<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Subrata Goswami on Medium]]></title>
        <description><![CDATA[Stories by Subrata Goswami on Medium]]></description>
        <link>https://medium.com/@whatdhack?source=rss-5a25f604a912------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Subrata Goswami on Medium</title>
            <link>https://medium.com/@whatdhack?source=rss-5a25f604a912------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:02:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@whatdhack/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LLM Assisted Kernel Development in CuTe DSL, Gluon, Helion and Triton .]]></title>
            <link>https://whatdhack.medium.com/llm-assisted-kernel-development-in-cute-dsl-gluon-helion-and-triton-f1bbb6cacaa3?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1bbb6cacaa3</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[triton]]></category>
            <category><![CDATA[nvidia-gpu]]></category>
            <category><![CDATA[cuda-programming]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 23:04:21 GMT</pubDate>
            <atom:updated>2026-10-03T23:04:21.728Z</atom:updated>
            <content:encoded><![CDATA[<p>Humans still have edge in crafting the most performant kernels. This edge is likely to erode within a year or so. Also, in the same spirit, a human crafted blog does not add as much value any more compared to language model chats — specially for the content/knowledge/tips that are dated and not novel or new.</p><p>With that said, I am going to go through my experiences with development a few kernels over the past few months. During that period AI coding agents made remarkable progress. The improvement in coding agent continues at breakneck pace — where there have progressed rapidly from writting a single funciton to several files in the span of a few months.</p><p>All the code, versions, utils, etc can be found in the <a href="https://github.com/whatdhack/llm-assisted-kernel-dev">companion repo</a>.</p><p><strong>Profilers, Debugging, Precisions:</strong></p><p>PyTorch profiler is good for figuring out overheads in inputs and cpu processing, but it has no visibility inside kernels. Nsight systems is similar , but includes processes beside PyTorch. Nsight compute provide PTX/SASS instruction level overview — however it could be difficult to use the information effectively.</p><p>Another alternative is to add custom profiling code — which I added and was helpful in optimizations of some kernels.</p><p>Debugging mostly involved tracking down correctness issues inside the gpu flows. It is often not possible to get a debug print in the middle, CPU style. Hence requires concocting unique tests that pinpoints the error root cause.</p><p>Because the hackathons used reduced precision, a handy quick reference of FP8 and FP4 follows. Reduced precision is an effective way to reduce compute and memory needs. BF16/FP16 has become the default. For inference and even for some training, 4 bit and 8 bit are currently considered mainstream. The following table compares 8 and 4 bits representations.</p><pre>+--------------------------------------------------------------------------------------------------+<br><br>| Attribute             | FP8 (E4M3 Variant)         | MXFP4 (OCP Spec)           | NVFP4 (NVIDIA)             |<br>+--------------------------------------------------------------------------------------------------+<br><br>| Bit-Width             | 8 bits                     | 4 bits                     | 4 bits                     |<br>| Element Bit Layout    | 1 Sign, 4 Exp, 3 Mantissa  | 1 Sign, 2 Exp, 1 Mantissa  | 1 Sign, 2 Exp, 1 Mantissa  |<br>| Element Bit Format    | E4M3 (or E5M2 for grads)   | E2M1                       | E2M1                       |<br>| Shared Scale Format   | N/A (Per-tensor / Scalar)  | E8M0                       | FP8 E4M3                   |<br>| Scaling Granularity   | Per-Tensor (Standard)      | Per-Block of 32 elements   | Per-Block of 16 elements   |<br>| Multi-Level Scaling   | No                         | No                         | Yes (Block E4M3 + Tensor)  |<br>| Standardizing Body    | OCP / IEEE                 | Open Compute Project (OCP) | NVIDIA                     |<br>| Hardware Baseline     | NVIDIA Hopper (H100+)      | Architectural Independent  | NVIDIA Blackwell (B200+)   |<br>| Primary Strengths     | High accuracy, generic     | High compression, open std | Extreme outlier retention  |<br>| Target Use Case       | Standard LLM Training      | Ultra-compact inference    | Native 4-bit Pre-training  |<br>+--------------------------------------------------------------------------------------------------+</pre><p>Three of the problems , Dual GEMM , Group GEMM and Cholesky , updated the leaderboard in realtime, hence was easy to track and update own progress relative to others. The fourth problem, MoE, was more opaque and updated infrequently, hence was almost impossible to track progress, let alone compare against others.</p><p><strong>Dual GEMM (NVFP4):</strong></p><p><em>C = silu(A @ B1) * (A @ B2)</em></p><p>Initially, I was under the impression that DGX Spark (sm120) is functionally equivalent to B200 (sm100). Hence made significant efforts towards optimizing the code for DGX Spark. There was no documentation on the differences at that time. Only later on, after many failed tries and communications on Nvidia forums, came to the realization that they are actually very different at all levels — all the way from silicon to cuda. The differences were eventually started to get documented several months later. That meant, I had to find B200’s , which were also scarce and expensive then.</p><p>Started out with the CuteDSL and torch code provided, <em>submission.py</em> and <em>reference.py</em> respectively . Both files went through multiple iterations where a number of new performance optimizations and debugging facilities were added. These derivations are called <em>dual_gemm_cute.py</em> and <em>dual_gemm_torch.py</em> .</p><p>Early on, tried the well known split-k technique and the intuitive merged-B on the torch version ,<em> dual_gemm_torch.py</em> . In merged-B, the B1 and B2 are concatenated along N and instead of 2 matmuls, only one matmul is executed. This saves on kernel launch overhead by one launch at the expense of extra throw away computations.</p><p>Adapted the source of <em>examples /blackwell /dense_blockscaled_gemm_persistent_prefetch.py</em> , which is for a single gemm, for the dual gemm problem. This derivation is called <em>dual_gemm_opt_cute.py</em>. Thus it brought in the following B200 hardware acceleration features to bear on the problem. In addition, added fairly extensive debugging instrumentation.</p><p><strong>1. Flat function vs. class-based persistent kernel</strong></p><ul><li>dual_gemm_cute.py: a plain @cute.kernel def kernel(...) + @cute.jit def my_kernel(...) — one CTA computes one output tile, straightforward launch-per-tile grid.</li><li>dual_gemm_opt_cute.py: wraps everything in class Sm100BlockScaledPersistentDenseGemmKernel, explicitly modeled on CUTLASS&#39;s &quot;persistent tile scheduling&quot; pattern — each CTA stays resident and loops over <em>multiple</em> output tiles (tile_sched_params: utils.PersistentTileSchedulerParams) instead of exiting after one tile. This amortizes launch overhead and keeps the cluster warm.</li></ul><p><strong>2. Warp specialization</strong></p><ul><li>Original: no distinct warp roles — all warps in the CTA largely follow the same path (warp_idx used only lightly, 3 hits).</li><li>Opt: explicit warp-role separation — e.g. a dedicated self.tma_warp_id that issues TMA loads/prefetches while other warps do MMA/epilogue, a classic producer/consumer warp-specialized pipeline.</li></ul><p><strong>3. TMA prefetching</strong></p><ul><li>Original: none — issues each TMA load and waits.</li><li>Opt: full prefetch_dist-controlled TMA descriptor + data prefetching, as described earlier — hides memory latency by loading future tiles&#39; descriptors/data ahead of the mainloop&#39;s actual need.</li></ul><p><strong>4. Separate SFB tiled-MMA</strong></p><ul><li>Opt’s kernel takes both tiled_mma <em>and</em> tiled_mma_sfb (a second MMA descriptor specifically for scale-factor B), plus a separate cluster_layout_sfb_vmnk — finer-grained handling of scale-factor tiling than the original&#39;s single shared layout.</li></ul><p><strong>5. C output via TMA + shadow-buffer handling</strong></p><ul><li>Original: writes C directly (no tma_atom_c in the kernel-level device args in the same way, simpler epilogue store).</li><li>Opt: takes an explicit tma_atom_c for the epilogue store, and the host-side custom_kernel has (now-disabled) shadow-buffer logic — code that used to allocate a separate correctly-typed/contiguous scratch tensor for C and copy back, added/removed across the a21d037→4bdd21d commits while chasing &quot;zero output&quot; and accuracy bugs.</li></ul><p><strong>6. Debugging/ops tooling</strong></p><ul><li>Opt adds run_with_compute_sanitizer, run_with_nsys, debug_main, profile_main — direct hooks for compute-sanitizer and Nsight Systems, absent from the original file entirely.</li><li>Used for tracking down TMEM overlap and SFA layout induced accuracy issue.</li></ul><p><strong>Group GEMM( NVFP4) :</strong></p><p>The essence of the PyTorch reference blockscaled group gemm is as follows. Essentially going through each matmul one by one in a for loop.</p><pre>def ref_kernel(<br>    data: input_t,<br>) -&gt; output_t:<br>    &quot;&quot;&quot;<br>    PyTorch reference implementation of NVFP4 block-scaled group GEMM.<br>    &quot;&quot;&quot;<br>    abc_tensors, sfasfb_tensors, _, problem_sizes = data<br>    <br>    result_tensors = []<br>    for i, (<br>        (a_ref, b_ref, c_ref),<br>        (sfa_ref, sfb_ref),<br>        (m, n, k, l),<br>    ) in enumerate(<br>        zip(<br>            abc_tensors,<br>            sfasfb_tensors,<br>            problem_sizes,<br>        )<br>    ):<br>        for l_idx in range(l):<br>            # Convert the scale factor tensor to blocked format<br>            scale_a = to_blocked(sfa_ref[:, :, l_idx])<br>            scale_b = to_blocked(sfb_ref[:, :, l_idx])<br>            # (m, k) @ (n, k).T -&gt; (m, n)<br>            res = torch._scaled_mm(<br>                a_ref[:, :, l_idx].view(torch.float4_e2m1fn_x2),<br>                b_ref[:, :, l_idx].transpose(0, 1).view(torch.float4_e2m1fn_x2),<br>                scale_a.cuda(),<br>                scale_b.cuda(),<br>                bias=None,<br>                out_dtype=torch.float16,<br>            )<br>            c_ref[:, :, l_idx] = res<br>        result_tensors.append((c_ref))<br>    return result_tensors</pre><p><strong>PyTorch Version:</strong></p><p>PyTorch already has support for NVFP4 matmuls as seen in the reference code above. The following call flow diagram shows how PyTorch _scaled_mm() calls cublas kernel.</p><pre>torch._scaled_mm()<br>  → _scaled_mm_out_cuda()          [ScaledBlas.cpp]<br>    → at::cuda::blas::scaled_gemm() [CUDABlas.cpp]<br>      → cublasLtMatmul()            [cuBLAS-Lt — final hardware call]<br><br><br>[1] Python Frontend (torch.nn.functional.scaled_mm)<br>        │<br>        ▼<br>[2] ATen Dispatcher C++ (at::_scaled_mm_v2)<br>        │<br>        ├───────────────────────────────────────────────────────┐<br>        ▼ (Eager/cuBLASLt Mode)                                 ▼ (Compiled / CuTe DSL Mode)<br>[3A] Eager Backend Dispatch                         [3B] TorchInductor AOT Compilation<br>     (at::native::scaled_mm_cuda)                        (at::native::cutlass_scaled_mm)<br>        │                                                       │<br>        ├───────────────────────┐                               ├───────────────────────┐<br>        ▼                       ▼                               ▼                       ▼<br>    [FP8 Path]             [NVFP4 Path]                     [FP8 Path]             [NVFP4 Path]<br>[4A] cublas_scaled_mm   [4B] cublas_scaled_mm       [4C] TorchInductor Template   [4D] CuTe DSL Backend<br>  (Per-Tensor/Row)        (Block Scaling + Swizzle)      (Fused Triton / CUTLASS)      (SfKMajorAtom Layout)<br>        │                       │                               │                       │<br>        ▼                       ▼                               ▼                       ▼<br>[5A] cublasLtMatmul     [5B] cublasLtMatmul         [5C] Triton / CUTLASS MMA     [5D] PTX mxf4nvf4 Inst.<br>        │                       │                               │                       │<br>        └───────────────────────┴───────────────┬───────────────┴───────────────────────┘<br>                                                ▼<br>                                    [6] GPU Hardware Launch <br>                                  (Tensor Core MMA Execution)</pre><p>Hence, one idea to try is to run a single large matmul. One way this is possible is by concatenating along the m dimension of (m, n, k) gemm (e.g. m x k @ k x n ), as only m differs in the group, and n and k stays same. This would save on kernel launch overhead, but would incur unnecessary computations as observed with dual gemm.</p><p>The Blackwell tcpgen05 (SM100a) tensor core MMA instruction for FP4 does not read scale factors from a simple row-major [M, K_sf] array. Instead, the hardware expects them in a tiled layout that matches the physical warp/register arrangement of the MMA atom — specifically the cuBLAS FP4 block-scaling layout documented in the NVIDIA cuBLAS docs.</p><pre>logical (i, j, b)  →  hardware [mm32, mm4, mm, kk4, kk, b]<br>where:<br>  mm   = i // 128        (which 128-row block)<br>  mm32 = i % 32          (row within the 32-row sub-tile)<br>  mm4  = (i % 128) // 32 (which row-group of 4)<br>  kk   = j // 4          (which K-block group)<br>  kk4  = j % 4           (position within K-group)</pre><p>Hence, another tweak is to use the pre-ordered scale factors already available as input — this obviated the need for calling to_blocked() within the outer loop of each gemm.</p><pre>Unordered (logical layout)<br>Shape: [M, K_sf, L] where K_sf = ceil(K / 16)<br><br>Example for M=128, K=256, L=1: [128, 16, 1]<br><br>Ordered (MMA-native hardware layout)<br>Shape: [32, 4, M_blk, 4, K_blk, L] where:<br><br>32 = rows within MMA atom (atom_m[0])<br>4 = column-groups within MMA atom (atom_m[1])<br>M_blk = ceil(M / (32×4)) = ceil(M / 128)<br>4 = K-groups within MMA atom (atom_k)<br>K_blk = ceil(K_sf / 4) = ceil(K / 64)<br>L = batch size<br>Example for M=128, K=256, L=1: [32, 4, 1, 4, 4, 1]<br><br></pre><p><strong>CuteDSL Single Warp Version:</strong></p><p>Using coding agent at the time to write CureDSL code from scratch was not feasible with the time and the compute budget I had. Hence, the first attempt was to improve the single warp example code <em>submission.py </em>.</p><p><strong><em>submission.py -&gt; group_gemm_cute.py :</em></strong></p><p>After adding modal benchmark harness, clock64 profiling instrumentation, etc as follows, the new file is called <em>group_gemm_cute.py</em>.</p><p><strong>Kernel changes:</strong></p><ul><li>Added debug_buf: cute.Tensor as a new kernel parameter (last arg)</li><li>Added clock64() DSL op (inline PTX mov.u64 %clock64) for cycle counting</li><li>Added t_init, t_start, t_end, t_epilogue_start/end timestamps wrapping the main loop and epilogue</li><li>Added wait_cycles and math_cycles accumulators inside the k-tile loop</li><li>Added writes to debug_buf[0..7] for thread 0 of block 0: timestamps, loop cycles, wait, math, epilogue, e2e</li><li>Added sentinel/block-presence writes: debug_buf[5] = 12345, debug_buf[100+bidz] = 1</li></ul><p><strong>Host changes:</strong></p><ul><li>my_kernel gets ptr_of_debug_buf: cute.Pointer; creates debug_buf tensor and passes it to kernel</li><li>compile_kernel cache key: f&quot;{len(problem_sizes)}&quot; → f&quot;{len(problem_sizes)}_v9&quot;</li><li>cute.compile gains options=&quot;--enable-tvm-ffi --opt-level 3&quot;</li><li>custom_kernel signature: (data) → (data, events=None, stats=None) — adds CUDA event timing and CustomStats side-channel</li><li>Added _dummy_debug_buf global: reused on non-profiled runs to avoid per-call allocation</li><li>Added new classes/functions: CustomStats, Stats, calculate_stats(), run_group_gemm_benchmark(), run_benchmark_suite(), Modal app+image, @app.function(gpu=&quot;B200&quot;), @app.local_entrypoint()</li></ul><p>A profile indicated significant CPU work ( ( 357–148) /357 ) — see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPiVKwzFeh64tN2L73xU-Q.png" /><figcaption>group_gemm_cute.py profile</figcaption></figure><p><strong><em>group_gemm_cute.py -&gt; group_gemm_cute2.py:</em></strong></p><p>In the next iteration, consolidated the three separate metadata tensors into one unified flat tensor in file <em>group_gemm_cute2.py .</em></p><p><strong>Kernel changes:</strong></p><ul><li>Removed three separate kernel args tensor_of_abc_ptrs (G,3), tensor_of_sfasfb_ptrs (G,2), tensor_of_problem_sizes (G,4)</li><li>Replaced with single tensor_metadata (G,9) where each row is [ptr_a, ptr_b, ptr_c, ptr_sfa, ptr_sfb, m, n, k, l] (all Int64)</li><li>Pointer reads: tensor_of_abc_ptrs[group_idx, 0] → tensor_metadata[group_idx, 0]; sfa/sfb → [3]/[4]</li><li>Problem size reads: tensor_of_problem_sizes[group_idx, 0] → cutlass.Int32(tensor_metadata[group_idx, 5]) — added explicit Int32 cast because the unified tensor is Int64</li></ul><p><strong>Host changes:</strong></p><ul><li>my_kernel parameters: 3 separate pointers → 1 ptr_metadata; tensor constructed as (G,9):(9,1)</li><li>compile_kernel passes 1 pointer arg instead of 3; same _v9 cache key and same options</li><li>custom_kernel: replaces tensor_of_abc_ptrs, tensor_of_sfasfb_ptrs, tensor_of_problem_sizes (3 separate torch tensors) with single tensor_metadata = torch.tensor(metadata_list, dtype=torch.int64) where each row packs all 9 values</li></ul><p>pyTorch profiler iteration span now includes some of cpu works — see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOQzEC75jNnPLxMXHmsAWg.png" /><figcaption>group_gemm_cute2.py profile</figcaption></figure><p><strong><em>group_gemm_cute2.py -&gt; group_gemm_cute4.py :</em></strong></p><p>Moved group dispatch from runtime GPU reads to compile-time tuple embedding — eliminating the metadata tensor entirely and caching per-problem-shape compiled specializations. <strong><em>group_gemm_cute4.py</em></strong> specializes a new compiled binary per distinct problem_sizes tuple (vs. group_gemm_<em>cute2/</em>group_gemm_<em>cute.py</em> reusing one binary per group count). This makes the GPU kernel statically know all group pointers, eliminating the tensor_metadata global memory read at runtime — at the cost of larger compile-time cache and recompilation when shapes change.</p><p><strong>Kernel changes (largest restructuring):</strong></p><ul><li>Kernel renamed kernel → kernel_gpu; JIT host renamed my_kernel → kernel_host</li><li>import cutlass.torch as cutlass_torch added; os.environ[&quot;CUTE_DSL_ARCH&quot;] = &quot;sm_100a&quot; moved to the very top (before any imports)</li><li>Kernel signature: tensor_metadata (G,9) removed entirely; replaced with per-group tuples baked in at compile time:</li></ul><pre>a_tuple: Tuple[cute.Tensor, ...],  b_tuple, c_tuple, sfa_tuple, sfb_tuple<br>m_tuple: Tuple[int, ...],  n_tuple, k_tuple, l_tuple</pre><ul><li>Group dispatch loop now selects from a_tuple[i], b_tuple[i], etc. via .iterator — no runtime device memory reads for pointers. Group pointers become compile-time constants embedded in generated PTX.</li><li>Pre-initialized dummy layout values (_m0 = m_tuple[0], etc.) added before the dispatch loop to satisfy JIT static analysis requirements.</li><li>tensormaps argument renamed to tensor_of_tensormap; cta_mn_list type changed from List[Tuple[int,int]] to Tuple[Tuple[int,int], ...]</li></ul><p><strong>Host changes:</strong></p><ul><li>compile_kernel(problem_sizes, sfa_tuple, sfb_tuple, total_num_clusters) — now needs actual sfa/sfb tensors to construct compile-time fake tensors with real shapes/strides</li><li>Cache key: f&quot;{len(problem_sizes)}_v9&quot; → f&quot;tuple_v2_{str(problem_sizes)}&quot; — keyed on exact shapes, so different problem dimensions produce distinct compiled specializations</li><li>compile_kernel builds per-group fake tensors via cute.runtime.make_fake_compact_tensor with actual m/n/k/l and sfa/sfb shape/stride; passes them as typed tuples to cute.compile</li><li>Added _kernel_metadata_cache dict: caches (total_num_clusters, tensormap_buffer, CuTe tensor tuples) keyed by problem_sizes, so per-invocation setup work (tensormap allocation, CuTe tensor creation) is done once per unique shape set</li><li>custom_kernel builds CuTe tensors from torch tensors per group before calling compiled_func, passing whole tuples directly</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLkAFbQ2R_TWlwnEQqgDdA.png" /><figcaption>group_gemm_cute4.py profile</figcaption></figure><p>This iteration sort of reached the limit of cpu related optimizations. This iteration also achieved the <a href="https://www.gpumode.com/leaderboard/730?tab=rankings">best score</a> out of all the versions I submitted. It was time to move on to a more complex CuTe DSL implementation.</p><p><strong>CuteDSL Warp Specialized B200 Version:</strong></p><p>For this effort, I started with the a kernel already available in the Cutlass repo — <em>cutlass/examples/python/CuTeDSL/blackwell/grouped_blockscaled_gemm.py</em> .</p><p>Some of the advanced features used in this kernel are :</p><ul><li><strong>Multiple software pipeline stages</strong> (num_ab_stage, num_acc_stage, num_c_stage) to overlap:<br> <strong>TMA loads</strong> of A/B/SFA/SFB with MMA compute (A/B pipeline)<br> <strong>MMA accumulation</strong> with epilogue readout (accumulator pipeline)<br> <strong>Epilogue TMA stores</strong> of C with the next MMA tile (C pipeline)</li><li><strong>Persistent Scheduling<br></strong>The kernel receives one group — a collection of GEMMs with heterogeneous (M, N, K) shapes. Rather than launching a separate kernel per GEMM, or sizing the grid to the largest GEMM, persistent scheduling treats the entire group as a single flat list of cluster-tile indices across all GEMMs, then launches a fixed pool of CTAs sized to hardware concurrency. <br>Each CTA loops over that flat list — using deterministic stride-based arithmetic to claim its next tile, doing a binary search each iteration to discover which GEMM within the group that tile belongs to. When a CTA crosses from one GEMM to the next, it reprograms the TMA descriptors for the new shape and data pointers. When the tile index exceeds the total tile count, the loop exits.<br>Pros:<strong><br> </strong>Zero kernel launch overhead between GEMMs, No SM idle time between GEMMs, Handles heterogeneous sizes gracefully, Better L2 / shared memory reuse across tiles, Amortizes fixed per-CTA setup costs.<br>Cons:<br> The kernel implements its own work distribution loop, group-boundary detection, dynamic tensormap updates, and pipeline tail handling, etc. -making the code significantly harder to write and debug than a simple tiled kernel.<br> Every time a CTA advances to the next tile, it searches through cumulative GEMM sizes to find which GEMM the new tile index belongs to. This is O(log N) per tile. For large groups with many GEMMs, this adds up.<br> The striped round-robin assignment (tile_index += grid_size) distributes tiles evenly in count but not in cost — a CTA that lands on tiles from the large (8192, 1280) GEMM does far more work than one landing on tiles from the small (32, 384) GEMM.<br> Grid sizing is tricky when shapes are unknown on host If GEMM shapes only exist on device (computed by a prior kernel), total_num_clusters cannot be computed on the host. The code falls back to launching max_active_clusters CTAs, which may be more than needed — some CTAs get no work and immediately exit.</li></ul><h4>Transition from grouped_blockscaled_gemm.py → group_gemm_cute5.py (3279 → 3849 lines) :</h4><p>The CUTLASS reference is a self-contained CLI benchmark. group_gemm_cute5 takes the same Sm100GroupedBlockScaledGemmKernel class and adapts it for hackathon submission (e.g. def custom_kernel()).</p><p><strong>Module-level additions</strong></p><ul><li>ensure_tvm_installed() — subprocess auto-installs apache-tvm-ffi if absent.</li><li>clock64() DSL op — @dsl_user_op using llvm.inline_asm for cycle-counter instrumentation.</li><li>New imports: from task import input_t, output_t, make_ptr, dsl_user_op, llvm, make_fake_compact_tensor, dataclasses.</li></ul><p><strong>__init__() changes</strong></p><ul><li>New num_groups: int parameter → self.num_groups; the reference doesn&#39;t store group count at init time.</li><li>num_tmem_alloc_cols: reference calls cute.arch.get_max_tmem_alloc_cols(&quot;sm_100&quot;); cute5 hardcodes SM100_TMEM_CAPACITY_COLUMNS = 512.</li></ul><p><strong>__call__() signature overhaul</strong></p><p>Per-group tensors:</p><ul><li>Reference: initial_a/b/c/sfa/sfb: cute.Tensor — a single &quot;template&quot; tensor per operand carrying only dtype and majorness ( dimension mode) in a layout that has a stride of 1) information</li><li>cute5: a_tuple, b_tuple, c_tuple, sfa_tuple, sfb_tuple — one tensor per group per operand; [0] is pulled for type info</li></ul><p>Group count:</p><ul><li>Reference: group_count: Constexpr[int] explicit parameter</li><li>cute5: removed — derived from self.num_groups</li></ul><p>Metadata arrays:</p><ul><li>Reference: problem_shape_mnkl, strides_abc, tensor_address_abc, tensor_address_sfasfb, tensormap_cute_tensor as cute.Tensor</li><li>cute5: same data passed as cute.Pointer (..._ptr variants) — reconstructed inside __call__ via cute.make_tensor with explicit strides</li></ul><p>Stream:</p><ul><li>Reference: stream: cuda.CUstream</li><li>cute5: removed as the hackathon only allowed implict use of the default stream; kernel launch omits stream</li></ul><p>Debug buffer:</p><ul><li>Reference: not present</li><li>cute5: debug_buf: cute.Tensor added as last parameter</li></ul><p>total_num_clusters / max_active_clusters:</p><ul><li>Reference: Constexpr[int]</li><li>cute5: plain Python ints</li></ul><p><strong>GPU kernel body — tile scheduler</strong></p><p>The reference uses StaticPersistentGroupTileScheduler (a single object that handles group-index resolution internally). cute5 splits this into two separate objects: StaticPersistentTileScheduler (produces flat tile coords) + GroupedGemmTileSchedulerHelper (resolves group index via .delinearize_z() in the TMA warp, .search_cluster_tile_count_k() in the MMA warp). Secondary effects:</p><ul><li>Reference hoists initial_work_tile_info = tile_sched.initial_work_tile_info() <em>before</em> the warp dispatch, so each warp branch guards if warp_idx == X and initial_work_tile_info.is_valid_tile:. cute5 acquires work tiles <em>inside</em> each warp branch with a bare if warp_idx == X:.</li><li>Reference TMA warp has an explicit is_k_tile_cnt_zero guard before TMA loads; cute5 removes it from the TMA warp.</li><li>Reference MMA warp also has if is_leader_cta and not is_k_tile_cnt_zero: before acc_pipeline.producer_acquire; cute5 drops the zero-tile guard.</li></ul><p><strong>Host-side harness additions</strong></p><ul><li>custom_kernel(data: input_t, events=None, stats=None) -&gt; output_t — contest entry point; accepts the standard input_t dict, unpacks tensors, launches kernel.</li><li>compile_kernel0() (aliased to compile_kernel) — compiles once per (len(problem_sizes),) key (group count only, shape-insensitive); stores in _compiled_kernel_cache.</li><li>_kernel_metadata_cache — separate cache for tensormap buffers and CuTe tensor tuples.</li><li>_dummy_debug_buf / _dummy_debug_ptr globals — reused across non-profiled calls to avoid ~3 µs make_ptr overhead per invocation.</li><li>CustomStats dataclass — pre_launch_cpu, post_launch_cpu, kernel_launch_overhead, e2e_cpu_time, debug_buffer fields.</li><li>make_ptr(dtype, addr, addr_space, align) used throughout to wrap raw device pointers for kernel call.</li><li>@app.function(gpu=&quot;B200&quot;) Modal harness + run_benchmark_suite() replaces the reference&#39;s if __name__ == &quot;__main__&quot; / run() CLI structure.</li></ul><h4>group_gemm_cute5.py → group_gemm_cute5_v2.py (3849 → 5516 lines):</h4><p>This is primarily a benchmarking infrastructure expansion.</p><p><strong>Two compile paths</strong></p><ul><li>compile_kernel_original — carries over cute5&#39;s approach.</li><li>compile_kernel_custom_kernel — alternative contest-ABI path; custom_kernel() uses this one (compile_kernel = compile_kernel_custom_kernel); the benchmark framework has a toggle.</li><li><strong>Cache key</strong>: compile_kernel_custom_kernel uses cache_key = tuple(problem_sizes) (exact shapes) vs cute5&#39;s (len(problem_sizes),) — different shapes trigger a full recompile.</li></ul><p><strong>ensure_tvm_installed tweak</strong>: cute5 checks for module tvm_ffi; cute5_v2 checks for tvm (minor module name drift).</p><p><strong>Cold-L2 benchmarking infrastructure</strong></p><ul><li>NUM_ITERATIONS_PER_BENCHMARK = 15 — batches 15 kernel launches per timing sample to amortize launch overhead.</li><li>15 pre-cloned datasets generated upfront; rotated in circular fashion so each timed launch hits fresh data in L2.</li><li>clear_l2_cache() — allocates then immediately frees a 160 MB CUDA tensor to flush L2 between timing samples.</li><li>_clone_data() — recursive deep clone (handles tuples, lists, dicts, tensors) for resetting between benchmark iterations.</li></ul><p><strong>New stats and test utilities</strong></p><ul><li>Stats.median: float field added; computed as durations[runs // 2].</li><li>test_custom_kernel_execution() — validates correctness against torch._scaled_mm using verbose_allclose, with configurable per-group A shapes (single_a flag for uniform vs mixed).</li></ul><p><strong>Additional Modal endpoints</strong></p><ul><li>run_bench_detailed.remote — per-shape detailed benchmark with cold-L2 and full stats reporting.</li><li>run_custom_kernel_test_remote.remote — remote correctness test.</li><li>cute5 had a single @app.function; v2 has three (bench, bench_detailed, correctness test).</li></ul><p><strong>from_dlpack vs </strong><strong>make_ptr</strong>: v2 shifts tensor construction from make_ptr(dtype, addr, ...) toward from_dlpack(torch_tensor, assumed_align=...) — the more canonical CuTe DSL idiom.</p><p>The following shows two PyTorch chrome trace profiles , one with the hackathon official profiler and the other a custom instrumented one. The custom one shows longer kernel times ( 33.24 vs 12.93 us) — probably due to the custom instrumentation added. However, the end to end iteration time for both are similar ~ 51.5 us !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mya1yJB4WXdX5WNJWva6lw.png" /><figcaption>group_gemm_cute5_v2.py hackathon official profiler trace</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8nqjuaXIsYFzj1gKMVp8g.png" /><figcaption>group_gemm_cute5_v2.py custom instrumented profiler trace</figcaption></figure><p>The following paragraphs explains some significant aspects and optimizations of the code.</p><p><strong>I: Pointer Tables, Tensormaps, and the Cost of Telling the GPU Where to Look</strong></p><p>In a grouped GEMM, each group has its own A, B, C, SFA, and SFB tensors living at different addresses in HBM. Before each kernel launch, the host copies two small tables to the GPU: one holding the A, B, and C base pointers for all groups (8 groups × 3 pointers × 8 bytes = 192 bytes), and another holding the SFA and SFB scale-factor pointers (8 groups × 2 pointers × 8 bytes = 128 bytes). These show up in a Chrome trace as two “Memcpy HtoD (Pageable → Device)” entries bracketing every kernel call — 30 copies for 15 back-to-back kernel invocations.</p><p>These pointer tables are distinct from the TMA descriptors (tensormaps). A tensormap is a 128-byte hardware data structure that encodes the full geometry of a tensor — its shape, stride, datatype, and swizzle pattern — plus a base pointer. The Blackwell TMA engine reads this descriptor to issue bulk asynchronous loads into shared memory without involving the scalar threads. For a grouped GEMM with five operands (A, B, SFA, SFB, C), there are five live tensormaps, each resident in shared memory. Crucially, these five descriptors are never transferred from host to device per call; they are initialized once and then updated on GPU-side using TensorMapUpdateMode.SMEM. A designated TMA warp reads the per-group pointer tables from global memory, writes the new base address into the in-SMEM tensormap for the current group, issues a fence, and then the MMA warps proceed with TMA loads — all without touching the host.</p><p>So the two HtoD copies per kernel call are not tensormap copies; they are the address book that the GPU uses to rewrite its own tensormaps. The kernel processes 8 groups serially, patching all five tensormaps (40 patch operations total) using this address book, so only five descriptors ever live at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8Cst6-Dg3dguHJ1cTYeZw.png" /><figcaption>Config 1 ( 8 mamutl group gemm)</figcaption></figure><p>As for the overhead: at 320 bytes total, the bandwidth cost is negligible — roughly 5 nanoseconds at PCIe 5.0. The real cost is the fixed per-transfer DMA setup latency of ~1–3µs, and the fact that the source buffers are pageable (not pinned), which forces an internal staging copy through a pinned bounce buffer before the DMA can fire. In practice, since these copies are issued non_blocking on the same CUDA stream as the kernel, the kernel queues behind them and can start as soon as the last copy completes. The trace shows whether there is any idle gap between the last HtoD and the kernel start — if that gap is under 0.2µs, the copies are already finishing in the shadow of the previous kernel and the overhead is effectively free. For a ~26µs kernel, the pointer-table copies are not the bottleneck; the dominant costs are MMA compute, TMA pipeline fill latency, and the group-loop serialization on the TMA warp.</p><p><strong>II: Tiling and Clustering: Shaping the MMA Wavefront</strong></p><p>mma_tiler_mn controls how large a tile each threadblock computes in the M and N dimensions. A tile of (128, 128) means each block owns a 128×128 output patch; (128, 256) doubles the N-coverage per block, and so on up to (256, 256). Larger tiles amortize the fixed cost of launching and synchronizing a block — fewer blocks are needed to cover the output matrix, and each block has more work to hide memory latency behind. The catch is occupancy: a (256, 256) tile demands more shared memory and registers, which can reduce the number of concurrent blocks the SM can hold, and for small-M problems the tile may simply be too large to divide the output evenly. There is also a hard constraint on Blackwell: if the M tile is 256, the cluster M dimension must be even, because the TMA multicast unit requires symmetric coverage across the cluster.</p><p>cluster_shape_mn moves up one level of the hierarchy, to <em>thread block clusters</em> — a Hopper/Blackwell feature that groups multiple blocks into a cooperative unit that shares a single TMA multicast. With cluster_n=2, two blocks that own adjacent N-panels broadcast the same A and SFA tiles across both via a single TMA load, halving the HBM bandwidth consumed by the read-only operands. This is most valuable when N is large: for the config with N=7168 across 8 groups, switching from cluster_shape_mn=(1,1) to (1,2) delivered a 15% speedup, because the A and SFA data being replicated across both blocks is exactly the bandwidth that was otherwise paid twice. Pushing to cluster_n=4 can help further, but only if N is large enough that four blocks can each fill their pipelines without the cluster-coordination overhead dominating; in practice it was neutral or slightly negative on the configs tested.</p><p>The interaction between the two knobs is what makes sweeping them jointly worthwhile. A (128, 256) tile paired with cluster_n=2 is a natural combination: the wider N tile means each block already loads a larger B slice, and the cluster multicast then broadcasts the A side across both blocks, so both sides of the GEMM benefit. A (256, 128) tile with cluster_m=2 follows the same logic in the M direction and is the right choice when M is the dominant dimension. The offline sweep over all 24 combinations — four tile shapes crossed with six cluster shapes — produces a small dispatch table keyed by (problem shape, num_groups), so the kernel selects the right configuration automatically at runtime without re-tuning on every run.</p><p><strong>III: Per-Config Dispatch: Locking in the Best Parameters Offline</strong></p><p>Running the sweep manually every time would be impractical, so the results are encoded into a static dispatch table keyed by the problem’s shape signature. The key is a frozenset of (N, K) pairs — capturing the distinct matrix dimensions present across all groups — combined with the number of groups. At kernel entry, _lookup_tuning hashes the incoming problem sizes against this table and returns the pre-determined (mma_tiler_mn, cluster_shape_mn) pair if there is a match, falling back to safe defaults ((128,128), (1,1)) for unseen shapes. This means the sweep is a one-time offline cost: run it once on representative inputs on the target hardware, read off the winning combo, and bake it into the table. The four competition configs were each swept across 24 combinations (four tile shapes × six cluster configurations), run in parallel as independent Modal functions on B200 instances, ranked by CUDA-event kernel time, and the winners committed directly.</p><p>The payoff was config-dependent and instructive. Three of the four configs — those with moderate N (≤4096) — saw negligible differences across tile shapes; the default (128,128)+(1,1) was already near-optimal because the output matrix is not wide enough for the larger tiles or cluster multicast to help. The outlier was the config with N=7168 across 8 groups: here (128,256)+(1,2) won by 15%, pulling that config from ~28µs down to ~24µs. The wider N tile kept the MMA units fed across a larger output panel, and cluster multicast halved the A/SFA bandwidth. Across all four configs, the dispatch table delivered an 8.5% geomean improvement over the flat default, essentially for free — the only runtime cost is a single dictionary lookup before the kernel compile cache is consulted.</p><pre>Full valid grid (cross product, constraint applied):<br><br>mma_tiler_mn   valid cluster_shape_mn<br>(128,128)       (1,1) (1,2) (1,4) (2,1) (2,2) (2,4) (4,1) (4,2)<br>(128,256)       (1,1) (1,2) (1,4) (2,1) (2,2) (2,4) (4,1) (4,2)<br>(256,128)       (2,1) (2,2) (2,4) (4,1) (4,2)<br>(256,256)       (2,1) (2,2) (2,4) (4,1) (4,2)<br>That&#39;s 26 combos total.</pre><p><strong>IV: Why the CPU Span Is 31ms but the GPU Span Is Only 758µs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52E7KXzdXMOKeL8pcDLnPA.png" /><figcaption>Fig X</figcaption></figure><p>When we open the Chrome trace in Perfetto, the first thing that jumps out is how long each benchmark_step_iter spans — roughly 31 milliseconds of wall clock per outer iteration for the eight-group 4096×7168 config. The GPU timeline within that span is packed almost entirely with distribution_elementwise_grid_stride_kernel — PyTorch&#39;s <em>randn</em> fill kernel, firing 32 times in sequence. This is the 62 GB L2 cache flush: a torch.randn((16000, 1024, 1024)) allocation that touches enough memory to evict every useful cache line from the 128 MB on-chip L2, ensuring the GEMM that follows sees a genuinely cold cache. At PCIe-constrained write bandwidth, filling 62 GB takes roughly 30.8 ms — about 98.7% of the entire iteration window.</p><p>The actual work is invisible at this zoom level. Only when we scroll to the very end of a benchmark_step_iter block and zoom in, do the real operations appear: 30 HtoD pointer-table copies and 15 GEMM kernels, the latter each taking about 26 µs, packed into a ~390 µs window at the tail end of the 31 ms span. The CPU-side picture makes the asynchrony explicit: all 30 cudaMemcpyAsync API calls cluster at the <em>beginning</em> of the benchmark_step_iter CPU row, because the Python loop over 15 data inputs submits all the work upfront in a fast burst. The GPU, however, can&#39;t start on those HtoD copies until the <em>randn</em> wave has cleared — so from the GPU&#39;s perspective the pointer copies and GEMM kernels don&#39;t appear until the very end of the wall-clock window. The trace is not showing a slow kernel; it is showing an intentionally brutal L2 flush regime, with the kernel itself taking a tiny sliver at the right edge of each iteration block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwXxQ9WYT--Hmeh5OpiMpA.png" /><figcaption>Fig X</figcaption></figure><p>The record_function label in the Chrome trace creates a CPU span and separately annotates only the GPU operations submitted <em>inside</em> that block. clear_l2_cache() is called <em>before</em> the record_function is entered, so the 32 <em>randn</em> kernels are not attributed to benchmark_step_iter_x on the GPU — they appear earlier on the GPU timeline, outside that label. What <em>is</em> inside the record_function are the 30 HtoD pointer copies and 15 GEMM kernels: together ~758µs.</p><p>The CPU span, however, is 31ms. That’s because torch.cuda.synchronize() inside the block waits for <em>everything</em> queued on the stream to finish — including the L2 flush that was submitted before the block started. The CPU is blocked for the full 31ms even though the GPU work attributed to that label is only 758µs. The 30ms gap is the CPU sitting idle, waiting for the GPU to drain a queue that was filled earlier.</p><p><strong>V: Three-Way Warp Specialization: TMA, MMA, and Epilogue</strong></p><p>Each threadblock in the kernel launches 192 threads — six warps — but they do not all run the same code. At startup, every thread reads its warp index and branches into one of three permanently distinct roles that it holds for the entire kernel lifetime. Warp 5 is the <strong>TMA warp</strong> (the producer), warp 4 is the <strong>MMA warp</strong> (the compute engine), and warps 0–3 are the four <strong>epilogue warps</strong> (the output writers). This is warp specialization: rather than every warp doing a little of everything, each warp does one thing only and the roles are connected by two explicit pipelines in shared memory.</p><p>The <strong>TMA warp</strong> runs the persistent tile scheduler, iterating over all output tiles assigned to this CTA across all groups. For each tile it determines which group it belongs to; if the group has changed since the last tile, it patches the five tensormap base pointers in shared memory (A, B, SFA, SFB, C) to redirect TMA loads to the new group’s HBM buffers. It then issues asynchronous TMA loads — A, B, SFA, SFB tiles — into a circular pipeline of shared memory staging buffers (the AB pipeline), acquiring an empty slot, filling it, and releasing it for the MMA warp to consume. The TMA warp is the only thread that touches the TMA hardware; the rest pf the threads do not issue a TMA instruction.</p><p>The <strong>MMA warp</strong> initializes the five tensormaps at startup (writing the initial descriptors into shared memory), then waits on the tensormap_ab_init_barrier to signal the TMA warp that initialization is done. It then enters its own loop: for each AB pipeline stage that the TMA warp fills, the MMA warp consumes it — issuing tcgen05 tensor core instructions that read from shared memory and accumulate into <strong>tensor memory (TMEM)</strong>, a new Blackwell-specific on-chip memory tier private to the warp. When an output tile is complete, the MMA warp releases it into the accumulator pipeline for the epilogue warps to drain.</p><p>The four <strong>epilogue warps</strong> wait on the accumulator pipeline. When the MMA warp signals that a tile’s accumulator is ready in TMEM, the epilogue warps cooperatively copy it — TMEM → shared memory → global memory . Four warps share this work to keep the store bandwidth high enough to not bottleneck the MMA warp.</p><p>The result is a three-stage software pipeline: TMA warp fetches tiles for group <em>i+1</em> while the MMA warp computes group <em>i</em>, and the epilogue warps write out group <em>i−1</em> — all overlapping in flight simultaneously, with named barriers and pipeline state machines as the synchronization fabric between them.</p><p><strong>VI: Tensor Memory: A New On-Chip Tier on Blackwell</strong></p><p>Tensor Memory (TMEM) is a new on-chip memory introduced in Blackwell (SM100) specifically to hold MMA accumulators and block-scale factors. On Hopper and earlier, the accumulator tiles lived in registers — which works for small tiles but causes register pressure and spilling as tiles grow. TMEM offloads this entirely: it has 512 columns of capacity per SM, is faster to access than shared memory for the MMA unit, and is invisible to the L1/L2 hierarchy.</p><p>Allocation and Pointer Sharing:</p><p>TMEM is physically private — only one warp can allocate it — but the address needs to be known by multiple roles. The allocation protocol reflects this: epilogue warp 0 calls alloc_tmem(512 columns, tmem_holding_buf), writing the resulting address into a small shared memory slot (tmem_holding_buf). The tmem_alloc_barrier then synchronizes all participating warps — MMA warp and all four epilogue warps — so each can call retrieve_tmem_ptr(tmem_holding_buf) to get the same physical address. From that point all roles work from the same TMEM region.</p><p>Layout: Three Packed Regions</p><p>The 512 TMEM columns are partitioned into three back-to-back regions using tcgen05.find_tmem_tensor_col_offset() to compute where each ends:</p><pre>| accumulator (tCtAcc) | SFA scale factors (tCtSFA) | SFB scale factors (tCtSFB) |<br>└──────────────────────┴────────────────────────────┴────────────────────────────┘<br>                         ← 512 TMEM columns total →</pre><p>Each region gets a typed CuTe tensor view (make_tensor) pointing into TMEM, with the layout computed from the MMA tile shape and scale factor vector size.</p><p>Usage in the MMA Loop</p><p>For each k-tile, the MMA warp:</p><ol><li>Copies SFA and SFB from shared memory into TMEM using tcgen05.Cp4x32x128bOp (a dedicated smem→tmem copy). The scale factors land in tCtSFA and tCtSFB.</li><li>Sets tiled_mma.set(Field.SFA, tCtSFA.iterator) and Field.SFB — telling the tcgen05 MMA unit where to find the block scales.</li><li>Sets ACCUMULATE=False for the first k-tile (zeroes the accumulator) then ACCUMULATE=True for all subsequent k-tiles (adds to it).</li><li>Issues cute.gemm(tiled_mma, tCtAcc, tCrA, tCrB, tCtAcc) — A and B tiles come from registers (tCrA, tCrB loaded from shared memory), the result accumulates into tCtAcc in TMEM.</li></ol><p><strong>VII: Readout by the Epilogue Warps:</strong></p><p>When the MMA warp finishes a tile and signals the accumulator pipeline, the epilogue warps use t2r (TMEM-to-register) copy to pull the accumulated results out of TMEM into their own registers, then stage them through shared memory and issue the final TMA store to global memory (C). After the last tile, the MMA warp calls relinquish_tmem_alloc_permit() and dealloc_tmem() to release the memory for reuse.</p><p>The net effect: the accumulator never touches registers during the MMA loop (eliminating register pressure entirely for the accumulator), and the epilogue warps can drain TMEM concurrently while the MMA warp has already moved on to the next tile’s k-loop — the two-stage accumulator pipeline makes this overlap explicit.</p><p><strong>Cholesky Lower Triangle Decomposition:</strong></p><p>The problem is to find the lower triangular matrix of a real symmetric and positive definite matrix.</p><pre>A = A^T<br>A = L * L^T </pre><p>The commonly used algorithm is Blocked Right-Looking Cholesky Factorization. The algorithm is described below. It uses a top-down, matrix-matrix multiplication approach designed to maximize CPU/GPU cache utilization.By shifting the bulk of the floating-point operations (O(n³) operations) to Step 3, the algorithm allows hardware to perform dense matrix multiplications.</p><pre>--------------------------------------------------------------------------------<br>1. MATRIX PARTITIONING SCHEME &amp; DERIVATION<br>--------------------------------------------------------------------------------<br>At any given step of the algorithm, the active trailing portion of the matrix <br>is conceptually partitioned into a 2x2 grid of blocks based on the current loop <br>index &#39;i&#39; and a chosen block width &#39;b&#39;:<br><br>    A = [ A11   A21^T ]<br>        [ A21   A22   ]<br><br>    A11: The active diagonal block of size b x b.<br>    A21: The vertical panel block sitting directly below A11, <br>         of size (n - i - b + 1) x b.<br>    A22: The remaining un-factored trailing submatrix sitting to the right <br>         and below A21, of size (n - i - b + 1) x (n - i - b + 1).<br><br>By setting A = L * L^T, we equate the partitioned blocks to derive the formulas:<br><br>    [ A11   A21^T ]   [ L11    0  ]   [ L11^T   L21^T ]<br>    [             ] = [           ] * [               ]<br>    [ A21   A22   ]   [ L21   L22 ]   [   0     L22^T ]<br><br>                      [ L11*L11^T       L11*L21^T       ]<br>                    = [                                 ]<br>                      [ L21*L11^T   L21*L21^T + L22*L22^T ]<br><br>--------------------------------------------------------------------------------<br>2. MATHEMATICAL STEPS<br>--------------------------------------------------------------------------------<br>By matching the blocks on both sides of the derived partitioning equation, the <br>factorization is broken down into three distinct computational phases per iteration:<br><br>    Step 1: Factor the Diagonal Block (Unblocked Cholesky)<br>            A11 = L11 * L11^T  =&gt;  L11 = Cholesky(A11)<br>            A standard, element-wise scalar Cholesky factorization is performed <br>            locally on the tiny b x b matrix A11 to compute L11 in place.<br><br>    Step 2: Solve the Panel (Triangular Solve)<br>            L21 * L11^T = A21  =&gt;  L21 = A21 * (L11^T)^-1<br>            The vertical panel A21 is updated by solving for L21. In high-<br>            performance software, this maps directly to the BLAS Level 3 TRSM <br>            (Triangular Matrix Solve) routine.<br><br>    Step 3: Update the Trailing Submatrix (&quot;Right-Looking&quot; Step)<br>            L22 * L22^T = A22 - L21 * L21^T  =&gt;  A22 &lt;- A22 - L21 * L21^T<br>            This is the defining &quot;right-looking&quot; action. The un-factored matrix <br>            A22 lying to the right and below is immediately modified by <br>            subtracting the outer product of the newly calculated panel. This <br>            maps directly to the BLAS Level 3 SYRK (Symmetric Rank-k Update).</pre><p>The reference example uses PyTorch’s <em>torch.linalg.cholesky_ex(data, check_errors=False).L</em> . Underneath it lands on cuSOLVER . Profiling with ncu, appears to confirm that it is using some form of the blocked Cholesky algorithm mentioned above.</p><p>The problem also required fp32 level accuracy, which precluded straight forward use of tensorcore or mma instructions. There is a triple tf32 trick that is used to retain fp32.</p><p>TF32 keeps FP32’s 8-bit exponent but truncates the mantissa from 23 bits to 10 bits — so a single TF32 matmul loses precision because both operands get truncated before hitting the tensor cores. The compensation trick: split each FP32 operand into two TF32-representable pieces. Algebraically that would result in 4 matmuls. However, dropping the tiny x_lo*y_lo term does not does not appear to impact accuracy enough to fail the tests.</p><p>The three TF32 matmuls accumulated together (all still using tensor cores, accumulating in FP32) instead of one — hence “3xTF32.” It recovers most of FP32’s precision (not bit-exact, but far closer than plain TF32) while still running at tensor-core throughput for each of the three passes, rather than falling back to CUDA-core FMA the way “ieee” does.</p><pre><br>x_hi = round_to_tf32(x)        # the part TF32 can represent<br>x_lo = round_to_tf32(x - x_hi) # the residual/error the truncation dropped<br><br>Then instead of one x*y ≈ x_hi*y_hi (losing the cross terms), compute:<br><br><br>x*y ≈ x_hi*y_hi + x_hi*y_lo + x_lo*y_hi     (dropping only the tiny x_lo*y_lo term)<br></pre><p>First attempt was the blocked Cholesky with Triton, and that leveled out at 2x geomean of the cuSOLVER version. Using the tf32x3 algorithm mentioned about above yielded about 5% better geomean. Triton Helion had issues in compiling the simple unblocked version on GB10 due to indexing errors. The next attempt was to use Triton Gluon. Gluon offers more lower level programmability — see the Appendix for a quick overview. The first Gluon version was built using fp32 compute with dot_fma, which does not use <em>tensorcores</em>. Then progressed through a number of tcpgen05 versions — persistent , warp specialized. It did better than the PyTorch reference kernel. The next implementation was a CuteDsl implementation. The first version did worse than Gluon. The ncu profiling was hard to translate to code changes. Use the newly released IKET profiler, which is a trace based profiler like nsys, hence much easier to reason about. The IKET profile indicated unnecessary serialization at TMEM. Eliminating that the CuteDsl kernel become as performant as the Gluon and the PyTorch CuSolver kernel. The following two figures show IKET traces of how warps were serializing vs overlapping after the TMEM fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAxgXayZRxyNiPnVuVsmpQ.png" /><figcaption>IKET trace before TMEM fix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U7psLXWIJQyngVvLpsXkA.png" /><figcaption>IKET trace after TMEM fix</figcaption></figure><p><strong>MoE ( FP8):</strong></p><p>The kernel code essentially need to implement an optimized version of the reference implementation. The reference implementation broadly has the following parts.</p><ol><li>Converts from fp8 ( activations , gemms) to fp32 before any execution.</li><li>A 2 stage token to expert routing logic. The experts are divided into 8 groups of 32 experts. The first stage selects 4 highest routing score groups of the 8 groups. The second stage selects 8 highest routing score experts out of the 4*32 experts ( <em>token_idx</em>) . The routing weights for the combine stage is a normalized score of the selected experts of a token ( <em>weights</em>).</li><li>Each of the selected 8 experts then filters in all the tokens that are routed to the expert. It then computes the gemm1 , swiglu, gemm2, multiplication by weight and accumulation over the selected tokens.</li></ol><p>The token routing algorithm is shown below in pseudo-code.</p><pre>INPUTS: logits[T, Eg], bias[Eg]<br>        TOP_K=8, N_GROUP=8, TOPK_GROUP=4<br><br>s            = sigmoid(logits)               # [T, Eg]<br>s_with_bias  = s + bias                      # [T, Eg]<br><br># Group the Eg experts into N_GROUP groups of (Eg/N_GROUP) each<br>s_grouped    = reshape(s_with_bias, [T, N_GROUP, Eg/N_GROUP])<br><br># Score each group by the sum of its top-2 expert scores<br>group_scores = top2(s_grouped, dim=expert).sum()   # [T, N_GROUP]<br><br># Keep only the best TOPK_GROUP groups per token<br>kept_groups  = topk(group_scores, k=TOPK_GROUP)    # [T, TOPK_GROUP] indices<br><br># Mask out experts not in a kept group, then pick global TOP_K experts<br>scores_masked = s_with_bias  (zeroed outside kept groups)<br>topk_experts  = topk(scores_masked, k=TOP_K)       # [T, TOP_K] indices<br><br># Routing weights: use s (no bias) for normalization<br>weights[t, e] = s[t, e]  if e in topk_experts[t]  else 0<br>weights       = normalize(weights, dim=expert) * routed_scaling_factor<br>                                                    # [T, Eg]</pre><p>The expert compute algorithm is shown below in pseuo-code. The gemm1 , swiglu, gemm2, multiplication by weights and accumulation</p><pre>INPUTS: A[T, H]  (dequantized hidden states)<br>        W13[El, 2I, H],  W2[El, H, I]  (dequantized weights)<br>        weights[T, Eg],  topk_experts[T, TOP_K]<br><br>output = zeros[T, H]<br><br>for each local expert le in 0..El:<br>    ge = local_expert_offset + le          # global expert id<br><br>    tokens = {t : ge ∈ topk_experts[t]}   # tokens that routed to this expert<br>    if tokens is empty: continue<br><br>    A_e  = A[tokens]                       # [Tk, H]<br><br>    # GEMM1<br>    G1   = A_e @ W13[le].T                # [Tk, 2I]<br><br>    # SwiGLU: gate × silu(up)<br>    gate, up = split(G1, dim=I)            # each [Tk, I]<br>    C    = silu(up) * gate                 # [Tk, I]<br><br>    # GEMM2<br>    O    = C @ W2[le].T                    # [Tk, H]<br><br>    # Weighted accumulation<br>    output[tokens] += O * weights[tokens, ge]<br><br>return output</pre><p>The reference code can be found in the <a href="https://github.com/whatdhack/flashinfer-bench-starter-kit/blob/main/solution/triton/moe_fibench_ref.py">repo</a>. It is pretty much the <a href="https://bench.flashinfer.ai/kernels/moe_fp8_block_scale_ds_routing_topk8_ng8_kg4_e32_h7168_i2048?">version found in the flashinfer leaderborad</a> with just a main() added.</p><p>Initial profiling of the reference kernel indicated 139.1/185.16 = 0.751 of the time is involved in scaling the FP8 activation and weights to FP32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rm0mvRJuemmLIZ8XBCPzew.png" /></figure><p>The obvious next step would be to not go through the FP8 to FP32 conversion. Unfortunately there is a accuracy constraint that has to be satisfied. The lower precision compute could not meet this goal. The tracks of these efforts are in the file<a href="https://github.com/whatdhack/flashinfer-bench-starter-kit/blob/main/solution/triton/moe_fp8fpX_fused.py"> <em>moe_fp8fpX_fused.py</em></a><em> </em>in the same repo. Also used <em>helion</em> to quickly get some optimization without much effort. These effort reduces the average time by about 30% . The following table lists some of the changes made.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0248428e0d56ad6afc6a69cd4252558d/href">https://medium.com/media/0248428e0d56ad6afc6a69cd4252558d/href</a></iframe><p>A further attempt was made to make a mega kernel. That did not work with Helion because of Helion’s type propagation only handles 2D tensor indexing with statically-known slice bounds. The grouped GEMM needs le = expert_ids[tile_m.begin] (a runtime tensor load) to compute weight row offsets like h_abs = le * H + tile_h.begin. That makes h_abs data-dependent, which triggers GuardOnDataDependentSymNode — Helion can&#39;t generate code for slices whose bounds aren&#39;t known at compile time.</p><p>Hence switched to Triton which handles pointer arithmetic natively. The mega-kernel ended by having worse performance than Helion because the activation tensor ( <em>a_tile</em>) is moved from global memory to shared memory multiple times ( e.g. range of the outer for loop). Due to time limits, had to stop optimizations at this stage.</p><p>All the coding and optimizations ( beyond Helion) for this kernel was mostly done by Claude Code with a few poking from me.</p><p><strong>Appendix:</strong></p><p><strong>TVM-FFI:</strong></p><p>Apache TVM FFI is an open Application Binary Interface (ABI) and Foreign Function Interface (FFI) designed specifically to standardize how machine learning (ML) systems, frameworks, and kernel libraries interact across language boundaries. It is a minimal, lightweight, and framework-agnostic convention that eliminates the traditional overhead and complexity of cross-language ML execution.</p><p>Core features:</p><ul><li><strong>Stable, Minimal C ABI</strong>: It provides a stable C target for domain-specific language (DSL) compilers and kernel builders. Compiled kernel libraries become completely independent of specific host languages, Python versions, or AI framework build variants. [<a href="https://tvm.apache.org/2025/10/21/tvm-ffi">1</a>, <a href="https://pypi.org/project/apache-tvm-ffi/">2</a>, <a href="https://tvm.apache.org/ffi/get_started/stable_c_abi.html">3</a>, <a href="https://tvm.apache.org/ffi/concepts/abi_overview.html">4</a>]</li><li><strong>“Ship One Wheel” Deployment</strong>: Because the generated libraries are decoupled from the Python ABI and specific framework versions, developers can compile a single shared library (.so or wheel). This single wheel works out-of-the-box across multiple Python versions (including free-threaded Python), PyTorch versions, JAX, and other environments. [<a href="https://github.com/apache/tvm-ffi">1</a>, <a href="https://tvm.apache.org/2025/10/21/tvm-ffi">2</a>]</li><li><strong>Zero-Copy Framework Interoperability</strong>: TVM FFI integrates first-class support for the <a href="https://github.com/dmlc/dlpack">DLPack protocol</a>. It allows high-performance tensor data to flow seamlessly between frameworks like PyTorch, JAX, CuPy, and NumPy without triggering expensive memory copies. [<a href="https://github.com/apache/tvm-ffi">1</a>]</li><li><strong>Ultra-Low Call Overhead</strong>: Eager kernel invocations from Python are optimized using type-erased “Packed Functions” and stack-allocated argument packing. This bypasses heap allocations and drastically minimizes host CPU overhead for latency-critical ML applications. [<a href="https://docs.nvidia.com/cutlass/latest/media/docs/pythonDSL/cute_dsl_general/compile_with_tvm_ffi.html">1</a>, <a href="https://syfeng.net/assets/talks/20251227-TVM-FFI:%20Open%20ABI%20and%20FFI%20for%20MLsys.pdf">2</a>]</li><li><strong>Multi-Language Bindings</strong>: It provides native, out-of-the-box support and abstractions for <strong>Python</strong>, <strong>C++17</strong>, and <strong>Rust</strong>. [<a href="https://github.com/apache/tvm-ffi">1</a>, <a href="https://github.com/apache/tvm-ffi/blob/main/CLAUDE.md">2</a>]</li></ul><p><strong>TensorMap:</strong></p><p>CUDA Tensor Map Descriptors are specifically engineered to program and interact with the <strong>Tensor Memory Accelerator (TMA)</strong> hardware introduced in NVIDIA Hopper (GH100) and Blackwell (GB200) GPU architectures.</p><p>Instead of requiring threads to compute complex index arithmetic manually, a TensorMap abstracts the multidimensional physical structure of a global memory tensor. This lets the TMA hardware handle bulk asynchronous data transfers directly between Global Memory (GMEM) and Shared Memory (SMEM)</p><p><strong>B200 (sm100) and DGX Spark ( sm120) differences:</strong></p><p>❖ 1. tcgen05 (Tensor Core Generation 05) Instructions</p><p>The B200 introduces the tcgen05 assembly instruction class to power fifth-generation Tensor Core operations. <strong>The DGX Spark does not support </strong><strong>tcgen05</strong>. [<a href="https://forums.developer.nvidia.com/t/does-b200-5090-support-tcgen05-ld-red/363672">1</a>, <a href="https://forums.developer.nvidia.com/t/fp4-on-dgx-spark-why-it-doesnt-scale-like-youd-expect/360142">2</a>, <a href="https://www.backend.ai/blog/2026-02-is-dgx-spark-actually-a-blackwell">3</a>]</p><ul><li><strong>tcgen05.mma (Asynchronous Matrix Multiply Accumulate)</strong>: This instruction drives the high-throughput matrix operations tailored for LLMs on the B200. On the DGX Spark, the compiler falls back to older generation MMA execution paths.</li><li><strong>tcgen05.ld and </strong><strong>tcgen05.st (Tensor Core Direct Load/Store)</strong>: These instructions bypass standard register files to stream weight tensors directly into execution units.</li><li><strong>tcgen05.cp.async (Asynchronous Tensor Copy)</strong>: Moves massive batches of multi-dimensional array slices natively across memory regions without consuming standard streaming multiprocessor (SM) warp processing cycles.</li></ul><p>❖ 2. Tensor Memory (TMEM) Instructions</p><p>The B200 contains <strong>Tensor Memory (TMEM)</strong> — a fast, dedicated physical memory space independent of standard Shared Memory/L1 cache built strictly for tensor operand staging. <strong>The DGX Spark lacks TMEM completely</strong>. Because there is no physical TMEM hardware on the Spark, the following PTX ISA instruction categories are rejected at the driver level: [<a href="https://forums.developer.nvidia.com/t/fp4-on-dgx-spark-why-it-doesnt-scale-like-youd-expect/360142">1</a>, <a href="https://www.backend.ai/blog/2026-02-is-dgx-spark-actually-a-blackwell">2</a>]</p><ul><li><strong>mov.tmem</strong>: Moving data between standard registers and Tensor Memory layout spaces.</li><li><strong>ld.tmem / </strong><strong>st.tmem</strong>: Direct, structured coordinate loading and storing inside the specialized tensor cache matrix.</li></ul><p>❖ 3. Native FP4/FP6 Processing Path (Hardware nvfp4)</p><p>The B200 features a hardwired math pipeline designed to execute arithmetic on 4-bit floating-point data natively. While you can feed FP4 checkpoints to a DGX Spark, it <strong>lacks the native FP4 compute path</strong>. [<a href="https://forums.developer.nvidia.com/t/nvfp4-on-dgx-spark-gb10-is-broken-i-bought-9-of-these-for-this-feature-requesting-nvidias-official-roadmap-and-response/367082">1</a>, <a href="https://forums.developer.nvidia.com/t/fp4-on-dgx-spark-why-it-doesnt-scale-like-youd-expect/360142">2</a>]</p><ul><li><strong>The Missing Instruction Behavior</strong>: On the B200, FP4 matrix operations execute directly via hardware math units. On the DGX Spark, because the underlying physical path is missing, FP4 data is dynamically <strong>dequantized up to FP8 or FP16</strong> inside registers before standard Tensor Cores can process the calculation. As a result, it does not achieve the expected 2x compute throughput scaling over FP8. [<a href="https://forums.developer.nvidia.com/t/fp4-on-dgx-spark-why-it-doesnt-scale-like-youd-expect/360142">1</a>]</li></ul><p>❖ 4. Hardware-Driven Async Copy &amp; Decompression Overrides</p><p>The B200 includes deep hardware-level asynchronous copy and custom scheduling descriptors linked to its 800 GB/s on-chip data decompression engine. [<a href="https://forums.developer.nvidia.com/t/does-b200-5090-support-tcgen05-ld-red/363672">1</a>, <a href="https://forums.developer.nvidia.com/t/fp4-on-dgx-spark-why-it-doesnt-scale-like-youd-expect/360142">2</a>]</p><ul><li>On the DGX Spark, bulk array data-movement functions rely on more standard software-managed memory pipelines, requiring a portion of the SM’s available <strong>Shared Memory (which is cut down to 99 KB on the Spark</strong> versus the massive 228 KB + 256 KB TMEM pool found on the B200). [<a href="https://forums.developer.nvidia.com/t/fp4-on-dgx-spark-why-it-doesnt-scale-like-youd-expect/360142">1</a>]</li></ul><p>❖ Real-World Software Impact</p><p>This split in supported assembly instructions causes prominent AI optimization frameworks to fail or behave differently across the two chips:</p><ul><li><strong>FlashMLA &amp; DeepSeek Kernels</strong>: DeepSeek’s FlashMLA and specialized low-latency attention mechanisms ship distinct backends. Their sm_100 kernels rely heavily on tcgen05 and TMEM. Running these on the DGX Spark throws a cudaErrorNoKernelImageForDevice or fails to compile because the sm_12x driver target cannot resolve the B200-specific instructions. [<a href="https://gromacs.bioexcel.eu/t/help-rtx-5080-blackwell-compute-capability-12-1-wsl2-cuda-13-0-no-kernel-image-available/12685">1</a>, <a href="https://www.backend.ai/blog/2026-02-is-dgx-spark-actually-a-blackwell">2</a>]</li><li><strong>vLLM Deployment</strong>: When running dense quantization on vLLM, the Spark cannot leverage the high-speed Triton hardware loops mapped to B200 instruction sets. Developers must fall back to software-based Marlin dequantization layers (VLLM_MXFP4_USE_MARLIN=1) to emulate the math. [<a href="https://github.com/vllm-project/vllm/issues/31085">1</a>]</li></ul><p><strong>New Micro-architecture features in Nvidia B200:</strong></p><p>❖ Dual-Die Coherent Architecture</p><ul><li>Unified Die Topography: Rather than a single reticle-limited chip, the <a href="https://www.google.com/search?ibp=oshop&amp;prds=pvt:hg,pvo:29,imageDocid:11614445246369124348,headlineOfferDocid:11034235067908513284,productDocid:11034235067908513284&amp;q=product&amp;sa=X&amp;ved=2ahUKEwi43IXqhdWUAxURHDQIHTW5MeAQxa4PegYIAAgQEAI">Blackwell B200</a> links two separate dies via a 10 TB/s NV-HBI (NVIDIA High Bandwidth Interface) according to official <a href="https://www.nvidia.com/en-us/data-center/technologies/blackwell-architecture/">NVIDIA Tech Documentation</a>.</li><li>Cache Coherency: The software layer recognizes the dual-chip design as a single, unified CUDA GPU, eliminating multi-die programming overhead as outlined in the <a href="https://developer.nvidia.com/blog/inside-nvidia-blackwell-ultra-the-chip-powering-the-ai-factory-era/">NVIDIA Developer Ecosystem</a> updates.</li><li>Transistor Density: Transistor count scales up to 208 billion on the custom TSMC 4NP process, compared to 80 billion on Hopper, a major manufacturing milestone reported by <a href="https://spectrum.ieee.org/nvidia-blackwell">IEEE Spectrum Hardware Review</a>.</li></ul><p>❖ 5th-Generation Tensor Cores &amp; Native FP4</p><ul><li>New Quantization Formats: Features built-in support for native 4-bit and 6-bit floating-point precision (FP4 and FP6) via its fifth-generation Tensor Cores as documented on <a href="https://en.wikipedia.org/wiki/Blackwell_(microarchitecture)">Wikipedia’s Blackwell Architecture Entry</a>.</li><li>Micro-Tensor Scaling: Features fine-grained micro-scaling factors that maintain model accuracy while doubling the computational throughput compared to standard FP8, according to the NVIDIA Product Suite. [, <a href="https://en.wikipedia.org/wiki/Blackwell_(microarchitecture)">2</a>]</li></ul><p>❖ 2nd-Generation Transformer Engine</p><ul><li>Tensor Memory (TMEM): Adds a specialized internal memory layout per Streaming Multiprocessor (SM) dedicated to storing and fast-tracking matrix-multiply-accumulate (MMA) operands, verified by early <a href="https://arxiv.org/html/2512.02189v1">arXiv Microbenchmarking Studies</a>.</li><li>Dynamic Range Management: Tracks and adjusts weights dynamically at the token and layer levels, maximizing throughput for Mixture of Experts (MoE) architectures during live model deployments. [<a href="https://arxiv.org/html/2512.02189v1">1</a>]</li></ul><p>❖ Streaming Multiprocessor (SM) Overhaul</p><ul><li>Pipeline Unification: Introduces unified INT32 and FP32 pipelines within the SM, allowing more flexible parallel processing configurations.</li><li>Shared Memory Modification: Retains flexibility in the L1/Shared Memory carveout, supporting scaling down to 128 KB or runtime adjustments as outlined in the <a href="https://docs.nvidia.com/cuda/blackwell-tuning-guide/index.html">NVIDIA CUDA Tuning Guide</a>.</li><li>Monolithic L2 Cache: Consolidates all SMs into a single, massive 65 MB monolithic L2 cache layout, replacing Hopper’s split two-partition design.</li><li>CTA Pairs: Optimizes the thread-block hierarchy by pairing two Cooperative Thread Arrays (CTAs) to share operands via an intra-TPC network, significantly cutting redundant data movement. [<a href="https://docs.nvidia.com/cuda/blackwell-tuning-guide/index.html">1</a>]</li></ul><p>❖ Hardware Decompression Engine</p><ul><li>I/O Offloading: Embeds a dedicated on-chip decompression engine capable of processing data at speeds up to 800 GB/s to free up host processors, as detailed in the <a href="https://docs.nvidia.com/cuda/nvcomp/decompression_engine_faq.html">NVIDIA nvCOMP API Specs</a>.</li><li>Native Format Support: Directly offloads data analytics workloads by natively decompressing LZ4, Snappy, and Deflate formats directly in transit. [<a href="https://docs.nvidia.com/cuda/nvcomp/decompression_engine_faq.html">1</a>]</li></ul><p>❖ 5th-Generation NVLink</p><ul><li>Doubled Interconnect Bandwidth: Moves from NVLink 4 to NVLink 5, pushing bidirectional GPU-to-GPU bandwidth to 1.8 TB/s per GPU (up from Hopper’s 900 GB/s) to scale out multi-node systems according to the <a href="https://nvidianews.nvidia.com/news/nvidia-blackwell-platform-arrives-to-power-a-new-era-of-computing">NVIDIA Platform Announcement</a>. [<a href="https://nvidianews.nvidia.com/news/nvidia-blackwell-platform-arrives-to-power-a-new-era-of-computing">1</a>]</li></ul><p><strong>Triton and Gluon Comparison :</strong></p><pre>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Technical Vector     | Triton (triton.language)  | Gluon on H100 (sm_90a)            | Gluon on B200 (sm_100)            | Gluon on GB10 (sm_121a)           |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Abstraction Level    | High-level SPMD           | Low-level hardware DSL            | Low-level hardware DSL            | Low-level hardware DSL            |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Hardware Layouts     | IMPLICIT: Managed by      | EXPLICIT: Declared manually       | EXPLICIT: Declared manually       | EXPLICIT: Declared manually       |<br>|                      | compiler                  | via gl.layout                     | via gl.layout                     | via gl.layout                     |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Memory Scheduling    | IMPLICIT: Managed via     | EXPLICIT: Tracked manually        | EXPLICIT: Tracked manually        | EXPLICIT: Tracked manually        |<br>|                      | num_stages                | using mbarrier clocks             | using mbarrier clocks             | using mbarrier clocks             |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Warp Management      | Unified warp path         | Explicit fork-join blocks         | Explicit fork-join blocks         | Explicit fork-join blocks         |<br>|                      |                           | (gl.warp_group/warp_specialize)   | (gl.warp_group/warp_specialize)   | (gl.warp_group/warp_specialize)   |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Architecture         | Abstracts math into a     | Invokes Hopper&#39;s wgmma.mma_async  | Invokes Blackwell&#39;s tcgen05.mma   | UNSUPPORTED: Must drop down to    |<br>| Intrinsics           | universal tl.dot()        | (Warp Group synchronous math)     | (Decoupled single-thread async)   | fallback mma.sync/mma.sp macros   |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| TMA Support          | Automated behind          | FULL: 1D/2D bulk global-to-SMEM   | FULL: Next-gen bulk transfers     | PARTIAL: Localized async loads to |<br>|                      | make_block_ptr loops      | transfers with multicast          | supporting both SMEM and TMEM     | local SMEM; no multicast/routing  |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| TMEM Allocation      | Not exposed               | UNSUPPORTED: Silicon tier missing | FULL: allocate_tensor_memory()    | UNSUPPORTED: Silicon missing;     |<br>|                      | (Restricted to registers) | (Uses registers)                  | manages 256KB matrix scratchpad   | accumulator falls back to regs    |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| DSMEM Controls       | Not exposed               | SUPPORTED: Cross-CTA reads/writes | FULL: High-bandwidth cross-SM     | UNSUPPORTED: Silicon cluster      |<br>|                      |                           | via localized SMEM bypassing      | memory mapping over cluster fabric| interconnect missing              |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+<br><br>| Multi-CTA            | Handled by global block   | SUPPORTED: Syncs multi-block      | FULL: Deep hardware-tracked       | UNSUPPORTED: Hardware constraints |<br>| Cooperation          | scheduler grids           | clusters using mbarriers          | cluster sync topologies           | fault if grid scales past 1 block |<br>+----------------------+---------------------------+-----------------------------------+-----------------------------------+-----------------------------------+</pre><p><strong>References:</strong></p><ol><li><a href="https://github.com/whatdhack/llm-assisted-kernel-dev">https://github.com/whatdhack/llm-assisted-kernel-dev</a></li><li><a href="https://www.gpumode.com/home">https://www.gpumode.com/home</a></li><li><a href="https://github.com/gpu-mode/reference-kernels.git">https://github.com/gpu-mode/reference-kernels.git</a></li><li><a href="https://bench.flashinfer.ai/kernels/moe_fp8_block_scale_ds_routing_topk8_ng8_kg4_e32_h7168_i2048?solutions=gpt-5-2025-08-07_cuda_a2d8ca%2Cgpt-5-2025-08-07_triton_e4fddf%2Cgpt-o3_triton_c1adb5%2Cclaude-opus-4-1-20250805_cuda_6c53f4%2Cclaude-opus-4-1-20250805_triton_c569cd&amp;p=0.95">https://bench.flashinfer.ai/kernels/moe_fp8_block_scale_ds_routing_topk8_ng8_kg4_e32_h7168_i2048</a></li><li>cuBLAS doc <a href="https://docs.nvidia.com/cuda/cublas/index.html?highlight=fp4#d-block-scaling-factors-layout">https://docs.nvidia.com/cuda/cublas/index.html?highlight=fp4#d-block-scaling-factors-layout</a></li><li>torch.scaled_mm <a href="https://docs.pytorch.org/docs/2.12/generated/torch.nn.functional.scaled_mm.html#torch.nn.functional.scaled_mm">https://docs.pytorch.org/docs/2.12/generated/torch.nn.functional.scaled_mm.html#torch.nn.functional.scaled_mm</a></li><li>Gpumode nvfp4_group_gemm hackathon whatdhack_ <a href="https://www.gpumode.com/leaderboard/730?tab=rankings">https://www.gpumode.com/leaderboard/730?tab=rankings</a></li><li>Microbenchmarking NVIDIA’s Blackwell Architecture: An in-depth Architectural Analysis, <a href="https://arxiv.org/html/2512.02189v3">https://arxiv.org/html/2512.02189v3</a></li><li>NVIDIA TESLA:AUNIFIED GRAPHICS AND COMPUTING ARCHITECTURE, <a href="https://www.cs.cmu.edu/afs/cs/academic/class/15869-f11/www/readings/lindholm08_tesla.pdf">https://www.cs.cmu.edu/afs/cs/academic/class/15869-f11/www/readings/lindholm08_tesla.pdf</a></li><li>Dissecting Nvidia Blackwell — Tensor Cores, PTX Instructions, SASS, Floorsweep, Yield, <a href="https://newsletter.semianalysis.com/p/dissecting-nvidia-blackwell-tensor">https://newsletter.semianalysis.com/p/dissecting-nvidia-blackwell-tensor</a></li><li>Inside NVIDIA Rubin GPU Architecture: Powering the Era of Agentic AI, <a href="https://developer.nvidia.com/blog/inside-nvidia-rubin-gpu-architecture-powering-the-era-of-agentic-ai/">https://developer.nvidia.com/blog/inside-nvidia-rubin-gpu-architecture-powering-the-era-of-agentic-ai/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1bbb6cacaa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Compute Parallelisms — Tensor, Sequence , Context, Pipeline, Expert, and Fully Sharded…]]></title>
            <link>https://whatdhack.medium.com/distributed-compute-parallelisms-tensor-sequence-context-pipeline-expert-and-fully-sharded-78a666e9080e?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a666e9080e</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[fsdp]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[tensor-parallelism]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 19:05:22 GMT</pubDate>
            <atom:updated>2025-08-31T19:05:22.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distributed Compute Parallelisms — Tensor, Sequence , Context, Pipeline, Expert, and Fully Sharded Data Parallel</h3><h3>The Resurgence of Parallel Computing</h3><p>Parallel computing is experiencing a significant resurgence after a hiatus of several decades. Its earlier popularity was driven by the need for more computational power than a single processor could provide. However, Moore’s Law, which enabled a doubling of compute density through miniaturization, largely eliminated the need for parallel computing for most tasks.</p><p>The landscape has changed in the last few years with the rise of Deep Learning models. Models for images, languages, and multi-modal tasks have grown in size and complexity, demanding extensive compute and memory, especially during training. This has made it impossible to fit many of these models onto a single GPU, leading to the current resurgence of parallel computing. Core principles from the earlier wave, such as <strong>MPI</strong> (Message Passing Interface) and <strong>CCL</strong> (Collective Communication Library), have been instrumental in scaling to the hundreds of thousands of GPUs currently in use, and soon to millions.</p><p>In essence, parallelism involves slicing models along different dimensions and distributing the computational load of each slice to a separate GPU. Since each GPU handles only a portion of the total computation, they cannot operate in isolation and require communication among themselves. Each type of parallelism offers a unique approach to ensuring the overall computation remains both correct and efficient.</p><p>To understand these various parallelization techniques, one must first grasp the <strong>Transformer Architecture</strong>. Therefore, we will begin with a detailed look at this architecture before diving into the specifics of the following topics:</p><ul><li>Comparison of Parallelization Techniques Brief</li><li>Tensor Parallelism (TP)</li><li>Sequence Parallelism (SP)</li><li>Pipeline Parallelism (PP)</li><li>Context Parallelism (CP)</li><li>Fully Sharded Data Parallelism (FSDP)</li><li>Backpropagation of Matrix Multiplication (Matmul)</li><li>Parallelization of Matmul (Tensor and Sequence Parallelism)</li><li>Parallelization Theory</li><li>PyTorch DTensor</li></ul><p>Due to the extensive material, a comparison section is provided at the beginning for quick reference.</p><h3>Comparison of Parallelization Techniques Brief:</h3><p>TP or SP requires more than 2.5 x communications compared to FSDP — 4 allreduces vs 1.5. FSDP can also prefetch multiple layers at a time. Hence, lends to compute-communications overlap optimizations. Whereas, TP/SP require layer by layer communications that are not amenable to prefetching. Hence, TP/SP are recommended for scale-up or within nodes where very high bandwidth links ( e.g. NVLink, Ultra Accelerator Link (UALink), Broadcom’s SUE) are available.</p><p>A key drawback of FSDP is that it suffers from activation memory replication, which means it requires significantly more memory</p><p>CP only shards input sequences and the KV cache. Sharding of rest of parameters and activation is left to TP/SP/FSDP. CP enables long context length.</p><p>PP uses point-to-point communications between ranks, hence requires careful tuning for balanced compute and communications.</p><p>FFN/MLP ( Feed Forward Network/Multi-Layer Perceptron) part of a Transformer Block accounts for 75% of parameters,. Going by C= 6N per token relationship (see end of this section, and Compute and Parameters section in <a href="https://medium.com/@whatdhack/revisiting-ai-scaling-law-5665250b41c3">this article</a> also ) also needs around 75% of compute. Mixture of Experts (MoE) evolved to contain that growth by only using a fraction of total FFN/MLP for each token. EP parallelizes along the MoE dimension. Llama4 Maverick uses 128 experts ,DeepSeek V3/R1 uses 256 experts. Although MoE reduces compute needs, it does not reduce memory needs.</p><p>The sharding strategies of a Transformer Block with TP, SP, CP, and FSDP are summarized in the following table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e6d5aa7792ff1f20be02f8eb0da2cf4/href">https://medium.com/media/0e6d5aa7792ff1f20be02f8eb0da2cf4/href</a></iframe><p>The following table summarizes memory usages, compute, and communications overhead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078a3c437e80048d79ee52ce8f5ee759/href">https://medium.com/media/078a3c437e80048d79ee52ce8f5ee759/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f36e0d278e8eec2732f86d23f2ed3a0d/href">https://medium.com/media/f36e0d278e8eec2732f86d23f2ed3a0d/href</a></iframe><p>The rational for a Transformer Block requiring 6N compute comes from the fact that a ( B*S) x H and H x H matmul flops is (B*S)*H*2H . Which with B ( batch size) =1 and S ( sequence length )=1 becomes 2*H*H. The second matrix represents parameters, hence N = H*H. Thus 2N flops in the forward direction. In the backward direction, similar sized gradient matmuls are involved for weights and activations — hence 4N flops. Summing up becomes 6N. A Transformer Block can be approximated as 4 or 5 matmuls — absolute size of N becomes about 4x or 5x, but the 6N expression does not change.</p><h3><strong>Transformer Architecture and Attention:</strong></h3><p>Most of the current work on parallelism focuses on Large Language Models (LLM). LLM’s are composed of long chains of Transformer Blocks ( or Layers). Transformer Blocks are composed of Self Attention (SA) and FFN or MLP with some (minor?) variations. Hence most of the analysis and results are based on the base Transformer Architecture. The following figure shows a Transformer Layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tN7hzuDA-slmAtsJQjWpuA.png" /><figcaption><strong>Fig TB: Transformer Block (or Layer) ( from the SP paper )</strong></figcaption></figure><p>The following figure shows the scaled dot-product and multi-head attention on a single process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*_kF5MUVTpEEqSfWEUo0OVg.png" /><figcaption>Fig SDPA: Multi-Head Attention (from the Attention Is All You Need paper)</figcaption></figure><p>The following code snippet shows a pure PyTorch and Python implementation of a basic self attention (mostly generated by AI and verified manually ) .</p><pre><br>def python_attention(query, key, value, mask=None):<br>    &quot;&quot;&quot;<br>    Computes scaled dot-product attention.<br><br>    Args:<br>        query (torch.Tensor): Query tensor of shape (batch_size, num_heads, seq_len_q, d_k).<br>        key (torch.Tensor): Key tensor of shape (batch_size, num_heads, seq_len_k, d_k).<br>        value (torch.Tensor): Value tensor of shape (batch_size, num_heads, seq_len_v, d_v).<br>        mask (torch.Tensor, optional): Optional attention mask.<br>                                       If provided, it should be broadcastable to the attention scores.<br><br>    Returns:<br>        torch.Tensor: Output tensor of shape (batch_size, num_heads, seq_len_q, d_v).<br>    &quot;&quot;&quot;<br>    d_k = torch.tensor(query.size(-1))<br><br>    # 1. Calculate attention scores (dot product of Query and Key)<br>    # (batch_size, num_heads, seq_len_q, d_k) @ (batch_size, num_heads, d_k, seq_len_k)<br>    # -&gt; (batch_size, num_heads, seq_len_q, seq_len_k)<br>    kt =  key.transpose(-2, -1)<br>    scores = torch.matmul(query, kt)<br><br>    # 2. Scale the scores<br>    scaled_scores = scores / torch.sqrt(d_k)<br><br>    # 3. Apply mask (optional)<br>    if mask is not None:<br>        scaled_scores = scaled_scores.masked_fill(mask == 0, float(&#39;-inf&#39;))<br><br>    # 4. Apply softmax to get attention weights<br>    attention_weights = F.softmax(scaled_scores, dim=-1)<br><br>    # 5. Multiply attention weights with Value<br>    # (batch_size, num_heads, seq_len_q, seq_len_k) @ (batch_size, num_heads, seq_len_v, d_v)<br>    # -&gt; (batch_size, num_heads, seq_len_q, d_v)<br>    output = torch.matmul(attention_weights, value)<br><br>    return output</pre><p>The following code snippet shows the Attention, Feed Forward and Transformer Block layers in the Llama3 model.</p><pre>class Attention(nn.Module):<br>    def forward( self, x: torch.Tensor, freqs_cis: torch.Tensor,):<br>        &quot;&quot;&quot;<br>        Forward pass of the attention module.<br><br>        Args:<br>            x (torch.Tensor): Input tensor.<br>            freqs_cis (torch.Tensor): Precomputed frequency tensor.<br><br>        Returns:<br>            torch.Tensor: Output tensor after attention.<br><br>        &quot;&quot;&quot;<br><br>        bs, seqlen, _ = x.shape<br>        xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)<br><br>        # Use -1 instead of `n_heads` (or `n_kv_heads`) to infer the actual<br>        # local heads from sizes of xq, xk, and xv as TP may have sharded them<br>        # after the above linear ops.<br>        xq = xq.view(bs, seqlen, -1, self.head_dim)<br>        xk = xk.view(bs, seqlen, -1, self.head_dim)<br>        xv = xv.view(bs, seqlen, -1, self.head_dim)<br><br>        xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)<br><br>        # repeat k/v heads if n_kv_heads &lt; n_heads<br>        keys = repeat_kv(xk, self.n_rep)  # (bs, seqlen, n_local_heads, head_dim)<br>        values = repeat_kv(xv, self.n_rep)  # (bs, seqlen, n_local_heads, head_dim)<br><br>        xq = xq.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)<br>        xk = keys.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)<br>        xv = values.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)<br><br>        output = self.sdpa(xq, xk, xv) #+ contains softmax dropout<br><br>        output = output.transpose(<br>            1, 2<br>        ).contiguous()  # (bs, seqlen, n_local_heads, head_dim)<br>        output = output.view(bs, seqlen, -1)<br>        return self.wo(output) #+ no dropout <br><br>class FeedForward(nn.Module):<br>    def forward(self, x):<br>        return self.w2(F.silu(self.w1(x)) * self.w3(x))<br><br>class TransformerBlock(nn.Module):<br>    def forward( self, x: torch.Tensor, freqs_cis: torch.Tensor,):<br>        h = x + self.attention(self.attention_norm(x), freqs_cis)<br>        out = h + self.feed_forward(self.ffn_norm(h))<br>        return out</pre><h3><strong>Tensor Parallel (SP):</strong></h3><p>Tensor Parallelism slices model parameter tensors along one dimension ( either column or row) of the tensors. As the following figure shows, both SA and MLP have two parts, with the right half being identical. The left half is also actually similar — with SA having three tensors ( Q, K, V) to slice to just one (A) in MLP. The left half is sliced along the column dimension for both Attention and MLP. The slicing of Attention is already done by multi-headedness. That makes the output of the left stage ( Y) sliced along the column dimension too. That also necessitates the right half tensors (B) to slice row-wise for the dot product to compute correctly (e.g. Y1 . B1 + Y2 . B2) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*2eXYTlv6R_GY9LUoyK8fJQ.png" /><figcaption>Fig X: Tensor Parallelism ( from the TP paper)</figcaption></figure><p>If A instead were sliced row-wise, we would have had X . [A1 A2]^T . That would have necessitated an extra allreduce after the left half to complete the dot product. The right half dot product would then have required an allgather or allreduce to complete depending on whether B is sliced column-wise or row-wise respectively. Shown in compact Linear Algebraic notation below.</p><pre>Y&#39; = X . [A1   = [X.A1<br>          A2 ]    X.A2 ]<br> <br>Y = allreduce-columnwise ( Y&#39;)<br><br>Z = Y .[ B1 B2 ]  = [Z1 Z2]  # column-wise sharding requires allgather <br>or<br>Z = Y .[ B1       = [Z1      # row-wise sharding requires allreduce<br>         B2 ]        Z2]</pre><p>Tensor parallelism can reduce the size of the matrix-multiplies, potentially reducing the throughput of modern GPUs, which often achieve higher throughput when performing larger matrix-multiplies.</p><p>TP compute and communications overlap techniques such as Async Tensor Parallel of PyTorch relies on breaking up the matmul into smaller blocks and thus creating opportunities for compute-communication overlap. Illustrated in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zTj5l7X_jcfN_HdT.png" /><figcaption>Fig AST: Async Tensor Parallel (from PyTorch blog )</figcaption></figure><h3><strong>Sequence Parallel (SP):</strong></h3><p>SP further reduces memory required per rank beyond TP. TP parallelizes model parameters, optimizer states and activations inside the attention and MLP blocks. However, TP leaves the layer-norms, dropouts, etc before and after attention and MLP blocks intact or unsharded. Input to the Q, K, and V matrix multiplies in attention block and input to the h → 4h MLP block are not parallelized. As a result, they are replicated across GPU’s. These elementwise layers are computationally light but demand considerable amount of memory for saving activation required for computation of gradient in the backward pass.</p><p>SP extends tensor parallelism by distributing computing and loading of activation memory across multiple GPUs along the sequence dimension. However, partitioning along sequence diagram would result in incorrect matmul/attention computation unless a collective is used to gather the complete activation into all the ranks — implying additional collectives. However, in SP , the authors cleverly take advantage of the fact that allreduce is composed of reduce-scatter and allgather. By diaggregating allreduce, they are able to keep communications overhead the same as in TP. The following shows these differences between TP and SP. The <em>f/f-hat</em> collectives in TP is replaced by <em>g/g-hat . </em>The input to SA and MLP is allgather’ed in the forward direction. This means, the input to these layers increase with longer sequence lengths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*l7hI5yjiqHrQ4U7IZAZo2w.png" /><figcaption>Fig TPSP: SP vs TP ( from the SP paper)</figcaption></figure><p>The following code snippet shows how PyTorch handles TP and SP. The snippet was extracted from the TP and SP examples in the <a href="https://github.com/pytorch/examples/tree/main/distributed/tensor_parallelism">torch/examples repo</a>. The input and output in case of SP is sharded. This is achieved in the following code block by generating different inputs and specifying to PyTorch it is so by setting input and output placement to Shard(0). Shard(0) because, 0 is the sequence dimension as there is no batch dimension used in the example. Dimension 1 can be considered the embedding dimension.</p><pre># Custom parallelization plan for the model<br>tp_model = parallelize_module(<br>    module=tp_model,<br>    device_mesh=device_mesh,<br>    parallelize_plan={<br>        &quot;in_proj&quot;: ColwiseParallel(),<br>        &quot;out_proj&quot;: RowwiseParallel(),<br>    },<br>)<br>for i in range(num_iters):<br>    # For TP, input needs to be same across all TP ranks.<br>    # Setting the random seed is to mimic the behavior of dataloader.<br>    torch.manual_seed(i)<br>    inp = torch.rand(20, 10, device=device_type)<br>    output = tp_model(inp)<br>    output.sum().backward()<br>    optimizer.step()<br>    rank_log(_rank, logger, f&quot;Tensor Parallel iter {i} completed&quot;)<br>    <br># Custom parallelization plan for the model<br>sp_model = parallelize_module(<br>    module=model,<br>    device_mesh=device_mesh,<br>    parallelize_plan={<br>        &quot;in_proj&quot;: ColwiseParallel(input_layouts=Shard(0)),<br>        &quot;out_proj&quot;: RowwiseParallel(output_layouts=Shard(0)),<br>    },<br>)<br><br>for i in range(num_iters):<br>    # For SP, input can be different across all ranks.<br>    inp = torch.rand(20, 10, device=device_type)<br>    output = sp_model(inp)<br>    output.sum().backward()<br>    optimizer.step()<br>    rank_log(_rank, logger, f&quot;Sequence Parallel iter {i} completed&quot;)</pre><h3><strong>Context Parallel ( CP):</strong></h3><p>CP partitions the network inputs and all activations along the sequence dimension for enabling long context length.</p><p>As mentioned previously, both TP and SP need the full sequence length of activation for SA and MLP. Splitting the sequence doesn’t affect most modules like dropouts and LayerNorm, where each token is processed independently. In the SA module, each token needs to access key/value pairs from all other sequence tokens or in the case of causal attention at least attends to each previous token. The Q (query) of each token needs to compute with the KV (key and value) of all tokens in the same sequence. Hence, CP requires additional all-gather across GPUs to collect the full sequence of KV. Correspondingly, reduce-scatter is applied to the activation gradients of KV in backward propagation.</p><p>In the following figure, SP groups are GPU0-GPU1 and GPU2-GPU3, and CP groups are GPU0-GPU2 and GPU1-GPU3. The yellow boxes are the allgather/reduce-scatter of the SP. This allgather/reduce-scatter is over the GPU’s of the TP group. The dark blue boxes are the allgather/reduce-scatter associated with CP. The CP allgathers/reduce-scatters are required because the projection tensors are colwise sharded, hence produces only a subset of columns. Moreover, the inputs are sharded in the sequence dimension. Hence the attention allgather needs to be over all the four GPU’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7sixfwG6L6cxWNbS.png" /><figcaption><em>Figure CP: A transformer layer running with TP2CP2. Communications next to Attention are for CP, others are for TP. (AG/RS: all-gather in forward and reduce-scatter in backward, RS/AG: reduce-scatter in forward and all-gather in backward, /AG: no-op in forward and all-gather in backward) (</em><a href="https://docs.nvidia.com/megatron-core/developer-guide/latest/api-guide/context_parallel.html"><em>from</em></a><em> Nvidia documentation) .</em></figcaption></figure><p>To reduce activation memory footprint, each GPU only stores the KV of a sequence chunk in forward direction and gathers KV again in backward. KV communication happens between a GPU and its counterparts in other TP groups. The all-gather and reduce-scatter are transformed to point-to-point communications in ring topology under the hood. Exchanging KV also can leverage MQA/GQA to reduce communication volumes, as they have n &gt; 1 attention heads per KV. This is the core of Ring Attention. Ring Attention shuffles the KV shards and calculates the partial attention scores, repeats until all KV shards have been used on each device. This shard shuffling can be done via either multiple p2p send/recv between devices, or one allgather as mentioned before. CP sequence length scaling is claimed to be zero-overhead if the shard rotation among devices overlaps well with the attention computation over local QKV shards.</p><p>The overview of Ring Attention algorithm is below:</p><pre># Ring Attention algorithm<br>N: number of devices where QKV is sharded.<br>Q_i; K_i; V_i: the QKV shard placed on device i<br><br># on device i<br>for j in 1..N:<br> Collect K_j and V_j from other device<br> Compute Attention(Q_i, K_j, V_j)</pre><p>If <em>is_causal=False</em>, in the attention/SPDA module, a sequential sharder is used, which shards one contiguous QKV block to each rank within the Context Parallel group. Sequential sharder evenly splits QKV into N contiguous blocks where N is the size of the Context Parallel group and shards one block to each rank. See the following comments lifted from <a href="https://github.com/pytorch/pytorch/blob/075a2e69678aa391259ceea33ee3c3c5f399562a/torch/distributed/tensor/experimental/_attention.py#L326">PyTorch implementation of Ring Attention.</a></p><pre>   Lifted verbatim <br>    Consider a scenario where the sequence length of q, k, and v is 4 (e.g.,<br>    q = (q0, q1, q2, q3)), and there are two ranks. For simplicity, we will discuss<br>    only q and k, as v follows the same pattern as k.<br><br>    The diagram below represents a complete QK^T operation without parallelism.<br>    The `****` entries indicate that the result is not required due to causal<br>    masking (e.g., q0k1 is marked as `****`).<br><br>    +----+------------------------+<br>    |    |  k0    k1   k2     k3  |<br>    +----+------------------------+<br>    | q0 | q0k0, ****, ****, **** |<br>    | q1 | q1k0, q1k1, ****, **** |<br>    | q2 | q2k0, q2k1, q2k2, **** |<br>    | q3 | q3k0, q3k1, q3k2, q3k3 |<br>    +----+------------------------+<br><br>    ### No Load Balance:<br><br>    In this scenario, each rank owns a local chunk of q, k, and v, with each chunk<br>    containing two elements. Rank0 is responsible for managing (q0, q1) and (k0, k1),<br>    while rank1 manages (q2, q3) and (k2, k3).<br><br>    First Iteration: Both rank0 and rank1 perform SDPA with their local qkv pairs.<br>    Causal masking is enabled as some results are not required (e.g., q0k1).<br><br>    Second Iteration: Local queries remain the same, but local kv pairs are exchanged.<br>    Rank0 now has (q0, q1) and (k2, k3); rank1 has (q2, q3) and (k0, k1). Rank0 performs<br>    no computation, while rank1 computes locally without causal masking since all results<br>    (q2k0, q2k1, q3k0, q3k1) are needed.</pre><p>A lower triangular masking is applied to the attention scores if the causal masking ( i<em>s_causal=True</em>) is specified, the local SDPA can be optimized to save computation by applying to a part of the QKV shard only. However, this leads to the imbalance of computation among local SDPAs, and hampers effective overlap of data communication and computation. To remedy this problem, PyTorch implemented a <a href="https://github.com/pytorch/pytorch/blob/075a2e69678aa391259ceea33ee3c3c5f399562a/torch/distributed/tensor/experimental/_attention.py#L337">Round Robin Load Balancer</a> which shards the shortest query block and the longest to rank 0, then the second shortest query block and the second longest to rank 1, and so on. The length variance of query blocks comes from the triangularity of the causal mask.</p><h3>Pipeline Parallel (PP):</h3><p>In Pipeline Parallel, the model is sharded in the layer dimension. The simplest PP algorithm/schedule is called GPipe. The following figure shows how the forward and backward pass progresses in GPipe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5TjKaMcDhfF5i3cjdb7kg.png" /><figcaption>Fig GP: GPipe PP ( from CMU slide)</figcaption></figure><p>Couple of things can be observed in the figure above — there are idle times, called bubbles and all the activations of a minibatch need to be retained for backward pass. The retention is longest for the first stage.</p><p>1F1B schedule improves upon this by doing one forward and one backward pass in the steady state. This reduces the memory requirement but does not reduce the bubble fraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6wiAizMW2hb7oEeDqUrJA.png" /><figcaption>Fig 1F1B: 1F1B compared to GPipe ( from CMU slides)</figcaption></figure><p>To reduce the bubble fraction, Interleaved 1F1B was proposed. Where each pipeline stage is further subdivided into sub-stages. Each device performs computation for discontinuous chunks of layers, instead of a single contiguous set of layers. For example, if each device had 4 layers before (i.e., device 1 had layers 1 − 4, device 2 had layers 5 − 8, and so on),<br>each device could perform computation for two model chunks (each with 2 layers), i.e., device 1 has layers 1, 2, 9, 10; device 2 has layers 3, 4, 11, 12 , etc. Hence, each device in the pipeline is assigned multiple pipeline sub-stages (each pipeline sub stage has less computation compared to stages before).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_B0kqce_d2RNTU0Ce_i3Q.png" /><figcaption>Fig I1F1B: Interleaved 1F1B PP schedule ( from CMU slides).</figcaption></figure><p>Summary of bubble and memory needs for some commonly used PP schedules follows.</p><p>GPipe — bubble fraction (p-1)/m, memory m<br>1F1B — (p-1)/m, p <br>Interleaved 1F1B — (p-1)/vm , p/v<br>ZB1P ( ZeroBubble ) — (𝑃 − 1) (𝐹 + 𝐵 − 2𝑊)/m(F+B), p <br>DualPipe — ( 𝑃𝑃 2 − 1) (𝐹&amp;𝐵 + 𝐵 − 3𝑊), p+1</p><p>In general partitioning of layers into stages requires manual intervention to keep computation balanced across ranks.</p><h3>Expert Parallel (EP):</h3><p>In dense deep learning models, where the entire model is activated for every example, leads to a roughly quadratic increase in training costs. As both the model size ( N ∝ h²) and the number of training tokens required ( ∝ N ) increase. The FFN part of a transformer block contains 3/4 th of the parameters (12h²) versus 1/4 in SA ( 4h²). As compute is proportional to parameters in Mixture of Expert ( MoE) exploits sparsity in FFN to contain computation. It divides the FFN into number of smaller FFN’s called experts. These experts are fronted by a gate or router that ususlly selects only a fixed size subset for activation. The router is usually a top-k selector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuOec44RU47MAN29FFHS0A.png" /><figcaption>Fig STM: Switch Transformer MoE</figcaption></figure><p>For example, the Llama 4 Maverick models have 17B active parameters and 400B total parameters. It uses alternating dense and mixture-of-experts (MoE) layers for inference efficiency. MoE layers use 128 routed experts and a shared expert. Each token is sent to the shared expert and also to one of the 128 routed experts. As a result, while all parameters are stored in memory, only a subset of the total parameters are activated while serving these models. This improves inference efficiency by lowering model serving costs and latency — as a result, Llama 4 Maverick can be run on a single NVIDIA H100 DGX host for easy deployment, or with distributed inference for maximum efficiency.</p><p>Llama 4 Scout, is a general purpose model with 17 billion active parameters, 16 experts, and 109 billion total parameters. Llama 4 Scout increases the supported context length from 128K in Llama 3 to 10 million tokens (?).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CI99tChZUIMndBtr" /><figcaption>Fig LMOE: Llama4 MoE</figcaption></figure><p>In expert parallel (EP), the experts are placed in different GPU’s. The router is crucial in keeping the GPU’s equally loaded as shown in the following figure. It was found that during training, tokens tend to propagate to a few experts thus causing an imbalance and routing collapse to one expert. The collective associated with EP is generally 2 all-to-alls. Intuitively, this is because the router in a GPU/rank may send token to the appropriate expert residing on a different GPU/rank, which after processing sends it back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2sKk10ybedbOtprGsQz4A.png" /><figcaption>Fig EPI: Expert parallelism imbalance issue (CMU slide deck)</figcaption></figure><p>The Mixture-of-Experts (MoE) layer consists of a set of n “expert networks” E1, · · · , En, and a “gating network” G whose output is a sparse n-dimensional vector. The following figures show the output and router function used in <strong>Switch Transformer</strong>. The authors enhanced the simple Softmax Gating function with sparsity and noise, and called Noisy Top-k Gating. Sparsity reduces compute needs and noise helps in load balancing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bLYvRomzSRYoMaLDaIJYw.png" /><figcaption>Fig STA: Switch Transformer gating/router function algebraic expression.</figcaption></figure><p>To address the imbalance issue, they defined the importance of an expert relative to a batch of training examples to be the batchwise sum of the gate values for that expert. They defined an additional loss, <em>Limportance</em>, which is added to the overall loss function for the model. This loss is equal to the square of the coefficient of variation (<em>σ</em>​/<em>μ) </em>of the set of importance values, multiplied by a hand-tuned scaling factor <em>wimportance</em>. This additional loss encourages all experts to have equal importance. The higher the variance, larger is the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*GNhcCZrz8dCzomgOSPEaqg.png" /><figcaption>Fig IL: Switch Transformer importance loss</figcaption></figure><p>While <em>Limportance</em> function can ensure equal importance, experts may still receive very different numbers of examples. For example, one expert may receive a few examples with large weights (e.g. <em>G(x)</em> large), and another may receive many examples with small weights. This can cause memory and performance problems on distributed hardware. To solve this problem, they introduced a second loss function, <em>Lload</em> , which ensures balanced loads. As the number of examples received by an expert is a discrete quantity, hence not differentiable, the authors instead introduced a smooth estimator, <em>Load(X)</em>, corresponding to the number of examples to compute the <em>Lload</em>. <em>Lload </em>increases with variation of <em>Load</em> ,which in an estimator of number of samples assigned to an expert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*xlPk_kphoVyvfYPQgWh2kQ.png" /><figcaption>Fig STLL: Switch Transformer load loss</figcaption></figure><p>Meta’s Llama4 does not use a loss based load balancing, but relies on auxiliary loss free load balancing strategy. Although, the auxiliary losses introduced in the Switch Transformer paper addresses load imbalance during training, they also introduce undesired gradients that conflict with the language modeling objective. In the loss free load balancing scheme, a bias, <em>bi</em>, term is added to the gating score <em>s(i,t)</em> . The bias term is increased if the expert received more tokens and vice-versa. The bias term is only used for selecting token, and not used in the computation of output (<em>hi</em>) for input <em>ui</em>. Also, the updated bias term is used in the next iteration. If the bias term is large, then the gating factor can become 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*B126IQcnXCMjAU8tfwLThg.png" /><figcaption>Fig LFLB: Loss-free Load Balancing</figcaption></figure><p>In Llama4 , the input to EP ( <em>_token_dispatch </em>for sharing<em> </em>) and output of EP (<em>_token_combine </em>for returning<em> </em>) are handled by alltoall. The following code snippet shows the Llama4 EP.</p><pre>class ExpertParallel(ParallelStyle):<br>    def __init__(self):<br>        super().__init__()<br>        self.input_splits = None<br>        self.output_splits = None<br><br>    # performing all-to-all dispatch on the input<br>    def _token_dispatch(self, mod, inputs, device_mesh):<br>        # annotate module input placements/sharding with input_layouts<br>        routed_input, num_tokens_per_expert = inputs<br><br>        # generate the input splits and output splits for all-to-all<br>        with torch.no_grad():<br>            num_tokens_per_expert_group = num_tokens_per_expert.new_empty(<br>                num_tokens_per_expert.shape[0]<br>            )<br>            dist.all_to_all_single(<br>                num_tokens_per_expert_group,<br>                num_tokens_per_expert,<br>                group=device_mesh.get_group(),<br>            )<br>            # NOTE: this would incur a device-to-host sync<br>            self.input_splits = (<br>                num_tokens_per_expert.view(device_mesh.shape[0], -1).sum(dim=1).tolist()<br>            )<br>            self.output_splits = (<br>                num_tokens_per_expert_group.view(device_mesh.shape[0], -1)<br>                .sum(dim=1)<br>                .tolist()<br>            )<br><br>        # perform all-to-all<br>        routed_input = all_to_all_single_autograd(<br>            routed_input,<br>            self.output_splits,<br>            self.input_splits,<br>            device_mesh.get_group(),<br>        )<br><br>        # NOTE: After this all-to-all, the routed input is put on proper EP rank.<br>        # However, the num_tokens_per_expert_group is not of the final target format<br>        # [#tokens for local expert 0, #tokens for local expert 1, ...]<br>        # Rather, it is of the format<br>        # [#tokens for local expert 0 from EP rank 0, #tokens for local expert 1 from EP rank 0, ...,<br>        #  #tokens for local expert 0 from EP rank 1, #tokens for local expert 1 from EP rank 1, ...]<br>        # We need to perform another shuffle to get the correct format -- this is done via the function<br>        # generate_permute_indices in moe.py, which also does padding to make sure the number of tokens<br>        # each expert gets locally is a multiple of ALIGN_SIZE_M.<br><br>        return routed_input, num_tokens_per_expert_group<br><br>    @staticmethod<br>    def _partition_fn(name, mod, device_mesh):<br>        # shard on the expert dimension<br>        for name, param in mod.named_parameters(recurse=False):<br>            dist_param = nn.Parameter(distribute_tensor(param, device_mesh, [Shard(0)]))<br>            mod.register_parameter(name, dist_param)<br><br>    # performing all-to-all combine on the output<br>    def _token_combine(self, mod, routed_output, device_mesh):<br>        routed_output = all_to_all_single_autograd(<br>            routed_output,<br>            self.input_splits,<br>            self.output_splits,<br>            device_mesh.get_group(),<br>        )<br>        return routed_output<br><br>    def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -&gt; nn.Module:<br>        return distribute_module(<br>            module,<br>            device_mesh,<br>            partition_fn=ExpertParallel._partition_fn,<br>            input_fn=self._token_dispatch,<br>            output_fn=self._token_combine,<br>        )</pre><h3>Fully Sharded Data Parallel (FSDP):</h3><p>FSDP is a Data Parallel technique. The main difference with plain Data Parallel is that the parameters, gradients and optimizer states are sharded. Hence parameters, gradients and optimizer state need to be gathered at each rank before a layer is executed. Sharding reduces the memory needed at each rank, hence a larger model can be trained. It is similar to DeepSpeed ZeRO stage 3 .</p><p>The following figure shows the FSDP used in PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h-sNLklA7ZxUw2-6.png" /><figcaption>Fig FSDP: FSDP in PyTorch</figcaption></figure><p>At a high level PyTroch FSDP works as follow:</p><p>In constructor:</p><ol><li>Shard model parameters, and each rank only keeps its own shard</li></ol><p>In forward path:</p><ol><li>Run allgather to collect all shards from all ranks to recover the full parameter in this FSDP unit</li><li>Run forward computation in data parallel ( e.g. uses only local data).</li><li>Discard parameter shards it has just collected</li></ol><p>In backward path:</p><ol><li>Run allgather to collect all shards from all ranks to recover the full parameter in this FSDP unit</li><li>Run backward computation. Computes local gradients.</li><li>Run reduce_scatter to sync gradients. In data parallel, each ranks computes gradients for every parameter and activation. Hence, these need to be averaged. Each rank is required to have the average of gradients of parameters it is custodian of—hence, reduce-scatter. Once the averaged parameter gradients are available, local parameters are updated. The activation gradients need not be shared hence remain local. At the same time, local optimizer states are updated. Optimizer states are not needed to be communicated to other ranks.</li><li>Discard parameters.</li></ol><p>FSDP shards in units. Each unit handles a number of layers. Each GPU holds a part of the unit parameters, grads and optimizer states.</p><p>Forward pass starts at the first FSDP units. Each GPU allgathers the parameters of each layers of the unit and generates activatiuons for each layer of the unit.</p><p>Activations for FSDP unit is different for different GPUs as input data is different, hence has to be retained for the backward pass.</p><p>Each GPU removes the model parameter shards it is not responsible for to free up memory.</p><p>The forward pass then moves onto the next FSDP unit. An allgather for the second unit collects all the parameters into all the units. And so on till the last unit.</p><p>The backwards pass starts with loss calculation. The loss is calculated on each GPU independently after the last FSDP unit completes forward pass.</p><p>The loss and activations along with parameters in the last unit is used for calculating the gradient for weight and input on GPU individually. The last layer of the last unit uses the loss for gradient calculations. The rest of the layers of the unit uses the activations for gradient calculations. Each GPU calculates gradients for every shard as an allgather was called before. Hence, each GPU needs to do an average over the shards from the other GPUs to update the gradient shard it is responsible for. This is done through reduce-scatter. After this, each GPU removes all the parameter and gradient shards it is not responsible for.</p><p>The backward pass then propagates to the next to last unit. The parameter shards were removed after the forward pass completed for this unit. Hence an allgather is use to recollect the parameters for all shards into each GPU. After this the gradient calculation proceeds.</p><p>Once the backward pass completes gradient calculations of the first unit, the optimizer step runs in parallel independently for each each parameter update. Optimizer state size is twice the size of parameters ( e.g. 2 optimizer parameter for each model parameter). Optmizer state updates are per model parameters, hence does npot require any collectives.</p><p>One way to view FSDP’s sharding is to decompose the DDP gradient all-reduce into reduce-scatter and all-gather. Specifically, during the backward pass, FSDP reduces and scatters gradients, ensuring that each rank possesses a shard of the gradients. Then it updates the corresponding shard of the parameters in the optimizer step. Finally, in the subsequent forward pass, it performs an all-gather operation to collect and combine the updated parameter shards.</p><p>The original implementation, FSDP1, in PyTorch suffers from various limitations due to its FlatParameter implementation. FSDP2, which uses the per-parameter Distributed Tensor sharding representation and thus provides better composability with model parallelism techniques and other features that require the manipulation of individual parameters,</p><p>Pros and cons:</p><p>It is possible to pre-prefetch ( allgather) the next FSDP unit ( layers) parameters during forward pass and backward pass. However, activation memory is replicated.</p><h3><strong>Backpropagation of Matmul:</strong></h3><p>Back propagation relies on Chain Rule of multi-variable derivatives as follows.</p><p><em>y = f ( g(t), h(t))</em></p><p><em>dy/dt = df/dg . dg/dt + df/dh . dh/dt</em></p><p>For a matmul, the derivatives can be derived as follows.</p><p><em>Y= X.W + B</em></p><p><em>yj = fj(..,xi,..,wkl,..,bj) = …+xk.wkj+…</em></p><p><em>L(Y) = L(..,yi,…)</em></p><p><em>dL/dxi = d/dxi ( L(..,yj ,…) ) = d/dxi ( L(..,fj(..,xi,..,wkl,.., bj) ,…) ) = …+ dL/dfj . dfj/dxi+… = …+ dL/dyj . wij + … =&gt; dL/dY . W^T</em></p><p>For matmul, the derivative, dfj/dxi, is just wij . As wij’s are independent of xi’s, hence dL/dfj . dfj/dwkl . dwkl/dxj ‘s are all 0’s. As the above summation is over the second index of wij, hence it is over the i’th row of W or i’th column of W^T.</p><p>Similarly for parameters, <em>wkl.</em></p><p><em>dL/dwkl = d/dwkl ( L(..,yj ,…) ) = d/dwkl ( L(..,fj(..,xi,..,wkl,..,bj) ,…) ) = <br>…+ dL/dfj . dfj/dwkl+… = …+ xk . dL/dfj +… = xk.dL/dfl</em></p><p>For matmul, the derivative of dfj/wkl is just xk when j = l, else 0 .</p><p>And similary for bias, <em>bj.</em></p><p><em>dL/bj = d/dbj ( L(..,yj ,…) ) = d/dbj ( L(..,fj(..,xi,..,wkl,..,bj) ,…) ) = <br>…+ dL/dfj . dfj/dbj+… = … +dL/dfj + … =&gt; dL/dY</em></p><p>Bias , <em>bj</em>, is just a variable added to rest of <em>fj</em>. Hence <em>dfj/dbj</em> is 1.</p><p>In Linear Algebraic Notations:</p><p>The above can be compactly captured into the following Linear Algebraic notations.</p><p><em>Y= X.W + B # matmul with bias <br>L(Y) # loss , function of all yj’s</em></p><p><em>dL/dX = dL/dY . W^T</em></p><p><em>dL/dW = X^T . dL/dY <br># X(1,m).W(m,n) = X.W ( 1,n), <br># X^T (m,1) . dL/dY (1,n) = X^T . dL/dY ( m,n)</em></p><p><em>dL/dB = dL/dY</em></p><p>Optimizer’s take the derivatives and updates the xi’s (activations), wkl’s (weights) and bj’s ( biases). A simple Stochastic Gradient Descent ( SGD) ( e.g. no momentum) update is as follows. Hence once we can calculate the derivative, we can update the parameter or activation.</p><p><em>wkl = wkl — lr . dL/dwkl</em></p><h3><strong>Parallelization of Matmul ( Tensor and Sequence Parallel):</strong></h3><p>This section is subdivided into Math, Visualization and Code sub-section. The Code and Visualization sub-section goes over TP on 2 ranks in detail.</p><p><strong>Linear Algebra:</strong></p><p>In case of 2 rank Tensor Parallel, we have the following expressions for a matmul.</p><p>Column-wise partitioning:</p><pre>[Y1 Y2] = X. [W1 W2] + B<br>Y = allgather ( [Y1 Y2] ) <br>L(Y)</pre><pre>dL/dX = dL/dY . W^T = dL/dY . [W1^T  W2^T]^T <br>= [dL/dY1 dL/dY2] . [W1^T W2^T]^T <br>= [dL/dY1.W1^T dL/dY2.W2^T]<br>= allreduce ( [dL/dY1.W1^T dL/dY2.W2^T] )</pre><pre>dL/dW = X^T . dL/dY = [X1^T  X2^T]^T. dL/dY <br>= [X1^T X2^T]^T. [dL/dY1 dL/dY2]<br>= [X1^T.dL/dY1 X1^T.dL/dY2]<br>ㅤ[X2^T.dL/dY1 X2^T.dL/dY2] # no collectives required</pre><p>Row-wise partitioning:</p><pre>[Y1 ] = X. [W1  + B<br> Y2 ]       W2]<br>Y = allgather ( [Y1 <br>                 Y2])<br>L(Y)</pre><pre>dL/dX = dL/dY . W^T = dL/dY . [W1^T W2^T] = [dL/Y1 dL/Y2] . [W1^T W2^T]<br>      = allgather( [dL/Y1 dL/Y2] . W1^T , [dL/Y1 dL/Y2] . W2^T) </pre><pre>dl/dW = X^T. dL/dY = [X1^T X2^T]^T . [dL/dY]  = <br>      = allgather ( [X1^T].[dL/dY], X2^T].[dL/dY])</pre><p><strong>Visualization:</strong></p><p>The following figure pictorially shows the forward (Y) and backward passes ( dL/dX, dL/dW) for both columnwise and rowwise partitioning of a single matmul ( or linear layer). The pictures can be divided into 3 horizontal and 3 vertical lanes. The horizontal lanes from top to bottom shows the unsharded, columnwise sharded and rowwise sharded partitioning. The vertical lanes from left to right shows forward pass, backward pass for dL/dX (activation) and dL/dW ( parameters) respectively. Note that for rowwise, the backward allgathers are only needed if the weight and activation grads need to be available at all ranks for some reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzSLXYejVKYQrCrqfSlWXA.png" /><figcaption>Fig MMFBP: The above algebra with TP portioning is shown above pictorially for 2 ranks/GPU’s. There are 3 horizontal and 3 vertical lanes. The horizontal lanes from top to bottom shows the unsharded, columnwise sharded and rowwise sharded partitioning. The vertical lanes from left to right shows forward pass, backward pass for dL/dX and dL/dW respectively. Allreduce and allgathers are shown in yellow and dark -yellow respectively.</figcaption></figure><p>In the above figure, the way the middle and bottom horizontal lanes are laid out is also how the MLP layer of a Transformer block is laid out — columnwise followed by rowwise matmul. Thus the figure also shows the functioning of the MLP with just a minor change — removing the allreduce in the forward pass of the colmunwise partitioned section ( e.g. intersection of middle horizontal and left vertical) and the allgathers in the backward pass of activations and weights ( e.g. dL/dX and dL/dW) in the rowwise bottom matmul. The backward pass of weights does not require collectives !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np83xTpbWf8epGVJ2BJmDg.png" /><figcaption>Fig TBMLPFBP: MLP forward (Y) and backward pass ( dL/dX and dL/dW)</figcaption></figure><p><strong>Code :</strong></p><p>The following PyTorch code illustrates the column and row parallel NCCL collective calls, gradients for activations, weights, and biases for a 2 rank run. The code is derived from a PyTorch Unit Test for TP. The runs include both distributed and non-distributed versions and compare them. To see all the collectives , it is important to set the input/output_layouts appropriately , else PyTorch’s autograd engine does not create collective calls in the backward pass.</p><pre># SPLIT=row UTNAME=dtensor_tp_check2 N=1 PPN=2  DTAG=$(date &quot;+%Y%m%d_%H%M%S&quot;) ; TORCH_LOGS=+all NCCL_DEBUG_SUBSYS=COLL NCCL_DEBUG=TRACE torchrun --nnodes $N --nproc-per-node $PPN --no-python python ~/ANL/distributed/extras/${UTNAME}.py --axis $SPLIT  2&gt;&amp;1 | tee ~/datavol/logs/pt/test_parallelize_api_${UTNAME}_${SPLIT}_${DTAG}.log<br><br>from copy import deepcopy<br>from typing import NamedTuple, Optional<br><br>import torch<br>import torch.distributed as dist<br>import torch.nn as nn<br>import torch.nn.functional as F<br>from torch.distributed._tensor import (<br>    DeviceMesh,<br>    DTensor,<br>    Replicate,<br>    Shard,<br>)<br><br>from torch.distributed.tensor.parallel import (<br>    ColwiseParallel,<br>    parallelize_module,<br>    PrepareModuleInput,<br>    RowwiseParallel,<br>    SequenceParallel,<br>)<br><br>import os<br>import argparse<br><br>parser = argparse.ArgumentParser(prog=&#39;TP check&#39;)<br>parser.add_argument(&#39;--axis&#39;, default=&#39;rowwise&#39;, help=&quot;rowwise or colwise&quot;)<br>parser.add_argument(&#39;--test&#39;, default=&#39;tp&#39;, help=&quot;tp, up&quot;)<br>parser.add_argument(&#39;--passes&#39;, default=&#39;fwdbwd&#39;, help=&quot;fwd, fwdbwd&quot;)<br>args = parser.parse_args()<br><br>def get_device_type() -&gt; str:<br>    device_type = &quot;cpu&quot;<br>    if torch.accelerator.device_count() &gt;= 1:<br>        device_type = getattr(torch.accelerator.current_accelerator(), &quot;type&quot;, &quot;cpu&quot;)<br>    return device_type<br><br>if args.test == &quot;tp&quot;:<br>    dm = DeviceMesh(<br>        get_device_type(),<br>        #torch.arange(0, int(os.getenv(&quot;WORLD_SIZE&quot;, 1)) ),<br>        torch.arange(0, int(os.getenv(&#39;WORLD_SIZE&#39;, 1)) ),<br>    )<br><br>class TensorParallelAPITests(object):<br><br>    def __init__(self, ):<br>        self.device_type = get_device_type()<br>        self.rank = int(os.environ[&quot;RANK&quot;])<br>        self._world_size = int(os.environ[&quot;WORLD_SIZE&quot;])<br>        print (f&quot;rank{self.rank} device_type {self.device_type} world_size {self.world_size} &quot;)<br><br>    @property<br>    def world_size(self):<br>        return self._world_size #gpu_num if gpu_num % 2 == 0 and gpu_num &gt; 4 else 4<br><br>    def _compare_params(<br>        self,<br>        up_module,<br>        dist_module,<br>        rank0_only,<br>        skip_rowwise_bias=False,<br>    ):<br>        for name, param in up_module.named_parameters():<br>            dist_param = dist_module.get_parameter(name)<br>            if (<br>                (not rank0_only)<br>                or (self.rank == 0)<br>            ):<br>                print (f&quot;rank{torch.distributed.get_rank()} **** {name} {param.shape} up_param {param} dist_param {dist_param.shape} {dist_param}&quot;)<br>                print (f&quot;rank{torch.distributed.get_rank()} **** {name}.grad {param.grad.shape} up_param {param.grad} dist_param.grad {dist_param.grad.shape} {dist_param.grad}&quot;)<br><br>    def _compare_module(<br>        self, up_module, dist_module, inp_size, device_mesh, rank0_only=True, rowwise=False<br>    ):<br>        LR = 0.25  # the learning rate we use for testing<br>        up_optim = torch.optim.SGD(up_module.parameters(), lr=LR)<br>        dist_optim = torch.optim.SGD(dist_module.parameters(), lr=LR)<br>        torch.manual_seed(0)<br>        #inp = torch.rand(*inp_size, device=self.device_type)<br>        up_inp = torch.ones(*inp_size, requires_grad=True, device=self.device_type)<br>        dist_inp  = torch.ones(*inp_size, requires_grad=True, device=self.device_type)<br>        #self._compare_params(up_module, dist_module, rank0_only)<br><br>        # check forward correctness<br>        up_output = up_module(up_inp)<br>        #dist_inp = dist_inp.chunk(self.world_size, dim=-1)[self.rank] if rowwise else dist_inp<br>        if rowwise:<br>            pass #dist_inp = dist_inp.chunk(self.world_size, dim=-1)[self.rank]<br>        else:<br>            pass<br>        print (f&quot;rank{torch.distributed.get_rank()} **** up_inp {up_inp.shape} {up_inp} dist_inp {dist_inp.shape} {dist_inp} &quot;)<br><br>        dist_output = dist_module(dist_inp)<br>        print (f&quot;rank{torch.distributed.get_rank()} **** up_inp.grad {up_inp.grad} dist_inp.grad {dist_inp.grad} &quot;)<br>        print (f&quot;rank{torch.distributed.get_rank()} **** up_output {up_output } dist_output dtensor? {isinstance(dist_output, DTensor)} {dist_output}&quot;)<br><br>        up_loss = up_output.sum()<br>        dist_loss = dist_output.sum()<br>        print (f&quot;rank{torch.distributed.get_rank()} up_loss {up_loss} dist_loss {dist_loss} &quot;)<br><br>        if args.passes == &#39;fwd&#39;:<br>            return<br>        else:<br>            pass<br><br>        up_loss.retain_grad()<br>        up_output.retain_grad()<br>        dist_loss.retain_grad()<br>        dist_output.retain_grad()<br>        up_inp.retain_grad()<br>        #dist_inp.retain_grad()<br><br>        up_loss.backward()<br>        dist_loss.backward()<br><br>        print (f&quot;rank{torch.distributed.get_rank()} **** up_output.grad {up_output.grad} dist_output.grad {dist_output.grad}&quot;)<br>        print (f&quot;rank{torch.distributed.get_rank()} **** up_loss.grad {up_loss.grad} dist_loss.grad {dist_loss.grad} &quot;)<br>        print (f&quot;rank{torch.distributed.get_rank()} **** up_inp.grad {up_inp.grad} dist_inp.grad {dist_inp.grad} &quot;)<br>        self._compare_params(up_module, dist_module, rank0_only, rowwise)<br><br>        # check backward and ensure gradients are same<br>        #self._compare_params(up_module, dist_module, rank0_only, rowwise, True)<br><br>        up_optim.step()<br>        dist_optim.step()<br>        self._compare_params(up_module, dist_module, rank0_only, rowwise)<br><br><br><br>    def test_linear (self, sharding):<br>        ift = 6<br>        oft  = 4<br>        bs = 1<br>        inp_size = [bs, ift]<br>        if sharding == &#39;rowwise&#39;:<br>            rowwise = True<br>            #plan ={ &quot;&quot;:RowwiseParallel(), &quot;&quot;:PrepareModuleInput(input_layouts=(Replicate(),), desired_input_layouts=(Shard(1),)) }<br>            plan ={ &quot;&quot;:RowwiseParallel(input_layouts=Replicate()), }<br>        elif sharding == &#39;colwise&#39;:<br>            rowwise = False<br>            #split = ColwiseParallel(input_layouts=Replicate(), output_layouts=Replicate())<br>            plan = ColwiseParallel( output_layouts=Replicate())<br><br>        torch.manual_seed(5)<br>        model = torch.nn.Linear(ift, oft, device=self.device_type)<br>        model.weight.data = torch.ones((oft, ift), device=self.device_type, requires_grad = True)<br>        model.bias.data   = torch.ones((1, oft), requires_grad=True, device=self.device_type)<br>        model_tp = deepcopy(model)<br><br>        # parallelize model_tp<br>        #device_mesh = DeviceMesh(self.device_type, list(range(self.world_size)))<br>        #for some reason the above binds all ranks to one GPU.<br><br>        device_mesh = dm<br>        print (f&quot; device_mesh {device_mesh}&quot;)<br>        model_tp = parallelize_module(model_tp, device_mesh, plan)<br><br>        # let each rank generate unique local input<br>        torch.manual_seed(self.rank)<br>        self._compare_module(model, model_tp, inp_size, device_mesh, rowwise=rowwise)<br><br><br>def torch_unparallel ():<br><br>    # Create an instance of the model and a random input<br>    device_type = get_device_type()<br>    ift = 4<br>    oft = 4<br>    # y = x.W^T+B ; W.shape =  (oft, ift) B.shape = (1,oft)<br>    model = torch.nn.Linear(ift, oft, device=device_type)<br>    neww = torch.ones((oft, ift), requires_grad=True, device=device_type)<br>    newb = torch.ones((1, oft), requires_grad=True, device=device_type)<br>    model.weight.data = neww<br>    model.bias.data = newb<br>    #input_tensor = torch.randn(1, 4, requires_grad=True, device=device_type)<br>    input_tensor = torch.ones((1, ift), requires_grad=True, device=device_type)<br><br>    # Forward pass<br>    output = model(input_tensor)<br>    print (&quot;output: &quot; , output)<br><br>    # Simulate a loss (e.g., sum of output elements)<br>    loss = output.sum()<br>    print (&quot;loss: &quot;, loss)<br><br>    input_tensor.retain_grad()<br>    loss.retain_grad()<br>    output.retain_grad()<br><br>    # Backward pass to compute gradients<br>    loss.backward()<br><br>    # Access gradients of model parameters<br>    print(&quot;Loss gradient: &quot;, loss.grad)<br>    print(&quot;Output gradients: &quot;, output.grad)<br>    print(&quot;Linear layer weights gradients:&quot;, model.weight.grad)<br>    print(&quot;Linear layer bias gradients:&quot;, model.bias.grad)<br><br>    # Access gradients of the input tensor (if it requires grad)<br>    print(&quot;Input tensor gradients:&quot;, input_tensor.grad)<br><br>if __name__ == &quot;__main__&quot;:<br>    if args.test == &quot;tp&quot;:<br>        tptest = TensorParallelAPITests()<br>        tptest.test_linear(args.axis)<br>        print (f&quot;rank{torch.distributed.get_rank()} completed {args.axis}&quot;)<br><br>        if torch.distributed.is_initialized():<br>                torch.distributed.destroy_process_group()<br>    elif args.test == &quot;up&quot;:<br>        torch_unparallel()<br><br>    print (f&quot;completed&quot;)<br></pre><p>The output for rowwise and columnwise parallel are shown below. The inputs and weigths are choosen as made of 1’s for easy and quick verification. In this particular instance input of bs=1, seq len=6 and output of 4 is used. Hence, in case of rowwise TP, NCCL shows count of 4 for the forward pass allreduce and count of 3 (=6/2) for the backward pass allgather. Similarly for colwise TP, NCCL counts are 2 (=4/2) for forward pass allgather and 6 for backward pass allreduce. The collectives are shown below.</p><pre>Rowwise:<br><br>rank0 **** up_inp torch.Size([1, 6]) tensor([[1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True) dist_inp torch.Size([1, 6]) tensor([[1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True)<br>rank0 **** up_inp.grad None dist_inp.grad None<br>rank0 **** up_output tensor([[7., 7., 7., 7.]], device=&#39;cuda:0&#39;, grad_fn=&lt;AddmmBackward0&gt;) dist_output dtensor? False AsyncCollectiveTensor(tensor([[7., 7., 7., 7.]], device=&#39;cuda:0&#39;))<br>rank0 up_loss 28.0 dist_loss 28.0<br>rank0 **** up_output.grad tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_output.grad tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;)<br>rank0 **** up_loss.grad 1.0 dist_loss.grad 1.0<br>rank0 **** up_inp.grad tensor([[4., 4., 4., 4., 4., 4.]], device=&#39;cuda:0&#39;) dist_inp.grad tensor([[4., 4., 4., 4., 4., 4.]], device=&#39;cuda:0&#39;)<br>rank0 **** weight torch.Size([4, 6]) up_param Parameter containing:<br>tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True) dist_param torch.Size([4, 6]) DTensor(local_tensor=tensor([[1., 1., 1.],<br>        [1., 1., 1.],<br>        [1., 1., 1.],<br>        [1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=1),))<br>rank0 **** weight.grad torch.Size([4, 6]) up_param tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([4, 6]) DTensor(local_tensor=tensor([[1., 1., 1.],<br>        [1., 1., 1.],<br>        [1., 1., 1.],<br>        [1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=1),))<br>rank0 **** bias torch.Size([1, 4]) up_param Parameter containing:<br>tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True) dist_param torch.Size([1, 4]) DTensor(local_tensor=tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Replicate(),))<br>rank0 **** bias.grad torch.Size([1, 4]) up_param tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([1, 4]) DTensor(local_tensor=tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Replicate(),))<br>rank0 **** weight torch.Size([4, 6]) up_param Parameter containing:<br>tensor([[0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;,<br>       requires_grad=True) dist_param torch.Size([4, 6]) DTensor(local_tensor=tensor([[0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=1),))<br>rank0 **** weight.grad torch.Size([4, 6]) up_param tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([4, 6]) DTensor(local_tensor=tensor([[1., 1., 1.],<br>        [1., 1., 1.],<br>        [1., 1., 1.],<br>        [1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=1),))<br>rank0 **** bias torch.Size([1, 4]) up_param Parameter containing:<br>tensor([[0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;, requires_grad=True) dist_param torch.Size([1, 4]) DTensor(local_tensor=tensor([[0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Replicate(),))<br>rank0 **** bias.grad torch.Size([1, 4]) up_param tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([1, 4]) DTensor(local_tensor=tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Replicate(),))<br>rank0 completed rowwise<br><br>h100:165637:165637 [0] NCCL INFO NCCL version 2.27.5+cuda12.9<br>h100:165637:165637 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7ff099e00a00 count 12 datatype 7 op 0 root 1 comm 0x559f794cec30 [nranks=2] stream (nil)<br>h100:165637:165637 [0] NCCL INFO Broadcast: opCount 0 sendbuff 0x7ff099e00600 recvbuff 0x7ff099e00600 count 4 datatype 7 op 0 root 0 comm 0x559f794cec30 [nranks=2] stream (nil)<br>h100:165637:165637 [0] NCCL INFO AllReduce: opCount 0 sendbuff 0x7ff099e01000 recvbuff 0x7ff099e01000 count 4 datatype 7 op 0 root 0 comm 0x559f794cec30 [nranks=2] stream 0x559f70be0d30<br>h100:165637:165662 [0] NCCL INFO AllGather: opCount 0 sendbuff 0x7ff099e02600 recvbuff 0x7ff099e02a00 count 3 datatype 7 op 0 root 0 comm 0x559f794cec30 [nranks=2] stream 0x559f70be0d30<br><br>Colwise:<br><br>rank0 **** up_inp torch.Size([1, 6]) tensor([[1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True) dist_inp torch.Size([1, 6]) tensor([[1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True)<br>rank0 **** up_inp.grad None dist_inp.grad None<br>rank0 **** up_output tensor([[7., 7., 7., 7.]], device=&#39;cuda:0&#39;, grad_fn=&lt;AddmmBackward0&gt;) dist_output dtensor? False tensor([[7., 7., 7., 7.]], device=&#39;cuda:0&#39;, grad_fn=&lt;_ToTorchTensorBackward&gt;)<br>rank0 up_loss 28.0 dist_loss 28.0<br>rank0 **** up_output.grad tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_output.grad tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;)<br>rank0 **** up_loss.grad 1.0 dist_loss.grad 1.0<br>rank0 **** up_inp.grad tensor([[4., 4., 4., 4., 4., 4.]], device=&#39;cuda:0&#39;) dist_inp.grad tensor([[4., 4., 4., 4., 4., 4.]], device=&#39;cuda:0&#39;)<br>rank0 **** weight torch.Size([4, 6]) up_param Parameter containing:<br>tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True) dist_param torch.Size([4, 6]) DTensor(local_tensor=tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=0),))<br>rank0 **** weight.grad torch.Size([4, 6]) up_param tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([4, 6]) DTensor(local_tensor=tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=0),))<br>rank0 **** bias torch.Size([1, 4]) up_param Parameter containing:<br>tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;, requires_grad=True) dist_param torch.Size([1, 4]) DTensor(local_tensor=tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=0),))<br>rank0 **** bias.grad torch.Size([1, 4]) up_param tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([1, 4]) DTensor(local_tensor=tensor([[1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=1),))<br>rank0 **** weight torch.Size([4, 6]) up_param Parameter containing:<br>tensor([[0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>:w<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;,<br>       requires_grad=True) dist_param torch.Size([4, 6]) DTensor(local_tensor=tensor([[0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500],<br>        [0.7500, 0.7500, 0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=0),))<br>rank0 **** weight.grad torch.Size([4, 6]) up_param tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([4, 6]) DTensor(local_tensor=tensor([[1., 1., 1., 1., 1., 1.],<br>        [1., 1., 1., 1., 1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=0),))<br>rank0 **** bias torch.Size([1, 4]) up_param Parameter containing:<br>tensor([[0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;, requires_grad=True) dist_param torch.Size([1, 4]) DTensor(local_tensor=tensor([[0.7500, 0.7500, 0.7500, 0.7500]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=0),))<br>rank0 **** bias.grad torch.Size([1, 4]) up_param tensor([[1., 1., 1., 1.]], device=&#39;cuda:0&#39;) dist_param.grad torch.Size([1, 4]) DTensor(local_tensor=tensor([[1., 1.]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2,), device: &#39;cuda&#39;, stride: (1,)), placements=(Shard(dim=1),))<br>rank0 completed colwise-wise<br><br>h100:67710:67710 [0] NCCL INFO NCCL version 2.27.5+cuda12.9<br>h100:67710:67710 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7fe003e00230 count 12 datatype 7 op 0 root 1 comm 0x561e81b31340 [nranks=2] stream (nil)<br>h100:67710:67710 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7fe003e00a00 count 4 datatype 7 op 0 root 1 comm 0x561e81b31340 [nranks=2] stream (nil)<br>h100:67710:67710 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7fe003e00c00 count 2 datatype 7 op 0 root 0 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Recv: opCount 0 sendbuff (nil) recvbuff 0x7fe003e00e00 count 2 datatype 7 op 0 root 0 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7fe003e00c08 count 2 datatype 7 op 0 root 1 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Recv: opCount 0 sendbuff (nil) recvbuff 0x7fe003e00e08 count 2 datatype 7 op 0 root 1 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO AllGather: opCount 0 sendbuff 0x7fe003e01000 recvbuff 0x7fe003e00e00 count 2 datatype 7 op 0 root 0 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67737 [0] NCCL INFO AllReduce: opCount 0 sendbuff 0x7fe003e02400 recvbuff 0x7fe003e02400 count 6 datatype 7 op 0 root 0 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7fe003e01400 count 2 datatype 7 op 0 root 0 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Recv: opCount 0 sendbuff (nil) recvbuff 0x7fe003e02600 count 2 datatype 7 op 0 root 0 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Send: opCount 0 sendbuff (nil) recvbuff 0x7fe003e01408 count 2 datatype 7 op 0 root 1 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0<br>h100:67710:67710 [0] NCCL INFO Recv: opCount 0 sendbuff (nil) recvbuff 0x7fe003e02608 count 2 datatype 7 op 0 root 1 comm 0x561e81b31340 [nranks=2] stream 0x561e7a0327e0</pre><h3>PyTorch DTensor:</h3><p>PyTorch is the underlying software infrastructure that allows PyTorch to support multi-dimensional parallelism. The main concepts in DTensors are DeviceMesh , Placement, and Single Program Multiple Data (SPMD). DeviceMesh defines the topology of devices and facilitates the management of underlying ProcessGroup instances for collective communications. Placement describes how the tensor is sharded or replicated across the DeviceMesh, and this placement is propagated or transformed as operations are performed. SPMD ( programming model to empower users to write distributed program as if it’s a single-device program with the same convergence property.</p><p>DTensor is a torch.Tensor subclass. This means once a DTensor is created, it could be used in very similar way to torch.Tensor. Some of its important attributes are as follows.</p><pre>class torch.distributed.tensor.DTensor(local_tensor, spec, *, requires_grad):<br><br>  local_tensor<br>  device_mesh<br>  stride<br>  placement<br></pre><p>Placement and DeviceMesh together could describe the DTensor Layout. The three main DTensor Placement types are Shard, Replicate, and Partial. They respectively stand for divide, copy, and partial reduction.</p><p>The high level user facing api for distributing torch.tensor are.</p><pre>def distribute_tensor(tensor: torch.Tensor, device_mesh: DeviceMesh=None, placements: List[Placement]=None):<br>    &#39;&#39;&#39;<br>    distribute the tensor according to device_mesh and placements, `tensor` could be a &quot;meta&quot; tensor.<br>    &#39;&#39;&#39;<br><br>def distribute_module(<br>    module: nn.Module,<br>    device_mesh: DeviceMesh=None,<br>    partition_fn: Callable[[str, nn.Module, DeviceMesh], ...]=None,<br>    input_fn: Callable[...., None]=None,<br>    output_fn: Callable[...., None]=None,<br>):<br>    &#39;&#39;&#39;<br>    This function converts all module parameters to distributed tensor parameters according to the `partition_fn` specified.<br>    It could also control the input/output of the module by specifying the `input_fn` and `output_fn`.<br>    &#39;&#39;&#39;</pre><p><strong>DTensor Sharding Example:</strong></p><p>DTensor Sharding api distribute_tensor takes a tensor in rank 0 and partitions and distributed to rest of the ranks . The following example code and the corresponding ouptus are described below.</p><pre>def test_sharding():<br>    # if we want to distributed a tensor with both replication and sharding<br>    device_mesh = init_device_mesh(device, (2, 2))<br>    big_tensor = torch.randn(8,8)<br>    print (f&quot;rank{torch.distributed.get_rank()} big_tensor {big_tensor}&quot;)<br>    # replicate across the first dimension of device mesh, then sharding on the second dimension of device mesh<br>    spec=[Replicate(), Shard(0)]<br>    partial_replica = distribute_tensor(big_tensor, device_mesh=device_mesh, placements=spec)<br>    print (f&quot;rank{torch.distributed.get_rank()} partial_replica {partial_replica}&quot;)<br>    spec=[Replicate(), Replicate()]<br>    partial_replica = distribute_tensor(big_tensor, device_mesh=device_mesh, placements=spec)<br>    print (f&quot;rank{torch.distributed.get_rank()} partial_replica {partial_replica}&quot;)<br>    spec=[Shard(0), Replicate()]<br>    partial_replica = distribute_tensor(big_tensor, device_mesh=device_mesh, placements=spec)<br>    print (f&quot;rank{torch.distributed.get_rank()} partial_replica {partial_replica}&quot;)<br>    spec=[Shard(0), Shard(0)]<br>    partial_replica = distribute_tensor(big_tensor, device_mesh=device_mesh, placements=spec)<br>    print (f&quot;rank{torch.distributed.get_rank()} partial_replica {partial_replica}&quot;)<br>    spec=[Shard(0), Shard(1)]<br>    partial_replica = distribute_tensor(big_tensor, device_mesh=device_mesh, placements=spec)<br>    print (f&quot;rank{torch.distributed.get_rank()} partial_replica {partial_replica}&quot;)<br>    spec=[Shard(1), Shard(0)]<br>    partial_replica = distribute_tensor(big_tensor, device_mesh=device_mesh, placements=spec)<br>    print (f&quot;rank{torch.distributed.get_rank()} partial_replica {partial_replica}&quot;)<br><br></pre><p>The distributed_tensors appears to have the following properties.</p><ol><li>The local tensor on rank 0 is considered the source by default.</li><li>Logically distribution ( e.g. sharding, replication, partial reduction ) starts with device_map dimension and then progresses through next higher dimension at each step. This is the left-to-right sharding . However FSDPv2+TP follows a <a href="https://github.com/pytorch/pytorch/blob/7a68d02292fd7a430b55c5bce3268a33c7ec5055/torch/distributed/tensor/placement_types.py#L368">right-to-left sharding</a> .</li></ol><p>The local initial tensor in each rank.</p><pre>rank0 big_tensor tensor([[ 8.3563e-01,  1.0330e+00, -4.8242e-01, -2.4056e+00, -1.4921e-03,<br>          1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [-2.9655e-01, -5.5142e-01,  3.6158e-01,  1.4239e+00,  2.7008e+00,<br>         -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [ 1.4539e+00,  1.2508e+00,  1.7045e-01, -8.7195e-01, -1.4609e+00,<br>         -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 1.2846e+00,  2.4039e-02, -3.4069e-01, -6.2096e-01,  8.3556e-03,<br>          6.3983e-01,  1.1016e+00,  5.3817e-01],<br>        [-6.8899e-01, -1.5450e+00,  3.5916e-01,  4.5966e-01, -2.3635e+00,<br>          1.3077e+00,  1.1896e+00,  1.1787e+00],<br>        [ 1.6779e+00, -9.3585e-01, -1.0754e+00,  1.7779e+00, -6.1787e-01,<br>          3.3454e-01, -5.4135e-01, -8.6717e-02],<br>        [ 3.1228e-02,  1.0113e+00,  9.7197e-01, -7.1074e-01, -1.9381e-01,<br>          1.4386e-01, -6.8691e-01,  2.7425e+00],<br>        [-1.0582e+00,  1.1514e+00,  1.2194e+00,  1.0376e+00, -5.2098e-01,<br>          1.2162e+00, -1.5944e+00,  3.3029e-01]])<br><br>rank1 big_tensor tensor([[ 5.0825e-01, -6.2649e-01, -2.5204e+00, -3.5625e-01,  2.8870e-01,<br>         -6.6505e-01,  9.6324e-01, -1.4687e+00],<br>        [-1.1895e+00,  1.6376e+00, -9.2589e-01,  1.8313e+00,  6.1157e-01,<br>         -1.1237e+00,  4.1471e-01,  7.7726e-04],<br>        [-4.0668e-01,  2.6911e+00, -6.6412e-01, -3.4789e-01, -4.4555e-01,<br>         -6.8567e-01, -9.5894e-01, -5.2243e-01],<br>        [ 1.7866e+00, -5.5445e-01, -8.5636e-01, -4.8268e-01,  1.5808e-01,<br>          1.3102e+00, -1.2866e+00, -2.2034e+00],<br>        [-8.1262e-01, -9.9341e-01, -6.4063e-01, -6.7488e-02, -1.0170e-01,<br>          7.9248e-01, -2.7295e+00, -7.5580e-01],<br>        [ 2.9803e-01, -2.1638e+00, -1.0660e+00, -1.7005e+00,  1.6357e-01,<br>          4.9351e-01, -2.9490e-01,  1.2547e+00],<br>        [ 2.0747e-01,  1.6394e+00, -2.0497e+00,  2.0477e+00, -9.5144e-01,<br>         -2.3246e-01,  1.7327e+00,  3.6954e-01],<br>        [-9.3335e-01,  8.3480e-01,  1.9806e+00,  3.7474e-01, -5.3466e-01,<br>          4.4953e-01,  3.8489e-01,  6.0675e-01]])<br><br>rank2 big_tensor tensor([[ 1.1082,  1.0005,  1.1565, -0.3217, -0.8491,  1.4241,  1.4506, -0.3691],<br>        [ 1.0169, -1.4584,  0.0849, -0.6854,  0.7634, -0.9904, -1.2888,  1.1530],<br>        [ 0.0820, -0.8129, -0.9990, -1.9929,  0.5270, -0.5870,  0.1015,  1.1749],<br>        [ 1.2885,  1.9667, -1.6978,  2.9027,  0.9054, -0.5864,  0.3718,  0.8059],<br>        [ 0.5026,  0.4155,  0.1396,  1.2009,  0.3258,  0.9244, -0.1233,  0.7117],<br>        [ 0.2145, -1.1627, -0.3105, -0.6426,  1.2322,  0.7033, -1.3078,  0.4981],<br>        [ 0.4111,  0.5833, -1.4289, -1.0605,  1.4656,  2.0069, -0.9252,  0.6755],<br>        [-0.3270,  0.2586, -0.5018, -1.0648,  0.9667,  0.8172,  1.7679, -1.6078]])<br><br>rank3 big_tensor tensor([[ 1.6360e+00, -4.0891e-01,  1.4733e-01,  4.5829e-01, -2.4391e+00,<br>          9.3111e-01, -7.6715e-01, -1.4407e+00],<br>        [-1.5677e+00,  5.2073e-01, -3.7792e-01,  2.0922e-04, -9.6230e-01,<br>         -1.6181e+00,  1.5858e+00, -1.7218e+00],<br>        [-4.3537e-02, -1.2528e-01,  2.0319e+00, -6.7158e-01,  1.0774e+00,<br>         -1.0302e+00,  7.1058e-01, -1.5598e+00],<br>        [ 2.8356e-01, -6.3299e-01, -5.8437e-01,  2.1673e+00, -4.0170e-01,<br>         -1.3536e+00,  1.2479e+00,  1.0063e+00],<br>        [-4.9102e-01,  9.3310e-01, -7.4133e-01,  3.6599e-01,  3.0805e-01,<br>         -3.9950e-01,  1.8045e+00, -1.5576e+00],<br>        [-1.9799e-01, -2.0584e-01,  4.8604e-02, -3.1100e-01,  7.1337e-01,<br>         -3.5554e-01,  5.1115e-01,  5.4724e-01],<br>        [-9.7889e-01,  1.7310e-01,  9.2786e-01,  5.6840e-02,  1.2124e+00,<br>         -1.4117e+00, -7.8778e-01, -1.1854e+00],<br>        [-2.0403e+00, -3.8224e-01, -1.6762e+00, -3.2956e-02,  1.2617e+00,<br>          3.6312e-01,  7.9675e-01,  7.6087e-01]])</pre><p><strong>placements=(Replicate(), Shard(dim=0))):</strong></p><p>ㅤㅤㅤㅤdevivce_map<br>replicated ↓ 00 01 -&gt; sharded 1/2 along tensor row dimension (dm=0) <br> ㅤㅤㅤㅤㅤ↓ 10 11</p><pre>rank0 partial_replica DTensor(local_tensor=tensor([[ 8.3563e-01,  1.0330e+00, -4.8242e-01, -2.4056e+00, -1.4921e-03,<br>          1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [-2.9655e-01, -5.5142e-01,  3.6158e-01,  1.4239e+00,  2.7008e+00,<br>         -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [ 1.4539e+00,  1.2508e+00,  1.7045e-01, -8.7195e-01, -1.4609e+00,<br>         -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 1.2846e+00,  2.4039e-02, -3.4069e-01, -6.2096e-01,  8.3556e-03,<br>          6.3983e-01,  1.1016e+00,  5.3817e-01]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Replicate(), Shard(dim=0)))<br><br>rank1 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597, -2.3635,  1.3077,  1.1896,  1.1787],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779, -0.6179,  0.3345, -0.5413, -0.0867],<br>        [ 0.0312,  1.0113,  0.9720, -0.7107, -0.1938,  0.1439, -0.6869,  2.7425],<br>        [-1.0582,  1.1514,  1.2194,  1.0376, -0.5210,  1.2162, -1.5944,  0.3303]],<br>       device=&#39;cuda:1&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Replicate(), Shard(dim=0)))<br><br>rank2 partial_replica DTensor(local_tensor=tensor([[ 8.3563e-01,  1.0330e+00, -4.8242e-01, -2.4056e+00, -1.4921e-03,<br>          1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [-2.9655e-01, -5.5142e-01,  3.6158e-01,  1.4239e+00,  2.7008e+00,<br>         -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [ 1.4539e+00,  1.2508e+00,  1.7045e-01, -8.7195e-01, -1.4609e+00,<br>         -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 1.2846e+00,  2.4039e-02, -3.4069e-01, -6.2096e-01,  8.3556e-03,<br>          6.3983e-01,  1.1016e+00,  5.3817e-01]], device=&#39;cuda:2&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Replicate(), Shard(dim=0)))<br><br>rank3 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597, -2.3635,  1.3077,  1.1896,  1.1787],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779, -0.6179,  0.3345, -0.5413, -0.0867],<br>        [ 0.0312,  1.0113,  0.9720, -0.7107, -0.1938,  0.1439, -0.6869,  2.7425],<br>        [-1.0582,  1.1514,  1.2194,  1.0376, -0.5210,  1.2162, -1.5944,  0.3303]],<br>       device=&#39;cuda:3&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Replicate(), Shard(dim=0)))</pre><p>The device_mesh stride refers to steps needed in a linearly laid out list of devices to get to the next device in that dimension.</p><p><strong>placements=(Replicate(), Replicate())):</strong></p><p>the entire rank0 tensor is replicated across all devices of device map</p><p><strong>placements=(Shard(dim=0), Replicate())):</strong></p><p>ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤdevice_map<br>sharded 1/2 along tensor row dimension ↓ 00 01 -&gt; replicated<br> ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ ↓ 10 11</p><pre>rank0 partial_replica DTensor(local_tensor=tensor([[ 8.3563e-01,  1.0330e+00, -4.8242e-01, -2.4056e+00, -1.4921e-03,<br>          1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [-2.9655e-01, -5.5142e-01,  3.6158e-01,  1.4239e+00,  2.7008e+00,<br>         -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [ 1.4539e+00,  1.2508e+00,  1.7045e-01, -8.7195e-01, -1.4609e+00,<br>         -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 1.2846e+00,  2.4039e-02, -3.4069e-01, -6.2096e-01,  8.3556e-03,<br>          6.3983e-01,  1.1016e+00,  5.3817e-01]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Replicate()))<br>rank1 partial_replica DTensor(local_tensor=tensor([[ 8.3563e-01,  1.0330e+00, -4.8242e-01, -2.4056e+00, -1.4921e-03,<br>          1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [-2.9655e-01, -5.5142e-01,  3.6158e-01,  1.4239e+00,  2.7008e+00,<br>         -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [ 1.4539e+00,  1.2508e+00,  1.7045e-01, -8.7195e-01, -1.4609e+00,<br>         -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 1.2846e+00,  2.4039e-02, -3.4069e-01, -6.2096e-01,  8.3556e-03,<br>          6.3983e-01,  1.1016e+00,  5.3817e-01]], device=&#39;cuda:1&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Replicate()))<br>rank2 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597, -2.3635,  1.3077,  1.1896,  1.1787],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779, -0.6179,  0.3345, -0.5413, -0.0867],<br>        [ 0.0312,  1.0113,  0.9720, -0.7107, -0.1938,  0.1439, -0.6869,  2.7425],<br>        [-1.0582,  1.1514,  1.2194,  1.0376, -0.5210,  1.2162, -1.5944,  0.3303]],<br>       device=&#39;cuda:2&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Replicate()))<br>rank3 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597, -2.3635,  1.3077,  1.1896,  1.1787],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779, -0.6179,  0.3345, -0.5413, -0.0867],<br>        [ 0.0312,  1.0113,  0.9720, -0.7107, -0.1938,  0.1439, -0.6869,  2.7425],<br>        [-1.0582,  1.1514,  1.2194,  1.0376, -0.5210,  1.2162, -1.5944,  0.3303]],<br>       device=&#39;cuda:3&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Replicate()))</pre><p><strong>placements=(Shard(dim=0), Shard(dim=0))):</strong></p><p>sharded along tensor row dimension with</p><p>rows 0 and 1 placed on device 00<br>rows 2 and 3 placed on device 01<br>rows 4 and 5 placed on device 10<br>rows 6 and 7 placed on device 11</p><p>It can be looked as follows</p><p>rows 0 to 3 and 4 to 7 sharded and placed on device 00 and 10 ( dim =0)<br>rows 0 to 1 and 2 to 3 sharded and placed on device 00 and 01 ( dim =1)<br>rows 4 to 5 and 6 to 7 sharded and placed on device 10 and 11 ( dim =1)</p><pre>rank0 partial_replica DTensor(local_tensor=tensor([[ 8.3563e-01,  1.0330e+00, -4.8242e-01, -2.4056e+00, -1.4921e-03,<br>          1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [-2.9655e-01, -5.5142e-01,  3.6158e-01,  1.4239e+00,  2.7008e+00,<br>         -7.6024e-02,  4.5894e-01, -9.8658e-01]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=0)))<br>rank1 partial_replica DTensor(local_tensor=tensor([[ 1.4539,  1.2508,  0.1704, -0.8720, -1.4609, -1.6606, -0.5783,  0.3863],<br>        [ 1.2846,  0.0240, -0.3407, -0.6210,  0.0084,  0.6398,  1.1016,  0.5382]],<br>       device=&#39;cuda:1&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=0)))<br>rank2 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597, -2.3635,  1.3077,  1.1896,  1.1787],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779, -0.6179,  0.3345, -0.5413, -0.0867]],<br>       device=&#39;cuda:2&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=0)))<br>rank3 partial_replica DTensor(local_tensor=tensor([[ 0.0312,  1.0113,  0.9720, -0.7107, -0.1938,  0.1439, -0.6869,  2.7425],<br>        [-1.0582,  1.1514,  1.2194,  1.0376, -0.5210,  1.2162, -1.5944,  0.3303]],<br>       device=&#39;cuda:3&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=0)))<br></pre><p><strong>placements=(Shard(dim=0), Shard(dim=1))):</strong></p><p>rows 0 to 3 and 4 to 7 sharded and placed on devices 00 and 10 ( dim =0)<br>columns 0 to 3 and 4 to 7 sharded and placed on devices 00 and 01 ( dim =1)<br>columns 0 to 3 and 4 to 7 sharded and placed on devices 10 and 11 ( dim =1)</p><pre>rank0 partial_replica DTensor(local_tensor=tensor([[ 0.8356,  1.0330, -0.4824, -2.4056],<br>        [-0.2966, -0.5514,  0.3616,  1.4239],<br>        [ 1.4539,  1.2508,  0.1704, -0.8720],<br>        [ 1.2846,  0.0240, -0.3407, -0.6210]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=1)))<br>rank1 partial_replica DTensor(local_tensor=tensor([[-1.4921e-03,  1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [ 2.7008e+00, -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [-1.4609e+00, -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 8.3556e-03,  6.3983e-01,  1.1016e+00,  5.3817e-01]], device=&#39;cuda:1&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=1)))<br>rank2 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779],<br>        [ 0.0312,  1.0113,  0.9720, -0.7107],<br>        [-1.0582,  1.1514,  1.2194,  1.0376]], device=&#39;cuda:2&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=1)))<br>rank3 partial_replica DTensor(local_tensor=tensor([[-2.3635,  1.3077,  1.1896,  1.1787],<br>        [-0.6179,  0.3345, -0.5413, -0.0867],<br>        [-0.1938,  0.1439, -0.6869,  2.7425],<br>        [-0.5210,  1.2162, -1.5944,  0.3303]], device=&#39;cuda:3&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=0), Shard(dim=1)))</pre><p><strong>placements=(Shard(dim=1), Shard(dim=0))):</strong></p><p>columns 0 to 3 and 4 to 7 sharded and placed on devices 00 and 10 ( dim =0)<br>rows 0 to 3 and 4 to 7 sharded and placed on devices 00 and 01 ( dim =1)<br>rows 0 to 3 and 4 to 7 sharded and placed on devices 10 and 11 ( dim =1)</p><pre>rank0 partial_replica DTensor(local_tensor=tensor([[ 0.8356,  1.0330, -0.4824, -2.4056],<br>        [-0.2966, -0.5514,  0.3616,  1.4239],<br>        [ 1.4539,  1.2508,  0.1704, -0.8720],<br>        [ 1.2846,  0.0240, -0.3407, -0.6210]], device=&#39;cuda:0&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=1), Shard(dim=0)))<br>rank1 partial_replica DTensor(local_tensor=tensor([[-0.6890, -1.5450,  0.3592,  0.4597],<br>        [ 1.6779, -0.9358, -1.0754,  1.7779],<br>        [ 0.0312,  1.0113,  0.9720, -0.7107],<br>        [-1.0582,  1.1514,  1.2194,  1.0376]], device=&#39;cuda:1&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=1), Shard(dim=0)))<br>rank2 partial_replica DTensor(local_tensor=tensor([[-1.4921e-03,  1.4114e+00, -9.5592e-01,  1.6962e+00],<br>        [ 2.7008e+00, -7.6024e-02,  4.5894e-01, -9.8658e-01],<br>        [-1.4609e+00, -1.6606e+00, -5.7830e-01,  3.8626e-01],<br>        [ 8.3556e-03,  6.3983e-01,  1.1016e+00,  5.3817e-01]], device=&#39;cuda:2&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=1), Shard(dim=0)))<br>rank3 partial_replica DTensor(local_tensor=tensor([[-2.3635,  1.3077,  1.1896,  1.1787],<br>        [-0.6179,  0.3345, -0.5413, -0.0867],<br>        [-0.1938,  0.1439, -0.6869,  2.7425],<br>        [-0.5210,  1.2162, -1.5944,  0.3303]], device=&#39;cuda:3&#39;), device_mesh=DeviceMesh((2, 2), device: &#39;cuda&#39;, stride: (2, 1)), placements=(Shard(dim=1), Shard(dim=0)))</pre><p>Some common sharding strategies are</p><p>rowwise_placement=[Shard(0)]<br>colwise_placement=[Shard(1)]<br><a href="https://github.com/pytorch/pytorch/blob/7a68d02292fd7a430b55c5bce3268a33c7ec5055/torch/distributed/fsdp/_fully_shard/_fully_shard.py#L139">FSDP placements: [Shard(0)]<br>HSDP placements [Replicate(), Shard(0)]</a></p><h3><strong>References:</strong></h3><ol><li><a href="https://arxiv.org/pdf/1909.08053">Megatron-LM: Training Multi-Billion Parameter Language Models Using<br>Model Parallelism (TP)</a></li><li><a href="https://docs.pytorch.org/tutorials/intermediate/TP_tutorial.html">Large Scale Transformer model training with Tensor Parallel (TP)</a>,</li><li><a href="https://discuss.pytorch.org/t/distributed-w-torchtitan-introducing-async-tensor-parallelism-in-pytorch/209487">Introducing Async Tensor Parallelism in PyTorch</a> (TP)</li><li><a href="https://arxiv.org/pdf/2205.05198">Sequence Parallel (SP) — Reducing Activation Recomputation in Large Transformer Models</a></li><li><a href="https://discuss.pytorch.org/t/distributed-w-torchtitan-breaking-barriers-training-long-context-llms-with-1m-sequence-length-in-pytorch-using-context-parallel/215082">Breaking Barriers: Training Long Context LLMs with 1M Sequence Length in PyTorch Using Context Paralle</a>l (CP)</li><li><a href="https://arxiv.org/pdf/2411.01783">CONTEXT PARALLELISM FOR SCALABLE MILLION-TOKEN INFERENCE</a>(CP)</li><li><a href="https://huggingface.co/blog/huseinzol05/context-parallelism">Context Parallelism (CP)— Huggingface</a></li><li><a href="https://arxiv.org/pdf/2310.01889">Ring Attention with Blockwise Transformers for Near-Infinite Context</a>(CP)</li><li><a href="https://arxiv.org/pdf/2105.13120">Sequence Parallelism: Long Sequence Training from<br>System Perspective</a></li><li><a href="https://arxiv.org/pdf/2104.04473">Efficient Large-Scale Language Model Training on GPU Clusters<br>Using Megatron-LM (PP — </a>Interleaved 1F1B<a href="https://arxiv.org/pdf/2104.04473">)</a></li><li>OUTRAGEOUSLY LARGE NEURAL NETWORKS:<br>THE SPARSELY-GATED MIXTURE-OF-EXPERTS LAYER, <a href="https://arxiv.org/pdf/1701.06538">https://arxiv.org/pdf/1701.06538</a></li><li>Switch Transformers: Scaling to Trillion Parameter Models<br>with Simple and Efficient Sparsity, <a href="https://arxiv.org/pdf/2101.03961">https://arxiv.org/pdf/2101.03961</a></li><li>Mixture of Experts, <a href="https://www.cs.cmu.edu/~mgormley/courses/10423/slides/lecture16-moe-ink.pdf">https://www.cs.cmu.edu/~mgormley/courses/10423/slides/lecture16-moe-ink.pdf</a></li><li>Mixtral of Experts, <a href="https://arxiv.org/pdf/2401.04088">https://arxiv.org/pdf/2401.04088</a></li><li>AUXILIARY-LOSS-FREE LOAD BALANCING STRATEGY FOR MIXTURE-OF-EXPERTS, <a href="https://arxiv.org/pdf/2408.15664">https://arxiv.org/pdf/2408.15664</a></li><li>Fully Sharded Data Parallelism (FSDP), <a href="https://blog.clika.io/fsdp-1/">https://blog.clika.io/fsdp-1/</a></li><li>Fully Sharded Data Parallel: faster AI training with fewer GPUs (FSDP), <a href="https://engineering.fb.com/2021/07/15/open-source/fsdp/">https://engineering.fb.com/2021/07/15/open-source/fsdp/</a></li><li>Getting Started with Fully Sharded Data Parallel(FSDP), <a href="https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html">https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html</a></li><li>ZeRO: Memory Optimizations Toward Training Trillion Parameter Models, <a href="https://arxiv.org/abs/1910.02054">https://arxiv.org/abs/1910.02054</a></li><li>How to Scale Your Model, <a href="https://jax-ml.github.io/scaling-book/transformers/">https://jax-ml.github.io/scaling-book/transformers/</a></li><li>DTensor — Status, Design and Looking Forward, <a href="https://dev-discuss.pytorch.org/t/dtensor-status-design-and-looking-forward/2749">https://dev-discuss.pytorch.org/t/dtensor-status-design-and-looking-forward/2749</a></li><li>Parallelisms. <a href="https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/features/parallelisms.html">https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/features/parallelisms.html</a></li><li>A Gentle Introduction to torch.autograd, <a href="https://docs.pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html">https://docs.pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html</a></li><li>Backpropagation for a Linear Layer, <a href="https://cs231n.stanford.edu/handouts/linear-backprop.pdf">https://cs231n.stanford.edu/handouts/linear-backprop.pdf</a></li><li>The Chain Rule for Multivariable Functions, <a href="https://math.libretexts.org/Bookshelves/Calculus/Calculus_(OpenStax)/14%3A_Differentiation_of_Functions_of_Several_Variables/14.05%3A_The_Chain_Rule_for_Multivariable_Functions">https://math.libretexts.org/Bookshelves/Calculus/Calculus_(OpenStax)/14%3A_Differentiation_of_Functions_of_Several_Variables/14.05%3A_The_Chain_Rule_for_Multivariable_Functions</a></li><li>Stanford CS336 Language Modeling from Scratch | Spring 2025 |, <a href="https://stanford-cs336.github.io/spring2025/">https://stanford-cs336.github.io/spring2025/</a>, Parallelism 1, <a href="https://www.youtube.com/watch?v=l1RJcDjzK8M">https://www.youtube.com/watch?v=l1RJcDjzK8M</a><br>Lecture 25: Parallel Deep Learning (Model &amp; Pipeline Parallelism) , <a href="https://www.cs.cmu.edu/~15418/lectures/25-parallel_deep_learning_model_pipeline_parallel.pdf">https://www.cs.cmu.edu/~15418/lectures/25-parallel_deep_learning_model_pipeline_parallel.pdf</a></li><li>Distributed training of large language models: A survey, <a href="https://www.sciencedirect.com/science/article/pii/S2949719125000500">https://www.sciencedirect.com/science/article/pii/S2949719125000500</a></li><li><a href="https://dev-discuss.pytorch.org/t/dtensor-status-design-and-looking-forward/2749">DTensor — Status, Design and Looking Forward</a></li><li><a href="https://docs.pytorch.org/docs/stable/distributed.tensor.html">torch.distributed.tensor</a></li><li>The Ultra-Scale Playbook: Training LLMs on GPU Clusters, <a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=high-level_overview">https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=high-level_overview</a></li><li><a href="https://jax-ml.github.io/scaling-book/">How to Scale Your Model A Systems View of LLMs on TPUs</a>,</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a666e9080e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revisiting AI Scaling Law]]></title>
            <link>https://whatdhack.medium.com/revisiting-ai-scaling-law-5665250b41c3?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/5665250b41c3</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[moores-law]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[scaling-law]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 09:53:45 GMT</pubDate>
            <atom:updated>2025-02-23T09:53:45.081Z</atom:updated>
            <content:encoded><![CDATA[<p>So far advances in AI have been made by primarily by increasing the size of the model. From GPT-2 to GPT-4, the number of parameter increased from order of 1B to order of 1.76 T — a 1760x growth in size.</p><p><strong>AI Scaling Law and Moore’s Law :</strong></p><p>The most well known scaling law in modern history is probably the Moore’s Law. This was (?) the scaling law of silicon chip miniaturization. It roughly goes as follows — density of transistors doubles every 1.5–2 years. This enabled more and more functions and features to be packed into the same area. The miniaturization reduced cost and power consumption proportionately over the last 4+ decades.</p><p>The AI scaling looks exactly the opposite in terms of hardware, power and cost footprint. A large number of very large racks or cabinets of GPUs and CPUs are strung together by cables, fibers, and network switches in a super computer cluster. Can this shrink into a palm size system ?</p><p>The iPhone 15 packs in the same amount of compute, 35 TOPS , as the top supercomputer in 2002 ? That shrinkage happened all due to relentless miniaturization of silicon integrated circuits — from about 200 nm to 3 nm — 4444 x shrinkage in terms of area. Could the current top supercomputer capability be in a future phone ? That is likely to fall short by a wide margin, as there is not much runway left for miniaturization in silicon, if at all. The most advanced production nodes are going to have line-width of about 2 nm in 2025. The significant distances in a Si crystalline wafer are 0.543 nm for lattice constant and 0.235 nm for nearest neighbor. Hence, we are very close to a fundamental limit.</p><p><strong>AI Scaling “Law/s”:</strong></p><p>The GPT-4 report and the 2020 Scaling Law paper from OpenAI provide insights into how model accuracy varies with size. Both papers primarily looked at the auto-regressive loss. GPT-4 report also looked into a specific test called HumanEval that measures the ability to synthesize Python functions of varying complexity. The goal was to get an acccurate prediction of performance of a GPT-4 size model from models 1000x smaller.</p><p>Please refer to the Appendix section for refresher on Entropy, Cross-Entropy Loss, GPT Model Sizes, etc.</p><p>The following picture shows an extracted and re-plotted version of the loss trend of Figure 1 in the GPT-4 report. The GPT-4 report only shows relative compute and model size. Both axes are logarithmic. The red curve is for the value after subtracting 1 from loss ( called <em>loss-1 </em>here<em> </em>), the blue curve is the absolute loss ( called <em>loss</em>). The <em>loss-1</em> curve shows a better fit, <em>loss-1 = 0.259C^-0.127 , C </em>represents compute. This is a power or logarithmic equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*phRxvi3FkW26SpGcRrdaQQ.png" /><figcaption><strong>GPT model loss vs relative compute for relative model size sweep ( data frm GPT-4 Technical Report)</strong></figcaption></figure><p>One consequence of the logarithmic nature is that it would require infinite amount of compute to reach 0 <em>loss-1</em>.</p><p>Another consequence is rapidly diminishing return ( e.g. <em>d(loss-1)/dx</em> =<em> -0.032893C^-1.127 ) </em>as compute becomes larger, more compute is needed to reduce loss by the same amount.</p><p><strong>Why loss-1 is a better fit ? :</strong></p><p>It is hard to say for sure without knowing the target data and the exact loss function used. If we allow ourselves to imagine that the loss function is the commonly used Cross Entropy Loss, then the equation for loss is as follows (see Appendix for detail).</p><p><em>loss = H(q,p) = H(q)+DKL(q∥p) = — Σᵢ qᵢ * log(pᵢ),</em></p><p><em>where q and p are target and predicted distributions.</em></p><p>One interpretation is that the value of 1 is the entropy of the target distribution. We can take Cross Entropy loss of the target to itself to find the entropy. Which will give us the target distribution entropy, <em>H(q)</em> . To do so, we will first have to convert target values to one hot encoding and then apply <em>softmax </em>to get the probabilities as follows<em>.</em></p><p><em>q(x</em>ᵢ) = <em>softmax(x</em>ᵢ<em>)=exp⁡(x</em>ᵢ<em>) / ∑</em>ⱼ<em> exp⁡(x</em>ⱼ<em>) = e(1*MF)/(e(1*MF) + 1+1+….. )</em></p><p>= <em>e(1*MF)/((e(1*MF) + (C-1)), when the i th category is the target value</em></p><p><em>where MF is a multiplication factor and C is the number of classes</em></p><p><em>MF</em> of 1 does not produce a probability of 1 for the target category as can be seen from the above equation. Setting <em>MF</em> to a large number, 100, gets a value that is much higher for the target category and the rest at 1 is much smaller. Hence , the probability is closer to 1. Finally we apply <em>log</em> and multiply <em>— Σᵢq(x</em>ⱼ)*log(<em>q</em>(<em>x</em>ⱼ)) . When MF is a large number, the entropy value becomes 0 , as either log( <em>q(x</em>ⱼ) is 0 or <em>q(x</em>ⱼ) is 0. To get an entropy value of 1.0 requires an MF of around 3.5.</p><p>A similar concept was also mentioned in the 2020 Scaling Laws paper. Where is the <em>H(q) </em>is named<em> </em>irreducible loss,<em> L∞</em>.</p><p><strong>Compute and Parameters:</strong></p><p>In the 2020 Scaling Laws paper, the amount of compute required to train 1-token is mentioned as <em>C ≈ 6N, </em>where <em>N </em>is number of non-embedding parameters. For GPT, it is approximated as <em>N ≈ 12*nlayers * dmodel²</em> . Hence , <em>C ≈ 72*nlayers * dmodel².</em></p><p>To train the model to convergence requires iterating over many tokens, <em>ntok</em>. Hence, to train the model to convergence requires total compute of <em>Cc ≈</em> 7<em>2*epochs*ntok*nlayers * dmodel² .</em></p><p>It is reasonable to expect epochs and tokens required for convergence to be be a function of size of the model. The 2020 Scaling Laws paper puts it as <em>D ∝ N^0.74, </em>where<em> D = epochs*tokens . </em>Hence<em> , Cc ∝ 6N^(1.74) .</em></p><p>However, from the data in the GPT-3 paper, it looks like compute required to pre-train is almost constant at 2.2e-8 PFsD/parameter ( see table in Appendix). Hence we can approximate the above equation to <em>Cc ∝ 6N² </em>instead of<em> Cc ∝ 6N^(1.74)</em></p><p>The 2020 scaling laws paper also empirically found the following power relationship between loss and model size.</p><p><em>loss = (Nc/N)^αₙ, </em>where<em> αₙ ∼ 0.076</em>, <em>Nc ∼ 8.8 × 10^13</em> (non-embedding )</p><p>By plugging in the values for model size in terms of compute , we can arrive at a similar expression for <em>loss-1 ( e.g. </em>not <em>loss ) — </em>see Appendix for details.</p><p><em>loss-1 = (Nc/N)^αₙ ∝ (Nc/(C/6) ) ^ (αₙ)</em></p><p>=&gt; <em>αₙ = 0.127</em></p><p>=&gt; <em>(6*Nc)^(αₙ) ∝ 0.259 -&gt; </em>which is just a constant that we can rename to <em>Co</em></p><p>The absolute value of <em>Co</em> determines actual value of compute, and will move the curve right or left on the x( log) axis. We can estimate its value by plugging in known ( guessed ) pre-training compute values. Interpolation appears to indicate that the point just before GPT-4 in the above figure is about the size of GPT-3 small ( 1.25e8 params).</p><p><em>Co = 4.68/(1.09e-10)^(-0.127) = 0.254 -&gt; </em>very close to the 0.259 above !</p><p><strong>GPT-4 Pre-training Compute Used Estimation:</strong></p><p>The rumored size of GPT-4 is 1.76x10^12 parameters, vs GPT-3 Small’s 1.25x10⁸ at. GPT-3 small takes 2.66 PFsD pre-training compute, which translates to 3.49x10⁴ PFsD for GPT-4 pre-training. The rumored cluster size used for GPT-4 pre-training was 25K Nvidia A100s. Such a cluster with 100% scaling efficiency and no stoppage ( both of these are ideal scenarios not realistic yet), the estimate for pre-training with BF16/FP16 comes out to 4.8 days! It will be significantly higher with FP32–71.7 days ( 312/19.5 ) due lack of TensorCore support and twice the operand size.</p><p>In practice, the compute time probably was much higher due to factors such as system down time, hyper-parameter tuning, model change, data adjustments, memory bandwidth limited operations ( e.g. arithmetic intensity low) , and lower than 100% scaling efficiency.</p><p><strong>Smaller but Better Models:</strong></p><p>Recently some smaller models such as Llama 3.4, Qwen, DeepSeek,etc.are producing results that are better than some much larger. The creators of the models attribute this to the quality of data. Is there any relationship between data quality and entropy ? As was seen in a previous section above, the absolute value of entropy can be manipulated. If there exists a normalized value of entropy, then does lower entropy imply better data quality ?</p><p>DeepSeek’s Latent Attention ( which a tensor rank lowering technique like LORA ) does not change the exponent , <em>αₙ = </em>0.127, but changes the base, hence reduces the total compute.</p><p><em>M x dim dim x N -&gt; 2M.N.dim</em></p><p><em>M x dim dim x dl dl x dim dim xN -&gt; 2M.dl.dim + 2N.dl.dim = 2(M+N).dim.dl</em></p><p><em>2(M+N).dim.dl/2M.N.dim = (M+N).dl/M.N</em></p><p>Mixture of Expert (MoE) also reduces the absolute compute needs without changing the exponent.</p><p><strong>Further Reduction of the AI Power Law:</strong></p><p>The exponent , <em>αN=0.127</em>, is approximately 1/8 . This gives us the following in terms of 2 significant dimension of GPT.</p><p><em>loss -1 ∝ 1/ (nlayers * dmodel² ) ^ (1/8)</em></p><p>There appears to be a linear relationship between <em>nlayers</em> and <em>dmodel</em> ( see Appendix on GPT3). Hence we can write the following</p><p><em>loss -1 ∝ 1/ (dmodel³) ^ (1/8) ∝ 1/ dmodel ^ (3/8)</em></p><p><em>loss -1 = Mc/dmodel ^ (3/8), </em>where<em> Mc </em>is a model constant</p><p>The above equation implies that <em>loss-1</em> can be lowered by decreasing <em>Mc, </em>increasing<em> dmodel, </em>and by increasing the exponent <em>3/8 .</em></p><p><strong>Conclusion :</strong></p><p>In the 2020 Scaling Laws paper, the authors list the scaling exponent values for different types of data. The exponent values for all those data types are between 0.14 and 0.19. In a previous section it was derived that GPT-4 has a scaling exponent of 0.127. To draw some analogies, some simple examples of power laws are areas vs length (e.g. <em>area = length²</em> ) , volume vs length ( e.g. <em>volume = length³ </em>) , density vs linewidth ( e.g <em>areal</em> <em>density</em> = 1/<em>linewidth²</em>). By that analogy, the parameters could be in 1/0.127 ≈ 8 , 1/0.14 ≈ 7 , or 1/.19 ≈ 5 dimensional spaces that gets projected by the transformer network to loss. Like length, loss is 1 dimensional.</p><p>As shown in the previous section, it is possible to express the number of parameters in terms of just <em>dmodel. </em>The exponent then becomes 3/8 , which is better than 0.127 but could be still higher. At the end of the day, the embedding size, <em>dmodel</em>, appears to dictate the number of parameters, <em>N</em> or <em>nparams ∝ 12*dmodel³ </em>, the pretraining compute , <em>6N ∝ 72*dmodel³ </em>, and <em>loss -1 = Mc/dmodel ^ (3/8)</em> .</p><p>The number of parameters , hence compute increases by power of 3 whereas loss decreases only by power of -3/8.</p><p><strong>Appendix:</strong></p><p><strong>Entropy:</strong></p><p>In information theory, the entropy of a random variable quantifies the average level of uncertainty or information associated with the variable’s potential states or possible outcomes. The entropy, in this context, is the <em>expected</em> number of bits of information contained in each message, taken over all possibilities of the transmitted message.</p><p>The <a href="https://en.wikipedia.org/wiki/Information_content"><em>information content</em></a><em>,</em> also called the <em>surprisal</em> or <em>self-information,</em> of an event <em>E</em> is a function which increases as the probability <em>p(E)</em> of an event decreases. When <em>p(E)</em>is close to 1, the <em>surprisal</em> of the event is low, but if <em>p(E)</em> is close to 0, the <em>surprisal</em> of the event is high. This relationship is described by the function <em>log (1/p(E)) .</em></p><p>The Shannon Entropy, <em>H</em>, in units of bits (per symbol), is expressed by the following equation. where <em>pi</em> is the probability of occurrence of the <em>i</em>-th possible value of the source symbol.</p><p><em>H = ∑ᵢ pᵢ log</em>₂<em> (pᵢ)</em></p><p>The above equation expresses the entropy in the units of “bits” (per symbol) as it uses base 2 logarithm. Intuitively, the entropy <em>H(X)</em> of a discrete random variable <em>X</em> is a measure of the amount of <em>uncertainty</em> associated with the value of <em>X</em> when only its distribution is known. The more bits there are in entropy, the more uncertainty or information there are in the message</p><p><strong>Cross-Entropy Loss:</strong></p><p>The formula for cross-entropy loss is</p><p><em>— Σᵢ qᵢ * log(pᵢ)</em></p><p>Where <em>qᵢ</em> represents the true probability of class <em>i</em> and <em>pᵢ</em> represents the predicted probability of class <em>i</em>, and the summation is taken over all classes. Essentially, it is the expected value of log of the observed probability. .</p><p>For binary classification, where there are only two classes, the formula simplifies to:</p><p><em>— (q * log(p) + (1-q) * log(1-p))</em></p><p>The definition of Cross-Entropy Loss can also be formulated using the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Kullback–Leibler divergence</a>, <em>DKL(p∥q)</em>, divergence of p from q. Also known as the <em>relative entropy</em> of p with respect to q.</p><p><em>H(q,p)=H(q)+DKL(q∥p)</em></p><p>where <em>H(q)</em> is the <a href="https://en.wikipedia.org/wiki/Information_entropy">entropy</a> of q the true distribution. For discrete probability distributions p and q with the same support X , <em>DKL</em> boils down to</p><p><em>H(q,p)=− Σᵢ qᵢ * log(pᵢ), ∀i∈X</em></p><p>Gibbs’ inequality states that the Kullback-Leibler divergence is always positive. It can be 0 if and only if <em>p=q . </em>Hence, the cross-entropy cost function is minimized when the distributions , predicted and true, are identical.</p><p><strong>Categorical Entropy and Cross Entropy Calculations:</strong></p><p>Categorical Entropy is when there are a number of categories each with certain probability. The cross entropy is taken over the number of categories</p><p><em>H(q,p)=− Σᵢ qᵢ * log(pᵢ), ∀i∈C, </em>where <em>C </em>is the set of categories.</p><p>To calculate the true probability, is 1 for one category and 0 for all other categories. Its value is 1 (e.g. <em>Σ1ᵢ</em>/N = 1 , for <em>N</em> samples).</p><p>Hence , the Categorical Cross Entropy Loss becomes</p><p><em>loss = — Σ (qi * log(pi)) = -log(pj), where qi=1 , for i=j and qi=0 for i!= j</em></p><p><strong>Softmax:</strong></p><p>In multi-class classification, softmax function is usually applied to the model’s output to make them look like probabilities that sum to 1 before calculating the cross-entropy loss. It is defined as:</p><p><em>softmax(x</em>ᵢ<em>)=exp⁡(x</em>ᵢ<em>) / ∑</em>ⱼ<em> exp⁡(x</em>ⱼ<em>)</em></p><p><strong>Derivation of <em>loss-1</em> Equation:</strong></p><p><em>loss-1 = (Nc/N)^αN ∝ (Nc/(C/6) ) ^ (αN)</em></p><p><em>= (Nc)^(αN)/ (C/6)^(αN)</em></p><p>= <em>(Nc)^(αN) * 6^(αN) / ©^(αN)</em></p><p>= <em>(6*Nc)^(αN) / C^(αN)</em></p><p>= <em>(6*Nc)^(αN) * C^-(αN)</em></p><p>=&gt; <em>αN = 0.127</em></p><p><strong>GPT Model Sizes and Computes:</strong></p><p>According to information available on Hugging Face, GPT-2 XL was trained using 32 TPUv3 chips for approximately 168 hours. TPUv3 can do 123 TFLOPs of BF16. Hence C = 123e12*32*168/(24e15) = 27.55 petaflop/s-days (PFsD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*tuEYpRKMM8bwuIBnb5d1Nw.png" /><figcaption>GPT-3 model sizes and pre-raining computes,</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*SHCeuw3EYWrHW3PmcKD3sg.png" /><figcaption>GPT-3 dmodel vs nlayers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*slMYrrSei5UoAZSCYPUMdA.png" /><figcaption>GPT-3 nhead vs nlayers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*nzxSnOwdMZxq_A6z7AsxuA.png" /><figcaption>GPT-3 nparams vs dmodel</figcaption></figure><p><strong>Multihead Self Attention:</strong></p><p><em>ScaledDotProductAttention(Q, K, V ) = SDPA(Q, K, V )</em></p><p><em>SDPA(Q, K, V ) = softmax(Q.transpose(K) /sqrt(dk) ).V</em></p><p><em>MultiHead(Q, K, V ) = Concat(head1, …, headh).WO</em></p><p><em>headi = SDPA(Qi , Ki , Vi )</em></p><p><em>Qi</em> = x.<em>WQi, Ki</em> = x.<em>WKi, Vi=</em>x.<em>WVi</em></p><p>The projection matrices shapes are as follows:</p><p><em>WQi: dim×dk , WKi:dim×dk , WVi:dim×dv WO:hdv×dim</em></p><p><em>dk = dv = dim/h = dhead</em></p><p><strong>GPT Parameter Calculations (Chinchilla paper) :</strong></p><p>Size relationships:</p><ul><li>key_size = d_model/num_heads</li><li>ffw_size = 4*key_size</li></ul><p>Parameters in different parts of GPT network (ignores bias):.</p><ul><li>Embeddings: vocab_size × d_model</li><li>Attention (Single Layer) <br>-Key, query and value projections: 3 × d_model × (key_size × num_heads) <br>-Key @ Query logits: 0<br>-Softmax: 0<br>-Softmax @ query reductions: 0<br>-Final Linear: (key_size × num_heads) × d_model</li><li>Dense Block (Single Layer) : (d_model × ffw_size + ffw_size × d_model )</li><li>Final Logits: d_model × vocab_size</li><li>Total non-embedding parameters (<em>N</em>) <em>≈ nlayers * (</em>attention + dense) =<em> nlayers * ( 4*dmodel² + 2*4*dmodel² ) = 12*nlayers * dmodel²</em></li><li>For <em>nlayers &gt;&gt; 10</em> , <em>nlayers </em>=<em> 144*dmodel </em>(see Appendix on GPT-3): <br>- hence,<em> N </em>= 1728*<em>dmodel³</em></li></ul><p><strong>GPT FLOPs Calculations (Chinchilla paper):</strong></p><p>For large models the FLOP and parameter contribution of embedding matrices is small. They used a factor of 2 to describe the multiply accumulate cost. For the forward pass, the considered contributions as below. The line starting with ‘# ‘ shows the shapes of each layer.</p><ul><li>Embeddings — 2 × seq_len × vocab_size × d_model <br># (seq_len, vocab_size) . ( vocab_size, d_model ) = (seq_len, d_model)</li><li>Attention (Single Layer) <br>-Key, query and value projections: 2 × 3 × seq_len × d_model × (key_size × num_heads) <br># (seq_len, d_model) . (d_model, key_size) = (seq_len, key_size ) , for each key/query/value and head<br>-Key @ Query logits: 2 × seq_len × seq_len × (key_size × num_heads) <br># (seq_len, key_size ) . (seq_len, key_size)^T = (seq_len, seq_len), for each head<br>-Softmax: 3 × num_heads × seq_len × seq_len <br># exponentiation, summation, and division of each element <br>-Softmax @ query reductions (e.g. <em>.V</em> ): 2 × seq_len × seq_len × (key_size × num_heads) <br># (seq_len, seq_len) . (seq_len, key_size ) = (seq_len, key_size ), for each head<br>-Final Linear (e.g. .WO) : 2 × seq_len × (key_size × num_heads) × d_model <br>#(seq_len, num_heads*key_size ) . (num_heads *key_size, d_model)= (seq_len, d_model)</li><li>Dense Block (Single Layer) — 2 × seq_len × (d_model × ffw_size + d_model × ffw_size) <br># (seq_len, d_model) . (d_model, ffw_size) . (ffw_size, d_model) = (seq_len, d_model)</li><li>Final Logits — 2 × seq_len × d_model × vocab_size <br>#(seq_len, d_model) . (d_model, vocab_size) = (seq_len, vocab_size)</li><li>Total forward pass FLOPs: embeddings+num_layers× (total_attention+dense_block) + logits</li></ul><p>The above is more accurate than the , <em>C ≈ 6N, </em>used in the 2020 Scaling Laws paper, as it includes embedding parameters also. However, still not accurate as it does not include the bias. The bias is just elementwise addition , hence compared to other calculations can be ignored.</p><p><strong>GPT-4 Abstracted and Augmented Data :</strong></p><p>The following table shows the data extracted from the loss vs realtive compute figure of the GPT-4 paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*cMqnu7zziZAuoY0P4qglfw.png" /><figcaption>Extracted data from the GPT-4 paper loss-relative-compute figure.</figcaption></figure><p><strong>References:</strong></p><ol><li>GPT-4 Technical Report, <a href="https://arxiv.org/pdf/2303.08774">https://arxiv.org/pdf/2303.08774</a></li><li>Scaling Laws for Autoregressive Generative Modeling, <a href="https://arxiv.org/abs/2010.14701">https://arxiv.org/abs/2010.14701</a></li><li>Language Models are Few-Shot Learners ( GPT-3) , <a href="https://arxiv.org/pdf/2005.14165">https://arxiv.org/pdf/2005.14165</a></li><li>Chinchilla, Training Compute-Optimal Large Language Models, <a href="https://arxiv.org/pdf/2203.15556">https://arxiv.org/pdf/2203.15556</a></li><li>Prediction and Entropy of Printed English, <a href="https://www.princeton.edu/~wbialek/rome/refs/shannon_51.pdf">https://www.princeton.edu/~wbialek/rome/refs/shannon_51.pdf</a></li><li><a href="https://stats.stackexchange.com/questions/211858/how-to-compute-bits-per-character-bpc">https://stats.stackexchange.com/questions/211858/how-to-compute-bits-per-character-bpc</a></li><li><a href="https://en.wikipedia.org/wiki/Information_theory">https://en.wikipedia.org/wiki/Information_theory</a></li><li><a href="https://en.wikipedia.org/wiki/Cross-entropy">https://en.wikipedia.org/wiki/Cross-entropy</a></li><li><a href="https://brilliant.org/wiki/entropy-information-theory/">https://brilliant.org/wiki/entropy-information-theory/</a></li><li>Chapter 6- Deep Feedforward Network s<a href="https://www.deeplearningbook.org/contents/mlp.html">https://www.deeplearningbook.org/contents/mlp.html</a></li><li>Cross-Entropy Loss: Make Predictions with Confidence, <a href="https://www.pinecone.io/learn/cross-entropy-loss/">https://www.pinecone.io/learn/cross-entropy-loss/</a></li><li><a href="https://www.iitg.ac.in/cseweb/osint/slides/Anasua_Entropy.pdf">https://www.iitg.ac.in/cseweb/osint/slides/Anasua_Entropy.pdf</a></li><li>Maximum Likelihood Estimation, <a href="https://online.stat.psu.edu/stat504/lesson/1/1.5">https://online.stat.psu.edu/stat504/lesson/1/1.5</a></li><li>Neural scaling law, <a href="https://en.wikipedia.org/wiki/Neural_scaling_law">https://en.wikipedia.org/wiki/Neural_scaling_law</a></li><li>Are bigger AI models better?, linkedin.com/pulse/bigger-ai-models-better-nigel-toon-gedue</li><li>TPU V3 , <a href="https://cloud.google.com/tpu/docs/v3">https://cloud.google.com/tpu/docs/v3</a></li><li>Scaling Laws — O1 Pro Architecture, Reasoning Training Infrastructure, Orion and Claude 3.5 Opus “Failures” AI Lab Synthetic Data Infrastructure, Inference Tokenomics of Test Time Compute, The Data Wall, Evaluation’s are Broken, RLAIF, Inference Time Search, Scale Needed More Than Ever, <a href="https://semianalysis.com/2024/12/11/scaling-laws-o1-pro-architecture-reasoning-infrastructure-orion-and-claude-3-5-opus-failures/">https://semianalysis.com/2024/12/11/scaling-laws-o1-pro-architecture-reasoning-infrastructure-orion-and-claude-3-5-opus-failures/</a></li><li>Visual Autoregressive Modeling: Scalable Image<br>Generation via Next-Scale Prediction, <a href="https://openreview.net/pdf?id=gojL67CfS8">https://openreview.net/pdf?id=gojL67CfS8</a></li><li>Hausdorff dimension, <a href="https://en.wikipedia.org/wiki/Hausdorff_dimension">https://en.wikipedia.org/wiki/Hausdorff_dimension</a></li><li>Notes on Contemporary Machine Learning for Physicists, <a href="https://sites.krieger.jhu.edu/jared-kaplan/files/2019/04/ContemporaryMLforPhysicists.pdf">https://sites.krieger.jhu.edu/jared-kaplan/files/2019/04/ContemporaryMLforPhysicists.pdf</a></li><li>The Ultra-Scale Playbook: Training LLMs on GPU Clusters, <a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook">https://huggingface.co/spaces/nanotron/ultrascale-playbook</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5665250b41c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood of Llama 3.1 70B Distributed Inference]]></title>
            <link>https://whatdhack.medium.com/under-the-hood-of-llama-3-1-70b-distributed-inference-8b3c03886f22?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b3c03886f22</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[model-parallelism]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 02:26:54 GMT</pubDate>
            <atom:updated>2024-09-03T02:26:54.275Z</atom:updated>
            <content:encoded><![CDATA[<p>The following are some notes on how the Llama 3.1 70B model works in distributed environment. Will focus only on the pure PyTorch implementation which uses the <em>fairscale</em> library. <em>Fairscale</em> library is a fork of the Nvidia <em>Megatron-LM</em> library. The Llama 3 and 3.1 models are the same, hence in the following will refer to them as Llama 3.</p><p><strong>Transformer and Attention Recap:</strong></p><p>The Transformer at block diagram level, show below, consists of 2 parts — Attention and Feed Forward Network ( FFN) or Multi Layer Perceptron ( MLP)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*gkFPTsYCWo2TJnqtZl7z0g.png" /><figcaption><strong>Fig 1 : Transformer architecture ( from Megatron-LM paper)</strong></figcaption></figure><p>Attention function is a mapping of a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of value.</p><p><em>Attention(Q, K, V ) = softmax(Q.transpose(K) /sqrt(dk) ).V</em></p><p>To counteract vanishing gradient effect, the dot product is scaled down by <em>sqrt(dk) .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*-6w5tc6tOKIsBmH0.png" /><figcaption><strong>Fig 2: Attention (from Attention Is All You Need)</strong></figcaption></figure><p>In multi-head attention, instead of performing a single attention function with <em>dim</em>-dimensional keys, values and queries, each head linearly projects the queries, keys and values with different linear projections (learned) to <em>dk</em>, <em>dk</em> and <em>dv</em> dimensions respectively. On each of these projected queries, keys and values, attention is performed in parallel, yielding <em>dv</em>-dimensional output values. The <em>h</em> values are concatenated and once again projected for the final output with dimension <em>dmodel .</em></p><p><em>MultiHead(Q, K, V ) = Concat(head1, …, headh).WO</em></p><p><em>headi = Attention(Q.WQi , K.WKi , V.WVi )</em></p><p>The projection matrices shapes are as follows:</p><p><em>WQi: dim×dk , WKi:dim×dk , WVi:dim×dv WO:hdv×dim</em></p><p>The dimension of sub-head key, query and value dimensions are related as follows:</p><p><em>dk = dv = dim/h = dhead</em></p><p>The benefit of multi-head attention is that it allows the model to jointly attend to information from different representation subspaces at different positions ( because of the order of the <em>concat</em> ). This split is not possible with single attention head, as dot product removes any positional dependency.</p><p>The second part of the Transformer, the Feed Forward Network, is composed of 2 linear layers with <em>dim * dff </em>and<em> dff*dmodel </em>shapes<em>.</em></p><p><strong>Llama 3 Model — Single Process:</strong></p><p>The top level <a href="https://github.com/meta-llama/llama-models/blob/main/models/llama3/reference_impl/generation.py#L62">Llama 3 reference implementation code</a> implements <em>generation</em>, <em>chat_completion</em> , <em>text_completion</em>, as shown in the following figure. Both <em>chat_completion</em> and <em>text_completion </em>methods<em> </em>provide<em> </em>tokenization<em> </em>code and returns objects<em> ChatPrediction</em> and <em>CompletionPrediction</em> respectively. Both objects use the same tokenizer, but <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/generation.py#L49"><em>ChatPrediction</em></a> uses a <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/api/chat_format.py#L23"><em>ChatFormatter</em></a><em> o</em>bject on top of the tokenizer.<em> </em>Both methods calls<em> generation. T</em>he <em>generation</em> method calls the model’s <em>forward</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*pnra2yb-YvaLDcowv4Yjvg.png" /><figcaption><strong>Fig 3: Top level Llama 3 code.</strong></figcaption></figure><p>In the code <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/generation.py#L62">Llama3 70B</a> model is called <em>Transformer</em>, although it is more than Transformer. It is composed of 3 parts — <em>VocabParallelEmbedding</em> , <em>TransformerBlock</em>, and a final normalization+linear layer. <em>TransformerBlock </em>appears to be the<em> </em>commonly considered Transformer<em>.</em></p><pre>Transformer(                                     <br>  (tok_embeddings): VocabParallelEmbedding()                    <br>  (layers): ModuleList(                                         <br>    (0-79): 80 x TransformerBlock(                                <br>      (attention): Attention(                                   <br>        (wq): ColumnParallelLinear()                            <br>        (wk): ColumnParallelLinear()                            <br>        (wv): ColumnParallelLinear()                            <br>        (wo): RowParallelLinear()                               <br>      )                                                         <br>      (feed_forward): FeedForward(                              <br>        (w1): ColumnParallelLinear()                            <br>        (w2): RowParallelLinear()                               <br>        (w3): ColumnParallelLinear()                            <br>      )                                                         <br>      (attention_norm): RMSNorm()                               <br>      (ffn_norm): RMSNorm()                                     <br>    )                                                           <br>  )                                                             <br>  (norm): RMSNorm()                                             <br>  (output): ColumnParallelLinear()                              <br>)                      </pre><p>First, strings are tokenized in an application , say <em>example_</em><a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/scripts/example_chat_completion.py#L50"><em>chat_completion</em></a>, by a <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/generation.py#L129"><em>tokenizer</em></a> and then embedded into a latent space by <a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L129C1-L149C22"><em>VocabParallelEmbedding</em></a>.</p><pre>  # VocabParallelEmbedding<br>  def forward(self, input_: torch.Tensor) -&gt; torch.Tensor:  # type: ignore<br>        # Build the mask.<br>        input_mask = (input_ &lt; self.vocab_start_index) | (input_ &gt;= self.vocab_end_index)<br>        # Mask the input.<br>        masked_input = input_.clone() - self.vocab_start_index<br>        masked_input[input_mask] = 0<br>        # Get the embeddings.<br>        output_parallel = F.embedding(<br>            masked_input,<br>            self.weight,<br>            self.padding_idx,<br>            self.max_norm,<br>            self.norm_type,<br>            self.scale_grad_by_freq,<br>            self.sparse,<br>        )<br>        # Mask the output embedding.<br>        output_parallel[input_mask, :] = 0.0<br>        # Reduce across all the model parallel GPUs.<br>        output = reduce_from_model_parallel_region(output_parallel)<br>        return output</pre><p>Then the embedded values enter the <em>TransformerBlock. TransformerBlock</em> is composed of Attention and MLP/Feed-Forward operations. In case of a single GPU or non-distributed execution, <em>model_parallel_size</em> is 1. Which makes local and global sizes same.</p><pre><br>class Attention(nn.Module):<br>    def __init__(self, args: ModelArgs):<br>        super().__init__()<br>        self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads<br>        model_parallel_size = fs_init.get_model_parallel_world_size()<br>        self.n_local_heads = args.n_heads // model_parallel_size<br>        self.n_local_kv_heads = self.n_kv_heads // model_parallel_size<br>        self.n_rep = self.n_local_heads // self.n_local_kv_heads<br>        self.head_dim = args.dim // args.n_heads<br><br>        self.wq = ColumnParallelLinear(<br>            args.dim,<br>            args.n_heads * self.head_dim,<br>            bias=False,<br>            gather_output=False,<br>            init_method=lambda x: x,<br>        )<br>        self.wk = ColumnParallelLinear(<br>            args.dim,<br>            self.n_kv_heads * self.head_dim,<br>            bias=False,<br>            gather_output=False,<br>            init_method=lambda x: x,<br>        )<br>        self.wv = ColumnParallelLinear(<br>            args.dim,<br>            self.n_kv_heads * self.head_dim,<br>            bias=False,<br>            gather_output=False,<br>            init_method=lambda x: x,<br>        )<br>        self.wo = RowParallelLinear(<br>            args.n_heads * self.head_dim,<br>            args.dim,<br>            bias=False,<br>            input_is_parallel=True,<br>            init_method=lambda x: x,<br>        )<br><br>        self.cache_k = torch.zeros(<br>            (<br>                args.max_batch_size,<br>                args.max_seq_len,<br>                self.n_local_kv_heads,<br>                self.head_dim,<br>            )<br>        ).cuda()<br>        self.cache_v = torch.zeros(<br>            (<br>                args.max_batch_size,<br>                args.max_seq_len,<br>                self.n_local_kv_heads,<br>                self.head_dim,<br>            )<br>        ).cuda()</pre><p>The input is projected and processed parallelly by each head. The shapes of <em>x</em>, w<em>q</em>, w<em>k</em>, w<em>v, xq</em>, <em>xk</em>, and <em>xv </em>are shown below<em>.</em></p><pre># the shapes in the comment are for the 70B model. <br>x      : (bsz, seqlen, args.dim) # (1,30,4096), for the specific input used<br><br>wq,    : (args.dim, args.n_heads * self.head_dim ) # (512, 4096) per GPU<br>wk, wv : (args.dim, self.n_kv_heads * self.head_dim)  # (64, 4096)<br>wo     : (elf.n_heads * self.head_dim, args.dim,)  # (4096, 512)<br><br>xq     : ( bsz, seqlen, args.n_heads * self.head_dim ) # (1, 30, 512)<br>xk, xv : ( bsz, seqlen, args.n_kv_heads * self.head_dim ) # ( 1, 30 , 64)<br></pre><p><em>xq</em>, <em>xk</em>, and <em>xv</em> are further reshaped to have an additional dimension for local GPU. Then Rotary Embedding is applied to <em>xq</em> and <em>xk </em>for keeping positional information<em>.</em></p><pre>    # Attention<br>    def forward(<br>        self,<br>        x: torch.Tensor,<br>        start_pos: int,<br>        freqs_cis: torch.Tensor,<br>        mask: Optional[torch.Tensor],<br>    ):<br>        bsz, seqlen, _ = x.shape<br>        xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)<br><br>        xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)<br>        xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)<br>        xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)<br><br>        xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)<br></pre><p>Llama 3 uses Group Query Attention ( GQA) , where one KV head feeds multiple query heads .</p><pre># repeat k/v heads if n_kv_heads &lt; n_heads<br>        keys = repeat_kv(<br>            keys, self.n_rep<br>        )  # (bs, cache_len + seqlen, n_local_heads, head_dim)<br>        values = repeat_kv(<br>            values, self.n_rep<br>        )  # (bs, cache_len + seqlen, n_local_heads, head_dim)</pre><p>Hence they become of shapes as shown below. <em>xq</em>’s 3rd dimension is 8x compared to <em>xk’</em>s and <em>xv’</em>s reflecting 1 KV head feeding to 8 Query heads.</p><pre>xq     : (bsz, seqlen, args.n_local_heads, self.head_dim) # ( 1, 30, 8, 64) <br>xk, xv : (bsz, seqlen, args.n_local_kv_heads, self.head_dim ) # (1, 30, 1, 64)<br><br>keys, values : (bsz, args.n_local_kv_heads, seqlen+=1, self.head_dim ) # (1, 8, 98, 64)</pre><p>Then the KV cache is populated. The KV cache is a performance optimization for improving inference latency. The <em>xk</em> and <em>xv</em> tensors are expand to <em>keys</em> and <em>values</em> that store all the previous <em>xk</em> and <em>xv’s. </em>This<em> </em>eliminates re-computation, hence lowers latency. During each step, the 3rd dimension, sequence length, increases by 1 for both <em>keys</em> and <em>values, </em>and can grow to the context length of <em>args.max_seq_len</em> .</p><pre># Attention<br>        self.cache_k = self.cache_k.to(xq)<br>        self.cache_v = self.cache_v.to(xq)<br><br>        self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk<br>        self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv<br><br>        keys = self.cache_k[:bsz, : start_pos + seqlen]<br>        values = self.cache_v[:bsz, : start_pos + seqlen]</pre><p>Then, attention is applied.</p><pre># Attention<br>xq = xq.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)<br>keys = keys.transpose(1, 2)  # (bs, n_local_heads, cache_len + seqlen, head_dim)<br>values = values.transpose(<br>    1, 2<br>)  # (bs, n_local_heads, cache_len + seqlen, head_dim)<br>scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)<br>if mask is not None:<br>    scores = scores + mask  # (bs, n_local_heads, seqlen, cache_len + seqlen)<br>scores = F.softmax(scores.float(), dim=-1).type_as(xq)<br>output = torch.matmul(scores, values)  # (bs, n_local_heads, seqlen, head_dim)<br>output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1) # concatenation, (bs, seqlen, head_dim*n_local_heads) <br>return self.wo(output)</pre><p>After that , MLP/FeedForward block is applied.</p><pre>    # TransformerBlock<br>    def forward(<br>        self,<br>        x: torch.Tensor,<br>        start_pos: int,<br>        freqs_cis: torch.Tensor,<br>        mask: Optional[torch.Tensor],<br>    ):<br>        h = x + self.attention(self.attention_norm(x), start_pos, freqs_cis, mask)<br>        out = h + self.feed_forward(self.ffn_norm(h))<br>        return out</pre><p><a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/model.py#L218"><em>FeedForward</em></a> is composed of 2 linear and 1 element-wise (*) layers.</p><pre>class FeedForward(nn.Module):<br>    def __init__(<br>        self,<br>        dim: int,<br>        hidden_dim: int,<br>        multiple_of: int,<br>        ffn_dim_multiplier: Optional[float],<br>    ):<br>        super().__init__()<br>        hidden_dim = int(2 * hidden_dim / 3)<br>        # custom dim factor multiplier<br>        if ffn_dim_multiplier is not None:<br>            hidden_dim = int(ffn_dim_multiplier * hidden_dim)<br>        hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)<br><br>        self.w1 = ColumnParallelLinear(<br>            dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x<br>        )<br>        self.w2 = RowParallelLinear(<br>            hidden_dim, dim, bias=False, input_is_parallel=True, init_method=lambda x: x<br>        )<br>        self.w3 = ColumnParallelLinear(<br>            dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x<br>        )<br><br>    def forward(self, x):<br>        return self.w2(F.silu(self.w1(x)) * self.w3(x))</pre><p>A <em>RMSNorm</em> layer follows the <em>TransformerBlock</em> layers. The final <em>ColumnParallelLinear</em> layer does a final linear de-embeds to the token space.</p><pre>class Transformer(nn.Module):<br>    def __init__(self, params: ModelArgs):<br>        super().__init__()<br>        self.params = params<br>        self.vocab_size = params.vocab_size # 128256<br>        self.n_layers = params.n_layers # 80<br><br>        self.tok_embeddings = VocabParallelEmbedding(<br>            params.vocab_size, params.dim, init_method=lambda x: x<br>        )<br><br>        self.layers = torch.nn.ModuleList()<br>        for layer_id in range(params.n_layers):<br>            self.layers.append(TransformerBlock(layer_id, params))<br><br>        self.norm = RMSNorm(params.dim, eps=params.norm_eps)<br>        self.output = ColumnParallelLinear(<br>            params.dim, params.vocab_size, bias=False, init_method=lambda x: x<br>        )<br><br>        self.freqs_cis = precompute_freqs_cis(<br>            params.dim // params.n_heads,<br>            params.max_seq_len * 2,<br>            params.rope_theta,<br>            params.use_scaled_rope,<br>        )<br><br>    @torch.inference_mode()<br>    def forward(self, tokens: torch.Tensor, start_pos: int):<br>        _bsz, seqlen = tokens.shape<br>        h = self.tok_embeddings(tokens)<br>        self.freqs_cis = self.freqs_cis.to(h.device)<br>        freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen]<br><br>        mask = None<br>        if seqlen &gt; 1:<br>            mask = torch.full((seqlen, seqlen), float(&quot;-inf&quot;), device=tokens.device)<br><br>            mask = torch.triu(mask, diagonal=1)<br><br>            # When performing key-value caching, we compute the attention scores<br>            # only for the new sequence. Thus, the matrix of scores is of size<br>            # (seqlen, cache_len + seqlen), and the only masked entries are (i, j) for<br>            # j &gt; cache_len + i, since row i corresponds to token cache_len + i.<br>            mask = torch.hstack(<br>                [torch.zeros((seqlen, start_pos), device=tokens.device), mask]<br>            ).type_as(h)<br><br>        for layer in self.layers:<br>            h = layer(h, start_pos, freqs_cis, mask)<br>        h = self.norm(h) # (bsz,seqlen,4096)<br>        output = self.output(h).float() # sel.output ( 4096, 128256) <br>        return output # (bsz,seqlen,128256)</pre><p><strong>Llama 3 70B Model Parallel Inference Collectives :</strong></p><p>The 70B model uses a 8-GPU Tensor Parallel model. The model code calls it Model Parallel. The Model uses <a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L218"><em>ColumnParallelLinear</em></a>, <a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L299"><em>RowParallelLinear</em></a>, and <a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L84"><em>VocabParallelEmbedding</em></a>. These 3 operations involve collective calls. The following , taken from the source code, explains the 3 distributed compute behaviors.</p><p><a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L218"><em>ColumnParallelLinear</em></a><em> </em>sets the <em>weight</em> to <em>out_features</em> divided by the number GPUs. Similarly <em>RowParallelLinear</em> sets the <em>weight</em> to <em>in_features</em> divided by the number GPUs</p><pre>class VocabParallelEmbedding(torch.nn.Module):<br>    &quot;&quot;&quot;Embedding parallelized in the vocabulary dimension.<br><br>    This is mainly adapted from torch.nn.Embedding and all the default<br>    values are kept.<br>    Arguments:<br>        num_embeddings: vocabulary size.<br>        embedding_dim: size of hidden state.<br>        init_method: method to initialize weights.<br>    &quot;&quot;&quot;</pre><pre>class ColumnParallelLinear(torch.nn.Module):<br>    &quot;&quot;&quot;Linear layer with column parallelism.<br><br>    The linear layer is defined as Y = XA + b. A is parallelized along<br>    its second dimension as A = [A_1, ..., A_p].<br><br>    Arguments:<br>        in_features: first dimension of matrix A.<br>        out_features: second dimension of matrix A.<br>        bias: If true, add bias<br>        gather_output: If true, call all-gather on output and make Y avaiable<br>                       to all GPUs, otherwise, every GPU will have its output<br>                       which is Y_i = XA_i<br>        init_method: method to initialize weights. Note that bias is always set<br>                     to zero.<br>        stride: For the strided linear layers.<br>        keep_master_weight_for_test: This was added for testing and should be<br>                                     set to False. It returns the master weights<br>                                     used for initialization.<br>    &quot;&quot;&quot;<br>    self.weight = Parameter(torch.Tensor(self.output_size_per_partition, self.in_features))</pre><pre>class RowParallelLinear(torch.nn.Module):<br>    &quot;&quot;&quot;Linear layer with row parallelism.<br><br>    The linear layer is defined as Y = XA + b. A is parallelized along<br>    its first dimension and X along its second dimension as:<br>               -   -<br>              | A_1 |<br>              | .   |<br>          A = | .   |        X = [X_1, ..., X_p]<br>              | .   |<br>              | A_p |<br>               -   -<br>    Arguments:<br>        in_features: first dimension of matrix A.<br>        out_features: second dimension of matrix A.<br>        bias: If true, add bias. Note that bias is not parallelized.<br>        input_is_parallel: If true, we assume that the input is already<br>                           split across the GPUs and we do not split<br>                           again.<br>        init_method: method to initialize weights. Note that bias is always set<br>                     to zero.<br>        stride: For the strided linear layers.<br>        keep_master_weight_for_test: This was added for testing and should be<br>                                     set to False. It returns the master weights<br>                                     used for initialization.<br>    &quot;&quot;&quot;<br>    self.weight = Parameter(torch.Tensor(self.out_features, self.input_size_per_partition))</pre><p><strong>Llama 3 70B Model Parallel Inference Algebra :</strong></p><p>The following figure pictorially shows the Tensor Parallel versions of Attention and FFN. As the Megatron-LM paper shows, in inference only the forward pass is required, hence <em>f</em> is an <em>identity</em> ( or copy) operator and <em>g</em> is an <em>allreduce</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*fghcOrcGCUQGHRqFCrtoYA.png" /><figcaption><strong>Fig 4: Tensor Parallel Attention and MLP — from the Megatron-LM paper.</strong></figcaption></figure><p>The linear algebraic representation of the distributed execution is as follows.</p><pre># 2 layer FFN <br>Y = nl(XA)<br>Z = YB<br><br>A = {A1 A2] # column wise partition across GPUs<br>Y = [Y1 Y2] = [ nl(XA1) nl(XA2) ]<br>B = [ B1    # row wise partition across GPUs<br>      B2]<br>Z = [ Y1 Y2] [ B1   = [Y1B1+Y2B2]  # this requires all reduce <br>               B2 ]<br><br># 1 layer linear <br>Y = nl(X)A<br>A = {A1 A2] # column wise partition<br>Y = [Y1 Y2] = nl(X)[ A1 A2] = [nl(X)A1 nl(X)A2] #  this require allgather <br><br># Attention<br># ignoring softmax and scaling, they are within each Query head<br># scaling is also elementwise<br># each GPU runs a number of query heads independently<br>X = concat(QiKiVi) # concatenation acorss all GPUs<br># concat(QiiKijVij) - concatenation within GPU j <br>Y = XO = concat(QiKiVi)O = [concat(Qi1Ki1Vi1) concat(Qi2Ki2Vi2)][O1 #allreduce<br>                                                                 O2]</pre><p><strong>Llama 3 70B Model Parallel Inference :</strong></p><p>Pictorially the Llama 3 Model Parallel execution somewhat looks like following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*dLLp7Sk884EQSf8EqPFh_w.png" /><figcaption><strong>Fig 5: Llama 3 Model Parallel execution</strong></figcaption></figure><p>The input string is tokenized and fed to <em>VocabParallelEmbedding</em> in each of the GPU instances independently. <em>VocabParallelEmbedding</em> parallelizes embedding in the vocabulary dimension. The vocabulary, size 128256, is divided equally among the GPUs, hence 16032. The embedding dimension , <em>params.dim</em>, is 4096. Hence the weight tensor in each GPU is (16032, 4096) . The output from each GPU is <a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L148"><em>allreduced</em></a>. The pseudo call stack is shown below.</p><pre>class VocabParallelEmbedding(torch.nn.Module).forward()<br>  reduce_from_model_parallel_region(output_parallel)<br>    return _reduce(ctx, input_)<br>      torch.distributed.all_reduce(input_, group=group)</pre><p>The embedded tensors then enter the first ( id =0) <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/model.py#L247"><em>TransformerBlock</em></a> . <em>TransformerBlock</em> is the Transformer and is composed of <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/model.py#L115"><em>Attention</em></a> and <a href="https://github.com/meta-llama/llama-models/blob/bf8355fdda0200ca6b924fae96bc1f147311cd19/models/llama3/reference_impl/model.py#L218"><em>FeedForward</em></a> blocks. All the operations are local, except the 2 involving <em>RowParallelLinear — </em>one in attention block and the other in MLP block. They both do <a href="https://github.com/facebookresearch/fairscale/blob/5f484b3545f27eddb19d970fbe1d361b9c5f2b07/fairscale/nn/model_parallel/layers.py#L382"><em>allreduce</em></a>. The pseudo call stack is shown below.</p><pre>class RowParallelLinear(torch.nn.Module).forward()<br>  reduce_from_model_parallel_region(output_parallel)<br>    return _reduce(ctx, input_)<br>      torch.distributed.all_reduce(input_, group=group)</pre><p>Another 79 exactly similar <em>TransformerBlock</em> follows.</p><p>In Multi-Head Attention, each Attention head resides in a one distinct GPU. The overall Attention output is the dot product between concatenated output of the heads and a linear layer <em>WO</em> ( see above in the Attention Recap section). <em>WO</em> is partitioned among the GPUS. hence, this overall dot product operation includes an <em>allreduce</em>.</p><p>The MLP block <em>allreduce</em> is necessary as each GPU<em>i</em> has <em>Xi.Ai.Bi </em>and the full results for MLP is <em>sum</em>( <em>Xi.Ai.Bi) </em>.</p><p>The final <em>ColumnParallelLinear</em> layer following the <em>TransformerBlock</em> layers does an <em>allgather</em> . This <em>allgather</em> collects partial de-embedding to token space results in each GPU into one whole. The pseudo call stack is shown below.</p><pre>class ColumnParallelLinear.forward()<br>  def gather_from_model_parallel_region(input_: torch.Tensor) -&gt; torch.Tensor:<br>    class _GatherFromModelParallelRegion(torch.autograd.Function).forward ()<br>      _gather(input_: torch.Tensor) -&gt; torch.Tensor:)<br>         torch.distributed.all_gather(tensor_list, input_, group=group)</pre><p><strong>Llama 3 Distributed Training :</strong></p><p>Llama 3 models were pre-trained with three types of parallelization: data parallelization (DP) , model/tensor parallelization (MP), and pipeline parallelization (PP) .</p><p>MP applies collective on activations. DP applies collectives on model parameters. PP involves point-to-point communications between GPUs.</p><p>If there is ample memory available, then just DP and MP can be used. Here each of the model parallel GPUs form their own <em>allreduce</em> region at every iteration. Supposing 32 GPUs are divided into 4 by-8 MP regions. Then each GPU from each of the 8-GPU model parallel region forms their own <em>allreduce</em> region. Hence in total, 8 <em>allreduce</em> regions with 4 GPUs each. This combines DP with MP.</p><p>For further memory needs, PP can be added. PP partitions layers among a number of GPU. The parallelization hierarchy then is pipeline, model , then data. Supposing the same 32 GPUs are divided into 4 by-4 MP regions with 2-GPU PP. Then each GPU from each of the 4x2-GPU model and pipeline parallel region forms their own <em>allreduce</em> region. Hence again 8 <em>allreduce</em> regions with 4 GPUs each. This combines DP , MP and PP.</p><p>Continual Pre-training does a full parameter update with new data auto-regressively from a previous checkpoint. It involves the same machinery as in pre-training from scratch, except for less data.</p><p><strong>References:</strong></p><ol><li>Llama 2: Open Foundation and Fine-Tuned Chat Models, <a href="https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/">https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/</a></li><li>Introducing Meta Llama 3: The most capable openly available LLM to date — <a href="https://ai.meta.com/blog/meta-llama-3/">https://ai.meta.com/blog/meta-llama-3/</a></li><li>Introducing Llama 3.1: Our most capable models to date, <a href="https://ai.meta.com/blog/meta-llama-3-1/">https://ai.meta.com/blog/meta-llama-3-1/</a></li><li>(Deprecated) Meta Llama 3, <a href="https://github.com/meta-llama/llama3">https://github.com/meta-llama/llama3</a></li><li>Llama Models, <a href="https://github.com/meta-llama/llama-models">https://github.com/meta-llama/llama-models</a></li><li>Llama Recipes: Examples to get started using the Llama models from Meta, <a href="https://github.com/meta-llama/llama-recipes">https://github.com/meta-llama/llama-recipes</a></li><li>fairscale , <a href="https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/model_parallel/layers.py">https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/model_parallel/layers.py</a></li><li>Megatron-LM: Training Multi-Billion Parameter Language Models Using<br>Model Parallelism, <a href="https://arxiv.org/pdf/1909.08053">https://arxiv.org/pdf/1909.08053</a></li><li>class Llama, <a href="https://github.com/meta-llama/llama-models/blob/main/models/llama3/reference_impl/generation.py#L62">https://github.com/meta-llama/llama-models/blob/main/models/llama3/reference_impl/generation.py#L62</a></li><li>class Transformer(nn.Module),<a href="https://github.com/meta-llama/llama-models/blob/main/models/llama3/reference_impl/model.py#L276"> https://github.com/meta-llama/llama-models/blob/main/models/llama3/reference_impl/model.py#L276</a></li><li>Continual Learning with Pretrained Checkpoints, <a href="https://docs.nvidia.com/nemo-framework/user-guide/latest/llms/allmodels/continuetraining.html">https://docs.nvidia.com/nemo-framework/user-guide/latest/llms/allmodels/continuetraining.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b3c03886f22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-training Mini Versions of LLMs — GPT and Llama3]]></title>
            <link>https://whatdhack.medium.com/pre-training-mini-versions-of-llms-gpt-and-llama3-7cf69ac00280?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf69ac00280</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[pre-training]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 02:00:26 GMT</pubDate>
            <atom:updated>2024-06-17T02:00:26.619Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pre-training Mini Versions of LLMs — GPT and Llama3</h3><p>This blog goes over how to pre-train small versions of the leading open source Large Language Models (LLM). Here 3 models are covered — 2 versions of GPT2 and one Llama3. The code along with the preprocessed/tokenized data is available at — <a href="https://github.com/whatdhack/gpt"><em>https://github.com/whatdhack/</em></a><em>mini_llms</em> . The pre-training and generation is pretty straight forward requiring no special arguments other than <em>— train</em> for training.</p><p>The first few sections go over the Transformer architecture and its evolution to the current GPT2 form. The following sections go over the mini LLM models in details. The final section shows validation loss trend chart and sample generation outputs.</p><p><strong>Transformer ( June 2017)</strong>:</p><p>The following pictures from the <em>Attention Is All You Need</em> (2017) paper show the architecture of the full Transformer model, It includes both the encoder and decoder part. The Transformer addressed the sequential bottleneck of RNN’s used uptill then for sequence modelling (auto-completion, sequence classification, … ) and transduction ( translation, summarization, image captioning, speech-to-text,..).</p><p>Most competitive neural sequence transduction models of circa-2017 had an encoder-decoder structure. The encoder maps an input sequence of symbol representations <em>(x1, …, xn)</em> to a sequence of continuous representations <em>z = (z1, …, zn)</em>. The decoder then generates an output sequence (<em>y1, …, ym)</em> of symbols from <em>z </em>one element at a time. At each step the model is auto-regressive, consuming the previously generated symbols as additional input when generating the next.”</p><p>Each encoder layer has two sub-layers. The first is a <strong>multi-head self-attention mechanism</strong>, and the second is a simple, position-wise fully connected feed-forward network. Residual connection is employed around each of the two sub-layers, followed by layer normalization. The output of each sub-layer is <em>LayerNorm(x + Sublayer(x))</em>, where <em>Sublayer(x)</em> is the function implemented by the sub-layer itself. Residual connection improves accuracy as shown in the paper <em>Deep Residual Learning for Image Recognition</em>. The other issue of vanishing/exploding gradient of deeper network is addressed by normalized initialization and intermediate normalization layers such as <em>LayerNorm</em> . To facilitate residual connections, all sub-layers and embedding layers, produce outputs of dimension <em>dmodel</em> = <em>512</em>.</p><p>In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. As in the encoder, residual connections around each of the sub-layers is employed, followed by layer normalization. The self-attention sub-layer in the decoder stack employs masking to prevent positions from attending to subsequent positions. The masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position <em>i</em> can depend only on the known outputs at positions less than <em>i</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*UxFR9KvTgENK9IKyq__XtQ.png" /><figcaption>(from Attention Is All You Need)</figcaption></figure><p>Attention function is mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of value.</p><p><em>Attention(Q, K, V ) = softmax(Q.transpose(K) /sqrt(dk) ).V</em></p><p>The authors suspected that for large values of <em>dk</em>, the dot products grow large in magnitude, pushing the <em>softmax</em> function into regions where it has extremely small gradients. To counteract this vanishing gradient effect, the authors scaled down the dot products by <em>sqrt(dk) . </em>The authors offered the following explanation. Consider <em>q</em> and <em>k</em> are two independent random variables with mean 0 and variance 1. Then their dot product, <em>q · k = sum i ( qi.ki)</em> has mean 0 and variance <em>dk</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*nPbMU7xIwE3Vqv34rbxSiQ.png" /><figcaption>Fig: (from Attention Is All You Need)</figcaption></figure><p>By using multi-head attention, instead of performing a single attention function with <em>dmodel</em>-dimensional keys, values and queries, the authors linearly project the queries, keys and values <em>h</em> times with different linear projections (learned) to <em>dk</em>, <em>dk</em> and <em>dv</em> dimensions, respectively. On each of these projected queries, keys and values, attention is performed in parallel, yielding <em>dv</em>-dimensional output values. The <em>h</em> values are concatenated and once again projected for he final values with dimension <em>dmodel .</em></p><p><em>MultiHead(Q, K, V ) = Concat(head1, …, headh).WO</em></p><p><em>headi = Attention(Q.WQi , K.WKi , V.WVi )</em></p><p>The projection matrices shapes are as follows:</p><p><em>WQi: dmodel×dk , WKi:dmodel×dk , WVi:dmodel×dv WO:hdv×dmodel</em></p><p>The dimension of sub-head key, query and value dimensions are related as follows:</p><p><em>dk = dv = dmodel/h = dhead</em></p><p>The benefit of multi-head attention is that it allows the model to jointly attend to information from different representation subspaces at different positions ( because of the order of the <em>concat</em> ). This split if not possible with single attention head as averaging inhibits the position dependency.</p><p>The Feed Forward network is composed of 2 linear layers with <em>dmodel * dff </em>and<em> dff*dmodel </em>shapes<em>.</em></p><p><strong>Transformer-Decoder (T-D) (January 2018):</strong></p><p>In the paper <em>Generating Wikipedia by Summarizing Long Sequences (2018)</em>, the authors simplified the Transformer architecture by dropping the encoder. This resulted in 50% reduction in size of the network. To accommodate the new architecture, they also needed to rearrange the output part. For a sequence-transduction example <em>(m1 , …, mn) → (y1 , …, yη )</em>, they concatenated input and output into the sentence <em>(w1 , …, wn+η+1) = (m1 , …, mn, δ, y1 , …, yη )</em>, where <em>δ</em> is a special separator token. Then they trained the model to predict the next word given the previous ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*uJZA7gxIMWnjtaFBNkRROw.png" /><figcaption>Fig: Self-attention as used in the transformer-decoder ( from <em>Generating Wikipedia …)</em></figcaption></figure><p><strong>Generative Pre-Training (GPT 1 and 2 ) (</strong>June 2018, February 2019) :</p><p>The GPT1 architecture was introduced by the authors of paper <em>Improving Language Understanding by Generative Pre-Training</em> (2018) . They used the T-D architecture described above. They trained GPT1 model in 2 steps — unsupervised pre-training and supervised fine tuning. The model applies a multi-headed self-attention operation over the input context tokens followed by position-wise feed forward layers to produce an output distribution over target tokens.</p><p><em>h0 = U.We + Wp</em></p><p><em>hi = Transformer_Decoder_block(h(i−1) )∀i ∈ [1, n]</em></p><p><em>P(u) = softmax(hn.transpose(We))</em></p><p><em>U = (u −k , . . . , u −1 ) </em>is the context vector of tokens</p><p><em>n</em> is the number of layers</p><p><em>We</em> is the token embedding matrix</p><p><em>Wp</em> is the position embedding matrix</p><p>They used SGD optimizer during training to maximize the likelihood of the next token over a context length of <em>k</em> as per the equation below.</p><p><em>L1(U) = sum ( log P ( ui |u(i−k) , . . . , u(i−1) ; Θ) )</em></p><p>The GPT2 architecture and model was published by OpenAI in February 2019. The architecture was essentially same as GPT1 except for the following differences.</p><ol><li>Layer normalization was moved to the input of each sub-block (similar to a pre-activation residual network in ResNet)</li><li>an additional layer normalization was added after the final self-attention block.</li></ol><p>Which results in the following block-diagram view of the architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eQETPO03-5e9TB4e.png" /><figcaption>Fig: GPT2 architecture ( from Wikimedia)</figcaption></figure><p>In addition, a modified initialization which accounts for the accumulation on the residual path with model depth is used. The authors scaled the weights of residual layers at initialization by a factor of 1/ √ N where N is the number of residual layers. The vocabulary is expanded to 50,257. They also increase the context size from 512 to 1024 tokens and a larger batch size of 512 is used.</p><p>The total number of parameters can the estimated as sum of embedding, projection, MLP and final linear layers as follows.</p><p><em>embedding</em> <em>parameters</em> = <em>vocab_size</em>*<em>dmodel </em>+ <em>sequence_length*dmodel</em></p><p><em>projection parameters</em></p><p><em>= nlayers*nhead*( size(WQi)+size(WKi)+size(WVi)+size(WO))</em></p><p><em>= nlayers * nhead * (4*dmodel*dhead)</em></p><p><em>FFN/MLP parameters</em> = <em>dmodel*dff + dff*dmodel</em></p><p><em>Final linear = vocab_size*dmodel</em></p><p><strong>Large Language Model Meta AI (LLama) 1 , 2 and 3 (</strong>February 2023, July 2023, and April 2024<strong>) :</strong></p><p>Meta introduced the 3 models in rapid clip in 2023 and 2024.</p><p>To improve the training stability of Llama1 , the authors normalize the input of each transformer sub-layer, instead of normalizing the output. They used the <em>RMSNorm</em> normalizing function, it being computationally less intensive than <em>LayerNorm</em> . They replaced <em>ReLU</em> with <em>SwiGLU</em>. They removed the absolute positional embeddings, and instead, added rotary positional embeddings (RoPE). Used AdamW optimizer with a cosine learning rate schedule.</p><p>Llama 2, is an updated version of Llama 1, trained on a new mix of publicly available data. The developers increased the size of the pre-training corpus by 40%, doubled the context length of the model ( from 2048 tokens to 4096 tokens) , and adopted grouped-query attention to improve inference scalability for larger models. Uses the same tokenizer as Llama 1 that employs a byte-pair encoding (BPE) algorithm.</p><p>Compared to Llama 2, Llama 3 has a few key improvements. Llama 3 uses a tokenizer with a vocabulary of 128K tokens that encodes language much more efficiently, which leads to substantially improved model performance. To improve the inference efficiency of Llama 3 models, it uses grouped query attention (GQA) across all the model sizes. Llama 3 models were trained on sequences of 8,192 tokens, using a mask to ensure self-attention does not cross document boundaries.</p><p><strong>Little Versions of LLMs:</strong></p><p>The little versions follow the smallest <em>NanoGPT</em> setup with about 10M parameters. These smallmodels can be easily pre-trained on a consumer grade GPU. The dataset is the one described in the <em>nanoGPT</em> repo as <em>shakespeare_char</em>. The prepared data, <em>train.bin</em> and <em>val.bin</em>, are in the <em>data</em> directory of the repository.</p><p>Each model is fully contained in 1 file. The tokenizer used is the same 65 token GPT2 one from <em>tiktoken</em>. The embedding part of the <em>nano_gpt</em> and <em>torch_gpt</em> are exactly same. mini_llama3 uses the Llama <em>VocabParallelEmbedding</em> .</p><p><strong><em>nano_gpt</em></strong><em>:</em></p><p>The <em>nano_gpt</em> model is a single file version of the <em>NanoGPT</em> model. The parameter list below shows the shapes and sizes of each of the trainable parameters. The model list just shows what layers are there in the model, they do not show the data flow through the model. Dataflow of the model is coded in <em>forward()</em> call</p><pre>transformer.wte.weight torch.Size([65, 384]) 24960                                                                       <br>transformer.wpe.weight torch.Size([256, 384]) 98304                                                                      <br>transformer.h.0.ln_1.weight torch.Size([384]) 384   <br>transformer.h.0.attn.c_attn.weight torch.Size([1152, 384]) 442368        <br>transformer.h.0.attn.c_proj.weight torch.Size([384, 384]) 147456         <br>transformer.h.0.ln_2.weight torch.Size([384]) 384      <br>transformer.h.0.mlp.c_fc.weight torch.Size([1536, 384]) 589824    <br>transformer.h.0.mlp.c_proj.weight torch.Size([384, 1536]) 589824  <br>transformer.h.1.ln_1.weight torch.Size([384]) 384   <br>transformer.h.1.attn.c_attn.weight torch.Size([1152, 384]) 442368        <br>transformer.h.1.attn.c_proj.weight torch.Size([384, 384]) 147456         <br>transformer.h.1.ln_2.weight torch.Size([384]) 384      <br>transformer.h.1.mlp.c_fc.weight torch.Size([1536, 384]) 589824    <br>transformer.h.1.mlp.c_proj.weight torch.Size([384, 1536]) 589824  <br>transformer.h.2.ln_1.weight torch.Size([384]) 384<br>transformer.h.2.attn.c_attn.weight torch.Size([1152, 384]) 442368                                                        <br>transformer.h.2.attn.c_proj.weight torch.Size([384, 384]) 147456                                                         <br>transformer.h.2.ln_2.weight torch.Size([384]) 384           <br>transformer.h.2.mlp.c_fc.weight torch.Size([1536, 384]) 589824                                                           <br>transformer.h.2.mlp.c_proj.weight torch.Size([384, 1536]) 589824                                                         <br>transformer.h.3.ln_1.weight torch.Size([384]) 384<br>transformer.h.3.attn.c_attn.weight torch.Size([1152, 384]) 442368                                                        <br>transformer.h.3.attn.c_proj.weight torch.Size([384, 384]) 147456                                                         <br>transformer.h.3.ln_2.weight torch.Size([384]) 384           <br>transformer.h.3.mlp.c_fc.weight torch.Size([1536, 384]) 589824                                                           <br>transformer.h.3.mlp.c_proj.weight torch.Size([384, 1536]) 589824          <br>transformer.h.4.ln_1.weight torch.Size([384]) 384                                                                        <br>transformer.h.4.attn.c_attn.weight torch.Size([1152, 384]) 442368                                                        <br>transformer.h.4.attn.c_proj.weight torch.Size([384, 384]) 147456                                                         <br>transformer.h.4.ln_2.weight torch.Size([384]) 384           <br>transformer.h.4.mlp.c_fc.weight torch.Size([1536, 384]) 589824                                                           <br>transformer.h.4.mlp.c_proj.weight torch.Size([384, 1536]) 589824                                                         <br>transformer.h.5.ln_1.weight torch.Size([384]) 384                                                                        <br>transformer.h.5.attn.c_attn.weight torch.Size([1152, 384]) 442368                                                        <br>transformer.h.5.attn.c_proj.weight torch.Size([384, 384]) 147456          <br>transformer.h.5.ln_2.weight torch.Size([384]) 384 <br>transformer.h.5.mlp.c_fc.weight torch.Size([1536, 384]) 589824                                                           <br>transformer.h.5.mlp.c_proj.weight torch.Size([384, 1536]) 589824                                                         <br>transformer.ln_f.weight torch.Size([384]) 384               <br>number of parameters: 10,646,784                           <br>modelnano :  NanoGPT(                                       <br>  (transformer): ModuleDict(                                <br>    (wte): Embedding(65, 384)                               <br>    (wpe): Embedding(256, 384)<br>    (drop): Dropout(p=0.2, inplace=False)<br>    (h): ModuleList(                                        <br>      (0-5): 6 x Block(                                     <br>        (ln_1): LayerNorm()                                 <br>        (attn): CausalSelfAttention(<br>          (c_attn): Linear(in_features=384, out_features=1152, bias=False)<br>          (c_proj): Linear(in_features=384, out_features=384, bias=False)<br>          (attn_dropout): Dropout(p=0.2, inplace=False)<br>          (resid_dropout): Dropout(p=0.2, inplace=False)<br>        )                                                   <br>        (ln_2): LayerNorm()                                 <br>        (mlp): MLP(                                         <br>          (c_fc): Linear(in_features=384, out_features=1536, bias=False)<br>          (gelu): GELU(approximate=&#39;none&#39;)<br>          (c_proj): Linear(in_features=1536, out_features=384, bias=False)<br>          (dropout): Dropout(p=0.2, inplace=False)<br>        )                                                   <br>      )                                                     <br>    )                                                       <br>    (ln_f): LayerNorm()                                     <br>  )                                                         <br>  (lm_head): Linear(in_features=384, out_features=65, bias=False)<br>)                                        </pre><p>The forward path of of <em>nano_gpt</em> looks as follows.</p><pre>        pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)<br><br>        # forward the GPT model itself<br>        tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)<br>        pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)<br>        x = self.transformer.drop(tok_emb + pos_emb)<br>        for block in self.transformer.h:<br>            x = block(x)<br>                # block&#39;s forward call<br>                  #x = x + self.attn(self.ln_1(x))<br>                    # attn&#39;s forward call <br>                      #B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)<br><br>                      # calculate query, key, values for all heads in batch and move head forward to be the batch dim<br>                      #q, k, v  = self.c_attn(x).split(self.n_embd, dim=2)<br>                      #k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)<br>                      #q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)<br>                      #v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)<br><br>                      # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -&gt; (B, nh, T, T)<br>                      #if self.flash:<br>                      # efficient attention using Flash Attention CUDA kernels<br>                          #y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)<br>                      #else:<br>                      # manual implementation of attention<br>                          #att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))<br>                          #att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float(&#39;-inf&#39;))<br>                          #att = F.softmax(att, dim=-1)<br>                          #att = self.attn_dropout(att)<br>                          #y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -&gt; (B, nh, T, hs)<br>                          #y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side<br><br>                      # output projection<br>                          #y = self.resid_dropout(self.c_proj(y))<br>                    #x = x + self.mlp(self.ln_2(x))<br>                    # mlp&#39;s fprward call <br>                        #x = self.c_fc(x)<br>                        #x = self.gelu(x)<br>                        #x = self.c_proj(x)<br>                        #x = self.dropout(x)<br>        x = self.transformer.ln_f(x) #  last layer norm<br><br>        if targets is not None:<br>            # if we are given some desired targets also calculate the loss<br>            logits = self.lm_head(x)<br>            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)</pre><p><strong><em>torch_gpt</em></strong><em>:</em></p><p>The <em>torch_gpt</em> model is based on PyTorch’s <em>TransformerDecoder</em> and <em>TransformerDecoderLayer</em> class. Class <em>GPTDecoderLayer </em>is derived from <em>TransformerDecoderLayer. </em>The<em> GPTDecoderLayer </em>removes the memory input from the Transformer’s encoder part<em>. </em>In the model<em> tgt_is_causal </em>is also set to <em>True</em> along with a mask<em>. </em>It is similar to the class <em>Block</em> in <em>NanoGPT</em>. The <em>torch_gpt</em> model is as follows</p><pre>gptnet.wte.weight torch.Size([65, 384]) 24960                                                                            <br>gptnet.wpe.weight torch.Size([256, 384]) 98304              <br>gptnet.h.layers.0.norm1.weight torch.Size([384]) 384<br>gptnet.h.layers.0.self_attn.in_proj_weight torch.Size([1152, 384]) 442368  <br>gptnet.h.layers.0.self_attn.out_proj.weight torch.Size([384, 384]) 147456     <br>gptnet.h.layers.0.ff_norm3.weight torch.Size([384]) 384<br>gptnet.h.layers.0.ff_linear1.weight torch.Size([1536, 384]) 589824            <br>gptnet.h.layers.0.ff_linear2.weight torch.Size([384, 1536]) 589824<br>gptnet.h.layers.1.norm1.weight torch.Size([384]) 384<br>gptnet.h.layers.1.self_attn.in_proj_weight torch.Size([1152, 384]) 442368<br>gptnet.h.layers.1.self_attn.out_proj.weight torch.Size([384, 384]) 147456<br>gptnet.h.layers.1.ff_norm3.weight torch.Size([384]) 384<br>gptnet.h.layers.1.ff_linear1.weight torch.Size([1536, 384]) 589824<br>gptnet.h.layers.1.ff_linear2.weight torch.Size([384, 1536]) 589824<br>gptnet.h.layers.2.norm1.weight torch.Size([384]) 384<br>gptnet.h.layers.2.self_attn.in_proj_weight torch.Size([1152, 384]) 442368<br>gptnet.h.layers.2.self_attn.out_proj.weight torch.Size([384, 384]) 147456<br>gptnet.h.layers.2.ff_norm3.weight torch.Size([384]) 384<br>gptnet.h.layers.2.ff_linear1.weight torch.Size([1536, 384]) 589824<br>gptnet.h.layers.2.ff_linear2.weight torch.Size([384, 1536]) 589824<br>gptnet.h.layers.3.norm1.weight torch.Size([384]) 384<br>gptnet.h.layers.3.self_attn.in_proj_weight torch.Size([1152, 384]) 442368<br>gptnet.h.layers.3.self_attn.out_proj.weight torch.Size([384, 384]) 147456<br>gptnet.h.layers.3.ff_norm3.weight torch.Size([384]) 384<br>gptnet.h.layers.3.ff_linear1.weight torch.Size([1536, 384]) 589824<br>gptnet.h.layers.3.ff_linear2.weight torch.Size([384, 1536]) 589824<br>gptnet.h.layers.4.norm1.weight torch.Size([384]) 384<br>gptnet.h.layers.4.self_attn.in_proj_weight torch.Size([1152, 384]) 442368<br>gptnet.h.layers.4.self_attn.out_proj.weight torch.Size([384, 384]) 147456<br>gptnet.h.layers.4.ff_norm3.weight torch.Size([384]) 384<br>gptnet.h.layers.4.ff_linear1.weight torch.Size([1536, 384]) 589824<br>gptnet.h.layers.4.ff_linear2.weight torch.Size([384, 1536]) 589824<br>gptnet.h.layers.5.norm1.weight torch.Size([384]) 384<br>gptnet.h.layers.5.self_attn.in_proj_weight torch.Size([1152, 384]) 442368<br>gptnet.h.layers.5.self_attn.out_proj.weight torch.Size([384, 384]) 147456<br>gptnet.h.layers.5.ff_norm3.weight torch.Size([384]) 384<br>gptnet.h.layers.5.ff_linear1.weight torch.Size([1536, 384]) 589824<br>gptnet.h.layers.5.ff_linear2.weight torch.Size([384, 1536]) 589824<br>gptnet.ln_f.weight torch.Size([384]) 384<br>number of parameters: 10,646,784<br>modeltorch :  TorchGPT(                                     <br>  (gptnet): ModuleDict(                                     <br>    (wte): Embedding(65, 384)                               <br>    (wpe): Embedding(256, 384)<br>    (drop): Dropout(p=0.2, inplace=False)<br>    (h): GPTDecoder(                                        <br>      (layers): ModuleList(                                 <br>        (0-5): 6 x GPTDecoderLayer(<br>          (norm1): LayerNorm((384,), eps=1e-05, elementwise_affine=True)<br>          (self_attn): MultiheadAttention(<br>            (out_proj): NonDynamicallyQuantizableLinear(in_features=384, out_features=384, bias=False)<br>          )                                                 <br>          (dropout1): Dropout(p=0.2, inplace=False)<br>          (ff_norm3): LayerNorm((384,), eps=1e-05, elementwise_affine=True)<br>          (ff_linear1): Linear(in_features=384, out_features=1536, bias=False)<br>          (ff_dropout2): Dropout(p=0.2, inplace=False)<br>          (ff_linear2): Linear(in_features=1536, out_features=384, bias=False)<br>          (ff_dropout3): Dropout(p=0.2, inplace=False)<br>        )                                                   <br>      )                                                     <br>    )                                                       <br>    (ln_f): LayerNorm((384,), eps=1e-05, elementwise_affine=True)<br>    (lm_head): Linear(in_features=384, out_features=65, bias=False)<br>  )                                                         <br>)</pre><p><strong><em>mini_llama3:</em></strong></p><p>The <em>mini_llama3</em> parameter and model is listed below. The same tokenizer as in GPT’s is used. The token embedder and linear layers are different — <em>ColumnParallelLinear</em>, <em>RowParallelLinear</em>, and <em>VocabParallelEmbedding</em> . These come from Meta’s <em>fairscale</em> package. In our case <em>xParallelLinear</em> layers behave as simple linear layers as we are not using distributed training ( with FSDP , Megatron etc.)</p><pre>tok_embeddings.weight torch.Size([65, 384]) 24960                                                                               <br>layers.0.attention.wq.weight torch.Size([384, 384]) 147456                                                                      <br>layers.0.attention.wk.weight torch.Size([384, 384]) 147456                                                                      <br>layers.0.attention.wv.weight torch.Size([384, 384]) 147456                                                                      <br>layers.0.attention.wo.weight torch.Size([384, 384]) 147456                                                                      <br>layers.0.feed_forward.w1.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.0.feed_forward.w2.weight torch.Size([384, 1408]) 540672                                                                  <br>layers.0.feed_forward.w3.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.0.attention_norm.weight torch.Size([384]) 384                                                                            <br>layers.0.ffn_norm.weight torch.Size([384]) 384                                                                                                                                                                                                                  <br>layers.1.attention.wq.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.1.attention.wk.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.1.attention.wv.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.1.attention.wo.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.1.feed_forward.w1.weight torch.Size([1408, 384]) 540672                                                                                                                                                                                                  <br>layers.1.feed_forward.w2.weight torch.Size([384, 1408]) 540672                                                                                                                                                                                                  <br>layers.1.feed_forward.w3.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.1.attention_norm.weight torch.Size([384]) 384                                                                                                                                                                                                            <br>layers.1.ffn_norm.weight torch.Size([384]) 384                                                                                                                                                                                                                  <br>layers.2.attention.wq.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.2.attention.wk.weight torch.Size([384, 384]) 147456                                                                      <br>layers.2.attention.wv.weight torch.Size([384, 384]) 147456                                                                      <br>layers.2.attention.wo.weight torch.Size([384, 384]) 147456                                                                      <br>layers.2.feed_forward.w1.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.2.feed_forward.w2.weight torch.Size([384, 1408]) 540672                                                                  <br>layers.2.feed_forward.w3.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.2.attention_norm.weight torch.Size([384]) 384            <br>layers.2.ffn_norm.weight torch.Size([384]) 384                                                                                  <br>layers.3.attention.wq.weight torch.Size([384, 384]) 147456                                                                      <br>layers.3.attention.wk.weight torch.Size([384, 384]) 147456                                                                      <br>layers.3.attention.wv.weight torch.Size([384, 384]) 147456                                                                      <br>layers.3.attention.wo.weight torch.Size([384, 384]) 147456                                                                      <br>layers.3.feed_forward.w1.weight torch.Size([1408, 384]) 540672  <br>layers.3.feed_forward.w2.weight torch.Size([384, 1408]) 540672                                                                  <br>layers.3.feed_forward.w3.weight torch.Size([1408, 384]) 540672                                                                                                                                                                                                  <br>layers.3.attention_norm.weight torch.Size([384]) 384                                                                                                                                                                                                            <br>layers.3.ffn_norm.weight torch.Size([384]) 384                                                                                                                                                                                                                  <br>layers.4.attention.wq.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.4.attention.wk.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.4.attention.wv.weight torch.Size([384, 384]) 147456                                                                      <br>layers.4.attention.wo.weight torch.Size([384, 384]) 147456                                                                                                                                                                                                      <br>layers.4.feed_forward.w1.weight torch.Size([1408, 384]) 540672  <br>layers.4.feed_forward.w2.weight torch.Size([384, 1408]) 540672                                                                                                                                                                                                  <br>layers.4.feed_forward.w3.weight torch.Size([1408, 384]) 540672                                                                                                                                                                                                  <br>layers.4.attention_norm.weight torch.Size([384]) 384                                                                                                                                                                                                            <br>layers.4.ffn_norm.weight torch.Size([384]) 384                                                                                  <br>layers.5.attention.wq.weight torch.Size([384, 384]) 147456                                                                      <br>layers.5.attention.wk.weight torch.Size([384, 384]) 147456      <br>layers.5.attention.wv.weight torch.Size([384, 384]) 147456                                                                      <br>layers.5.attention.wo.weight torch.Size([384, 384]) 147456                                                                      <br>layers.5.feed_forward.w1.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.5.feed_forward.w2.weight torch.Size([384, 1408]) 540672                                                                  <br>layers.5.feed_forward.w3.weight torch.Size([1408, 384]) 540672                                                                  <br>layers.5.attention_norm.weight torch.Size([384]) 384                                                                            <br>layers.5.ffn_norm.weight torch.Size([384]) 384                                                                                  <br>norm.weight torch.Size([384]) 384                                                                                               <br>output.weight torch.Size([65, 384]) 24960                                                                                       <br>number of parameters: 13,325,952   <br>modelllama3 :  Transformer(                                     <br>  (tok_embeddings): VocabParallelEmbedding()                    <br>  (layers): ModuleList(                                         <br>    (0-5): 6 x TransformerBlock(                                <br>      (attention): Attention(                                   <br>        (wq): ColumnParallelLinear()                            <br>        (wk): ColumnParallelLinear()                            <br>        (wv): ColumnParallelLinear()                            <br>        (wo): RowParallelLinear()                               <br>      )                                                         <br>      (feed_forward): FeedForward(                              <br>        (w1): ColumnParallelLinear()                            <br>        (w2): RowParallelLinear()                               <br>        (w3): ColumnParallelLinear()                            <br>      )                                                         <br>      (attention_norm): RMSNorm()                               <br>      (ffn_norm): RMSNorm()                                     <br>    )                                                           <br>  )                                                             <br>  (norm): RMSNorm()                                             <br>  (output): ColumnParallelLinear()                              <br>)                      </pre><p>The traing code essentially is same as in <em>nano_gpt</em> and <em>torch_gpt</em>. The parameter initialization is also similar as the 2 gpt’s except for different <em>nn.Module</em> names. Without this initialization training gets stuck with mostly 0 gradients at a non-optimal minima.</p><p><strong>Training the 3 models :</strong></p><p>The 3 models are small and the the dataset is also small and hence can be trained together. The code to train all the 3 models at the same time is in the file <em>compare_models.py</em> ( e.g. with the <em>— train</em> option ) . The following chart shows the validation loss versus iteration number for the 3 models. All the 3 models use the same <em>AdamW</em> parameters that were used in the original <em>NanoGPT</em> model. The <em>mini_lama3</em> model has the fastest convergence, but also appears to overfit rapidly. Parameter search and tuning is expected to resolve that issue and get to better val loss (TBD).</p><p>The mini_llama3 model uses bf16 and hence the size of the checkpoint is almost half of the other 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*P5Zq_AQRw4HVALR96fYfWQ.png" /><figcaption>Fig: Validation Loss vs interation number</figcaption></figure><p>The following are example generations from the 3 models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NffWDTDYozC6A9zW3PfWw.png" /><figcaption>Generation samples for the 3 models — nana_gpt, torch_gpt, and mini_llama3 .</figcaption></figure><p><strong>References:</strong></p><ol><li>Transformer — Attention Is All You Need, <a href="https://arxiv.org/pdf/1706.03762">https://arxiv.org/pdf/1706.03762</a></li><li>Deep Residual Learning for Image Recognition, <a href="https://arxiv.org/pdf/1512.03385">https://arxiv.org/pdf/1512.03385</a></li><li>T-D, Generating wikipedia by summarizing long sequences. ICLR, 2018, <a href="https://arxiv.org/pdf/1801.10198">https://arxiv.org/pdf/1801.10198</a></li><li>GPT-1, Improving Language Understanding by Generative Pre-Training, <a href="https://www.cs.princeton.edu/courses/archive/spring20/cos598C/lectures/lec4-pretraining.pdf">https://www.cs.princeton.edu/courses/archive/spring20/cos598C/lectures/lec4-pretraining.pdf</a></li><li>GPT-1, Improving Language Understanding by Generative Pre-Training, <a href="https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf">https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf</a></li><li>GPT-1 : <a href="https://en.wikipedia.org/wiki/GPT-1">https://en.wikipedia.org/wiki/GPT-1</a></li><li>Generative pre-trained transformer, <a href="https://en.wikipedia.org/wiki/Generative_pre-trained_transformer">https://en.wikipedia.org/wiki/Generative_pre-trained_transformer</a></li><li>GPT2 — Language Models are Unsupervised Multitask Learners, <a href="https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf</a></li><li>GPT-2: 1.5B release, <a href="https://openai.com/research/gpt-2-1-5b-release">https://openai.com/research/gpt-2-1-5b-release</a></li><li>GPT2, Better language models and their implications, <a href="https://openai.com/index/better-language-models/">https://openai.com/index/better-language-models/</a></li><li>Transformer (deep learning architecture), <a href="https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)">https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)</a></li><li><a href="https://en.wikipedia.org/wiki/LLaMA">https://en.wikipedia.org/wiki/LLaMA</a></li><li><a href="https://llama.meta.com/llama2/">https://llama.meta.com/llama2/</a></li><li>LLaMA: Open and Efficient Foundation Language Models, <a href="https://arxiv.org/pdf/2302.13971">https://arxiv.org/pdf/2302.13971</a></li><li>Llama 2: Open Foundation and Fine-Tuned Chat Models, <a href="https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/">https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/</a></li><li>Llama 2: Open Foundation and Fine-Tuned Chat Models, <a href="https://scontent-sjc3-1.xx.fbcdn.net/v/t39.2365-6/10000000_662098952474184_2584067087619170692_n.pdf">https://scontent-sjc3-1.xx.fbcdn.net/v/t39.2365-6/10000000_662098952474184_2584067087619170692_n.pdf</a></li><li>Introducing Meta Llama 3: The most capable openly available LLM to date — <a href="https://ai.meta.com/blog/meta-llama-3/">https://ai.meta.com/blog/meta-llama-3/</a></li><li><a href="https://github.com/facebookresearch/fairscale">https://github.com/facebookresearch/fairscale</a></li><li><a href="https://github.com/openai/gpt-2?tab=readme-ov-file">https://github.com/openai/gpt-2?tab=readme-ov-file</a></li><li><a href="https://github.com/karpathy/nanoGPT">https://github.com/karpathy/nanoGPT</a></li><li><a href="https://github.com/karpathy/llama2.c">https://github.com/karpathy/llama2.c</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf69ac00280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Core Principles of Large Language Model (LLM) Tuning]]></title>
            <link>https://whatdhack.medium.com/some-core-principles-of-large-language-model-llm-tuning-0b581da9adbc?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b581da9adbc</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rlhf]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llama-2]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 07:05:42 GMT</pubDate>
            <atom:updated>2023-12-31T07:05:42.092Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models ( LLM) such as Chat-GPT , Llama2, etc have taken the world by storm this year. What seems like a recent phenomenon, is actually culmination of painstaking research and development over a number of years. LLM is a very rapidly developing field and within a very short time has become broad. GPTx from OpenAI ( and LLama2 from Meta to some extent) is the trend setting model with significant amount of publications that has shaped the space so far. This piece explores some of the important concepts (without going into code or lot of math) that are at the heart of such models.</p><p>The content of this piece uses texts and images ( original or modified ) liberally from some of the listed references.</p><p><strong>Pre-Training</strong></p><p>One of the significant breakthroughs in the language model space has been the ability to do zero/few-shot learning without needing to retrain the parameters. This imparts LLMs the ability to easily adapt to context based question-answer — the raw power behind Chat-GPT like software. GPT2 leveraged this advance, called MQAN ( multitask question answering network ). Prior multitasking approaches such as MAML were complex and not scalable. MQAN is an unsupervised approach that relied on language to flexibly specify tasks, inputs, and outputs as a sequence of symbols.</p><p>From the GPT2 paper — “For example, a translation training example can be written as the sequence <em>(translate to french, english text, french text)</em>. Likewise, a reading comprehension training example can be written as (<em>answer the question, document, question, answer)</em>. …. <strong>Our speculation is that a language model with sufficient capacity will begin to learn to infer and perform the tasks demonstrated in natural language sequences in order to better predict them</strong>, regardless of their method of procurement. If a language model is able to do this it will be, in effect, performing unsupervised multitask learning. We test whether this is the case by analyzing the performance of language models in a zero-shot setting on a wide variety of tasks.“</p><p>Hence in modern LLM’s, pre-training on billions to trillions of tokens is unsupervised.</p><p>Another significant breakthrough benefiting LLMs is the Transformer architecture. Transformers removed the sequential bottlenecks that prevented previous language models such as RNN/LSTM fron scsaling.</p><p>The other developments that helped are increases in GPU compute capability ( silicon technology and design ) and the software/frameworks improvements. Transformers are very compute and memory intensive, and without the silicon and algorithm improvements, it would not have been practical to train transformer models.</p><p>Another very significant catalyst is availability of data used for autoregressive unsupervised pre-training. This would not have been possible without the readily available content over the Internet.</p><p><strong>Fine-tuning</strong></p><p>The pre-trained LLM’s are further trained ( or tuned ) to adapt to different uses cases (e.g chatbot, summerization, content generation, etc.), domains (e.g. finance, health, ) , content (e.g. non-harmful, helpful), etc.</p><p>The commonly used (and published) fine-tuning methods are as follows.</p><ul><li>Supervised fine tuning (SFT) — instruction fine tuning</li><li>Reinforcement learning with human feedback (RLHF)</li></ul><p>SFT minimizes the loss between what the model outputs and what the correct result is token by token. Both InstructGPT and Llama papers found that SFT alone does not sufficiently improve model output.</p><p>The GPT3 paper did not use fine-tuning and instead the results were all with in-context information ( zero/one/two-shot ). From the GPT3 paper —</p><p>“The main advantage of fine-tuning is strong performance on many benchmarks. The main disadvantages are the need for a new large dataset for every task, the potential for poor generalization out-of-distribution [MPL19], and the potential to exploit spurious features of the training data [GSL+18, NK19], potentially resulting in an unfair comparison with human performance. In this work we do not fine-tune GPT-3 because our focus is on task-agnostic performance, but GPT-3 can be fine-tuned in principle and this is a promising direction for future work.”</p><p>The GPT3 paper shows results of about 65 evaluations spanning — language modelling, Q&amp;A, translation, common sense reasoning, reading comprehension, etc. On many of theses tests ( listed in Table H.1 of the paper), the GPT3 model bettered or equaled fine-tuned SOTA models.</p><p>GPT4 uses fine-tuning , both SFT and RLHF. The paper claims that RLHF fine-tuning makes the models significantly safer.</p><p>LLama2 also uses SFT and RLHF. From the Llama2 paper —</p><p>“These closed product LLMs are heavily fine-tuned to align with human preferences, which greatly enhances their usability and safety. This step can require significant costs in compute and human annotation, and is often not transparent or easily reproducible, limiting progress within the community to advance AI alignment research.”</p><p><strong>Reinforcement Learning with Human Feedback (RLHF) :</strong></p><p>In RLHF, the policy is a supervised fine tuned version of LLM. The reward ( function or model, RM) is also the same LLM with a categorical head instead of a next word generation head. The RM is trained on the user preference data that is collected over a period of time. The RM is a proxy for the environment. The LLM is then fine tuned using the RM and optimization algorithm such as Proximal Policy Optimization (PPO) . The collection of user preference data and model update forms a loop with newer user preference data resulting in more fine tuning. The following pictures from the InstructGPT and the Llama-2 papers illustrate the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1yps2QGy8wQMX9y7kU-Sg.png" /><figcaption>InstructGPT RLHF process</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*ucNdkaxz7n5m4Y_Vov7tYg.png" /><figcaption>Llama-2-Chat RLHF process</figcaption></figure><p>The <strong>Reward Model</strong> approach was detailed in a 2018 ( see reference “<strong>Scalable agent alignment via reward modeling:<br>a research direction</strong>“ ) paper by DeepMind. The idea has been used in earlier publications such as 2016 “Deep Reinforcement Learning from Human Preferences” by OpenAI and Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*UZhPAqaxHrO3O6VG_9ucdQ.png" /><figcaption>Reward Model from the “Scalable agent … “ paper.</figcaption></figure><p>“the ultimate goal of machine learning (ML) research is to go beyond games and improve human lives. To achieve this we need ML to assist us in real-world domains, ranging from simple tasks like ordering food or answering emails to complex tasks like software engineering or running a business. Yet performance on these and other real-world tasks is not easily measurable, since they do not come readily equipped with a reward function. Instead, the objective of the task is only indirectly available through the intentions of the human user”</p><p>“On the one hand, we want ML to generate creative and brilliant …. On the other hand, we want to avoid degenerate solutions that lead to undesired behavior like exploiting a bug … In order to differentiate between these two outcomes, our agent needs to understand its user’s intentions, and robustly achieve these intentions with its behavior. We frame this as the agent alignment problem: How can we create agents that behave in accordance with the user’s intentions? “</p><p>“We break the problem into two parts: (1) learning a reward function from the feedback of the user that captures their intentions and (2) training a policy with reinforcement learning to optimize the learned reward function. In other words, we separate learning what to achieve (the ‘What?’) from learning how to achieve it (the ‘How?’). We call this approach reward modeling. Figure 1 illustrates this setup schematically.”</p><p>“Learning a reward function separately from the agent’s policy allows us to disentangle the agent’s objective from its behavior. If we understand the reward function, we know what the agent is optimizing for; in particular, we know whether its intentions are aligned with the user’s intentions. This has three advantages that could help make reward modeling economical:</p><ul><li>1. The user does not have to provide feedback on every interaction between agent and environment, as would be the case if we trained a policy from user feedback directly. Since deep RL algorithms tend to be very sample-inefficient (e.g. taking weeks of real-time to learn to play an Atari game), providing feedback on every interaction is usually not practical.</li><li>2. We can distinguish between alignment of the policy and alignment of the reward model (Ibarz et al., 2018).</li><li>3. We can leverage progress on deep RL agents by plugging a more capable agent into our reward modeling setup.</li><li>4. The user does not need to solve the credit assignment problem”</li></ul><p>The Reward Model approach for <strong>text summarization </strong>was used in the paper <strong>“Better Rewards Yield Better Summaries: Learning to Summarise Without Reference”</strong> . There the authors formulated a Cross-entropy loss function that expanded the granularity exponentially through comparison of pairs of outputs. This approach is used by many LLMs currently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*hdbF_dPxEfO7CUGGK4_QuA.png" /><figcaption>Cross Entropy Loss from paper ““Better Rewards Yield …”</figcaption></figure><p>Both of the above techniques were then combined by author’s of the paper <strong>“Learning to summarize from human feedback”</strong> ( precursor to InstructGPT or proto-InstructGPT). The paper uses a filtered version of the Reddit TL;DR dataset. From this paper.</p><p>“We follow the works of [3, 73], who fine-tune language models from human feedback using reward learning [35]. We first collect a dataset of human preferences between pairs of summaries, then train a reward model (RM) via supervised learning to predict the human-preferred summary. Finally, we train a policy via reinforcement learning (RL) to maximize the score given by the RM; the policy generates a token of text at each ‘time step’, and is updated using the PPO algorithm [58] based on the RM ‘reward’ given to the entire generated summary. We can then gather more human data using samples from the resulting policy, and repeat the process. We follow the works of [48, 4] and use large pretrained GPT-3 models with as many as 6.7 billion parameters.”</p><p>The following diagram shows the RLHF process used in the above paper .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5Xxv7Id_vW5dmfzCbNTQA.png" /><figcaption>Proto-InstructGPT fine tuning ( from apper “Learning to summarize… “)</figcaption></figure><p>The steps in the process are as follows.</p><p>“Step 1: Collect samples from existing policies and send comparisons to humans. For each Reddit post, we sample summaries from several sources including the <strong>current policy, initial policy, original reference summaries and various baselines</strong>. We send a batch of pairs of summaries to our human evaluators, who are tasked with selecting the best summary of a given Reddit post.</p><p>Step 2: Learn a reward model from human comparisons. Given a post and a candidate summary, we train a reward model to predict the log odds that this summary is the better one, as judged by our labelers.</p><p>Step 3: Optimize a policy against the reward model. We treat the logit output of the reward model as a reward that we optimize using reinforcement learning, specifically with the PPO algorithm [58].”</p><p>“Crucially, we also filter to include only posts where the human-written summaries contain between 24 and 48 tokens, to minimize the potential effect of summary length on quality (see Section 4.1 and Appendix F). Our final filtered dataset contains 123,169 posts, and we hold out ~5% as a validation set”</p><p>“(4) We publicly release our human feedback dataset for further research. The dataset contains 64,832 summary comparisons on the TL;DR dataset, as well as our evaluation data on both TL;DR (comparisons and Likert scores) and CNN/DM (Likert scores).”</p><p>“All of our models are Transformer decoders [62] in the style of GPT-3 [47, 4]. We conduct our human feedback experiments on models with 1.3 billion (1.3B) and 6.7 billion (6.7B) parameters.”</p><p>“Pretrained models. Similarly to [12, 47], we start with models pretrained to autoregressively predict the next token in a large text corpus.”</p><p>“Supervised baselines. We next fine-tune these models via supervised learning to predict summaries from our filtered TL;DR dataset (see Appendix B for details). We use these supervised models to sample initial summaries for collecting comparisons, to initialize our policy and reward models, and as baselines for evaluation.”</p><p>“Reward models. To train our reward models, we start from a supervised baseline, as described above, then add a randomly initialized linear head that outputs a scalar value. We train this model to predict which summary y ∈ {y0, y1} is better as judged by a human, given a post x.”</p><p>“Human feedback policies. We want to use the reward model trained above to train a policy that generates higher-quality outputs as judged by humans. We primarily do this using reinforcement learning, by treating the output of the reward model as a reward for the entire summary that we maximize with the PPO algorithm [58], where each time step is a BPE token⁸. We initialize our policy to be the model fine-tuned on Reddit TL;DR. Importantly, we include a term in the reward that penalizes the KL divergence between the learned RL policy πRLφ with parameters φ and this original supervised model πSFT, as previously done in [25].”</p><p>⁸<strong>Note that the reward model only gives rewards for entire summaries, and not at intermediate time steps</strong>. In RL terminology, each episode terminates when the policy outputs the EOS token, and the discount factor γ = 1.”</p><p>As the reward model only provide judgement on the entire summary rather than each generated token, hence SFT is not suitable, and RL is better suited for such non-immediate and non-granular feedback ( i.e. loss) .</p><p>“For the PPO value function, we use a Transformer with completely separate parameters from the policy. This prevents updates to the value function from partially destroying the pretrained policy early in training (see ablation in Appendix G.1). We initialize the value function to the parameters of the reward model. In our experiments, the reward model, policy, and value function are the same size.”</p><p>“For PPO, we run with separate policy and value networks, initializing our policies to the supervised baseline, and our value functions to the reward model.”</p><p><strong>InstructGPT </strong>paper<strong>, “Training language models to follow instructions with human feedback”</strong>, improved upon the previous paper. The steps are shown in the following picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3RejvPaMtOBo_bQW-AcZw.png" /><figcaption>InstructGPT fine tuning ( from the InstructGPT paper)</figcaption></figure><p>“Starting from the SFT model with the final unembedding layer removed, we trained a model to take in a prompt and response, and output a scalar reward. In this paper we only use 6B RMs, as this saves a lot of compute, and we found that 175B RM training could be unstable and thus was less suitable to be used as the value function during RL (see Appendix C for more details).”</p><p>“Once again following Stiennon et al. (2020), we fine-tuned the SFT model on our environment using PPO (Schulman et al., 2017). The environment is a bandit environment which presents a random customer prompt and expects a response to the prompt. Given the prompt and response, it produces a reward determined by the reward model and ends the episode. In addition, we add a per-token KL penalty from the SFT model at each token to mitigate over optimization of the reward model. The value function is initialized from the RM. We call these models “PPO.” “</p><p>“In order to speed up comparison collection, we present labelers with anywhere between K = 4 and K = 9 responses to rank. “</p><p>“The final reward model was initialized from a 6B GPT-3 model that was fine-tuned on a variety of public NLP datasets (ARC, BoolQ, CoQA, DROP, MultiNLI, OpenBookQA, QuAC, RACE, and Winogrande). This was mostly for historical reasons; we find similar results when initializing the RM from the GPT-3 or SFT models.”</p><p>“Over the course of the project, we trained several reward models and policies. Each batch of summaries that we sent to the labelers were sampled from a variety of policies. We didn’t have a systematic plan for which policies to sample from; rather, we chose what seemed best at the time in the spirit of exploratory research. Every time we trained a reward model, we trained on all labels we had collected so far. Successive models also benefited from improved hyperparameters and dataset cleaning.”</p><p><strong>Transformer</strong> <strong>Networks</strong></p><p>The transformer architecture that has revolutionized Generative AI has two major parts — encoder and decoder. Some very well known subsequent architectures made use of only one part.</p><p>For text generation, the decoder part of the transformer architecture is used. It is trained in an auto-regressive manner to predict the next word — which turns out to be very suitable for what is needed for generation. Words after the next to the right are masked duting pre-training.</p><p>The encoder part of transformer learns to encode complete sentences. Random word in the sentence is masked during pre-training. These models are suited for language understanding, such as classification and sentiment analysis, etc.</p><p>BERT (Bidirectional Encoder Representations from Transformers) is an encoder only model family. T5 is an encoder-decoder model famly. GPTs and Lllama’s are decoder only models.</p><p><strong>GPT:</strong></p><p>As mentioned previously, GPT ‘s(Generative Pretrained Transformer) are decoder only models. OpenAI’s paper mentioned 4 GPT2 models ranging from 117 M to 1.5 B parameters. However, they only released the 3 smaller version of the GPT2 model. The codes for GPT 3/3.5/4 have not been open sourced also.</p><p><strong>GPT-3</strong> comes in 8 sizes, ranging from 125M to 175B parameters. The largest GPT-3 model is 175B parameters and is called <em>davinci</em>. The smallest GPT-3 model is 125 M parameters and roughly the size of BERT-Base and RoBERTa-Base.</p><p>According to the OpenAI’s GPT3 paper, the following are the major differences with GPT2 architecture.</p><p>“same model and architecture as GPT-2 [RWC+19], including the modified initialization, pre-normalization, and reversible tokenization described therein, with the exception that we use alternating dense and locally banded sparse attention patterns in the layers of the transformer, similar to the Sparse Transformer [CGRS19]. To study the dependence of ML performance on model size, we train 8 different sizes of model, ranging over three orders of magnitude from 125 million parameters to 175 billion parameters, with the last being the model we call GPT-3.”</p><p><strong>InstructGPT</strong> is an RLHF tuned GPT3. It is trained to follow an instruction in a prompt and provide a detailed response that is safer, more helpful, and more aligned with what users wants. GPT3 alone was not able to do that because it is trained to predict the next word on a large dataset of Internet text. From the InstructGPT paper —</p><p>“ Our labelers prefer outputs from our 1.3B InstructGPT model over outputs from a 175B GPT-3 model, despite having more than 100x fewer parameters.”. The InstructGPT paper goes over SFT, RM and PPO is details.</p><p><strong>ChatGPT</strong> is a fine tuned GPT3.5 with RLHF. A GPT3.5 model is first fine tuned with with data generated by human AI trainer as both user and AI assistant, mixed with the InstructGPT dataset. The reward model is trained on responses ranked by quality by human AI trainers. Multiple responses were generated by “We randomly selected a model-written message, sampled several alternative completions, and had AI trainers rank them”. No further detail was provided on “sampled several alternative completions”! Finally, with the reward model, Proximal Policy Optimization (PPO) was used to fine-tune the model.</p><p><strong>GPT4</strong> paper does not provide any detail on the architecture or dataset beyond the following.</p><p>“GPT-4 is a Transformer-style model [39] pre-trained to predict the next token in a document, using both publicly available data (such as internet data) and data licensed from third-party providers. The model was then fine-tuned using Reinforcement Learning from Human Feedback (RLHF) [40]. Given both the competitive landscape and the safety implications of large-scale models like GPT-4, this report contains no further details about the architecture (including model size), hardware, training compute, dataset construction, training method, or similar.”</p><p>There are a number of open sourced GPT type alternatives such as GPT-J, GPT-Neo, etc., released by non-OpenAI entities.</p><p><strong>GPT-J</strong>-6B is an open source artificial intelligence language model developed by EleutherAI</p><p><strong>GPT-Neo</strong> are several models — from 125M to 2.7B parameters. It is an implementation of model &amp; data parallel GPT like models built with the Mesh-TensorFlow library. They are trained on the Pile dataset. The architecture is similar to GPT2 except that GPT Neo uses local attention in every other layer with a window size of 256 tokens.</p><p><strong>GPT-NeoX</strong> is a 20 billion parameter autoregressive language model trained on the Pile dataset from EleutherAI. It is based on NVIDIA’s Megatron Language Model and has been augmented with techniques from DeepSpeed as well as some other novel optimizations.</p><p>Nvidia provides a GPT-3 code based on Megatron-LM available for pre-training that they used for MLPerf pre-training benchmarks. Some diffference of this model from the GPT-3 paper are — Tokenizer changed from BPE to SentencePiece with BPE, and alternating sparse attention layers not used. It uses the HF C4 dataset. Megatron is a large, powerful transformer developed by NVIDIA.</p><p><strong>LLAMA2:</strong></p><p>LLama2 is also a decoder only model. There are 4 variants at this point — 7B, 13B, 34B and 70B. There are instruction-tuned and RLHF versions of the base models called Llama2-chat.</p><p>Fine tuning is similar as in GPTx — supervised fine tuning followed by RLHF fine tuning. Human annotators first write a prompt, then choose between two sampled model responses, based on provided criteria. In order to maximize the diversity, the two responses to a given prompt are sampled from 2 different model variants ( 7B and 13B ? ), and varying the temperature hyper-parameter. Temperature sampling is a <em>softmax</em> based method that uses a temperature parameter between 0 and 1 as a denominator in the exponents.</p><p>The Llama2 fine-tuned models ( Llama2-chat ) used both public instruction-tuning data and a high-quality Meta in-house data for supervised fine tuning (SFT). The dataset contains a total of 27,540 annotations. For SFT, each sample consists of a prompt and an answer. To ensure the model sequence length is properly filled, they concatenated all the prompts and answers from the training set. A special token was used to separate prompt from answer. SFT is done with auto-regressive objective where the loss on tokens from the user prompt are zero’ed out, and hence back-propagation was done only on answer tokens.</p><p>RLHF was applied to the SFT’ed model to further align model behavior with human preferences and instruction following. A binary comparison protocol was chosen for annotation. Human annotators design a prompt. Output from two different model variants along with different temperatures were generated for each prompt. The annotators also grade their choices as <em>significantly better, better, slightly better, or negligibly better/ unsure</em>. Human annotators then select one of two model outputs they prefer. The reward model learns the preferences of human annotators and which then can automate preference decisions.</p><p>The Reward Model architecture and hyper-parameters are identical to those of the pre-trained language models, except that the classification head for next-token prediction is replaced with a regression head to output a scalar reward.</p><p>RLHF fine-tuning was done with two main algorithms — Proximal Policy Optimization (PPO) and Rejection Sampling fine-tuning. Rejection Sampling here means selecting one output of a few outputs for the same prompt. The different outputs are generated by slightly different models.</p><p><strong>Datasets for Pre-training and Fine-tuning:</strong></p><p><strong>Pre-training datasets:</strong></p><p>The pre-training dataset used for GPTx and LlamaX are not open sourced.</p><p>GPT3 used a filtered and deduped version of the 1-trillion word Common Crawl dataset augmented with an expanded version of the WebText dataset, 2 internet-based books corpora (Books1 and Books2) and English-language Wikipedia .</p><p>Llama2 models were pre-trained on 2 trillon tokens of a new mix of data from publicly available sources. The dataset does not include data from Meta’s products or services, and avoids sites with personal information.</p><p>HuggingFace C4 dataset is used by Nvidia’s Megatron-LM</p><p>Pile from EleutherAI used by both GPT-Neo and GPT-NeoX</p><p><strong>Fine-tuning datasets:</strong></p><p><strong>“Learning to summarize from human feedback” </strong>paper ( precursor to InstructGPT or proto-InstructGPT) used a filtered version of the Reddit posts TL;DR dataset for SFT as “summarization task is significantly more challenging than on CNN/DM”. This dataset contains about 3 million posts from reddit.com across a variety of topics (subreddits), as well as summaries of the posts written by the original poster (the TL;DRs ). The filtered dataset contains 123,169 posts, of which about 5% was set aside for validation.</p><p>The same dataset is also used for RLHF RM and policy training along with the additional human preference feedback. The authors provide inference code for 1.3B models and baselines, as well as a model card and the human feedback dataset with over 64k summary comparisons.</p><p><strong>InstructGPT’s</strong> “prompt dataset consists primarily of text prompts submitted to the OpenAI API, specifically those using an earlier version of the InstructGPT models (trained via supervised learning on a subset of our demonstration data) on the Playground interface”</p><p>“To train the very first InstructGPT models, we asked labelers to write prompts themselves. This is because we needed an initial source of instruction-like prompts to bootstrap the process, and these kinds of prompts weren’t often submitted to the regular GPT-3 models on the API.”</p><p>“ We asked labelers to write three kinds of prompts:</p><ul><li>Plain: We simply ask the labelers to come up with an arbitrary task, while ensuring the tasks had sufficient diversity.</li><li>Few-shot: We ask the labelers to come up with an instruction, and multiple query/response pairs for that instruction.</li><li>User-based: We had a number of use-cases stated in waitlist applications to the OpenAI API. We asked labelers to come up with prompts corresponding to these use cases.</li></ul><p>From these prompts, we produce three different datasets used in our fine-tuning procedure: (1) our SFT dataset, with labeler demonstrations used to train our SFT models, (2) our RM dataset, with labeler rankings of model outputs used to train our RMs, and (3) our PPO dataset, without any human labels, which are used as inputs for RLHF fine-tuning. The SFT dataset contains about 13k training prompts (from the API and labeler-written), the RM dataset has 33k training prompts (from the API and labeler-written), and the PPO dataset has 31k training prompts (only from the API).”</p><p><strong>Evaluation Datasets</strong>:</p><p>HuggingFace Open LLM Leaderboard uses ARC, HellaSwag, MLLU, Truthful QA, Winnogrande, GSM8K and DROP.</p><p><strong>InstructGPT</strong> authors performed automatic evaluations on the following benchmark datasets:</p><p>“Winogender (Rudinger et al., 2018), CrowS-Pairs (Nangia et al., 2020), RealToxicityPrompts (Gehman et al., 2020), TruthfulQA (Lin et al., 2021), DROP (Dua et al., 2019), QuAC (Choi et al., 2018), SquadV2 (Rajpurkar et al., 2018), Hellaswag (Zellers et al., 2019), SST (Socher et al., 2013), RTE and WSC (both part of SuperGLUE (Wang et al., 2019)), WMT 15 Fr → En (Bojar et al., 2015), CNN/Daily Mail Summarization (Nallapati et al., 2016), and Reddit TLDR Summarization (Völske et al., 2017).”</p><p>Llama2 evaluated and compared the pre-trained models with a number open-source (MPT, Falcon) and closed-source (GPT 3.5/4, PALM-1/2L) models. For open-source comparison , they used both non-aggregated and aggregated benchmarks as follows</p><ul><li>Non-aggregated — HumanEval and MBPP for Code; PIQA, SIQA, HellaSwag, WinGrande, ARC easy and challenge, OpenBookQA and CommonsenseQA for Commonsense Reasoning; NaturalQuestions and TriviaQA for World Knowledge; SQuAD, QuAC and BoolQ for Reading Comprehension; GSM8K and MATH for Mathematics.</li><li>Aggregated — MATH, MMLU, BBH, AGI Eval</li></ul><p><strong>MMLU</strong> (<strong>Massive Multitask Language Understanding</strong>) is a benchmark designed to measure knowledge acquired during pretraining by evaluating models exclusively in zero-shot and few-shot settings. This makes the benchmark more challenging and more similar to how we evaluate humans. The benchmark covers 57 subjects across STEM, the humanities, the social sciences, and more. It ranges in difficulty from an elementary level to an advanced professional level, and it tests both world knowledge and problem solving ability. Subjects range from traditional areas, such as mathematics and history, to more specialized areas like law and ethics. The granularity and breadth of the subjects makes the benchmark ideal for identifying a model’s blind spots.</p><p><strong>MATH</strong> and <strong>GSM-8K</strong> are commonly used benchmarks for mathematical reasoning.</p><p><strong>HellaSwag</strong> is commonsense inference dataset.</p><p><strong>TruthfulQA</strong> is a benchmark made up of questions designed to cause imitative falsehoods (e.g. “What is 1241 × 123?”, GPT-3 outputs “14812” ).</p><p><strong>Winnogrande</strong> is a commonsense reasoning large-scale dataset of 44k problems, inspired by the original WSC design, but adjusted to improve both the scale and the hardness of the dataset.</p><p>Big Bench Hard (<strong>BBH</strong>) — BIG ( Beyond the imitation game) Bench is a set of 204 or more language tasks. The benchmark tasks are novel, and cover a diverse range of topics and languages. The BBH version is a set of 23 challenging BIG-Bench tasks.</p><p><strong>AGI Eval</strong> is a novel benchmark specifically designed to assess foundation model in the context of human-centric standardized exams, such as college entrance exams, law school admission tests, math competitions, and lawyer qualification tests.</p><p><strong>Appendix:</strong></p><p><strong>Reinforcement Learning </strong>— in supervised learning, with easily implementable cost function and gradient descent optimization, it is relatively easy to yield excellent results with relatively little hyperparameter tuning. Unlike supervised learning, reinforcement learning (RL) does not require labelled input/output pairs, and is better suited for goals such as somewhat subjective human safety and alignment, that are not captured well by simple metrics/loss functions.</p><p>There are a 2 significant components in RL — agent (+policy) and environment (+reward). The agent, through its policy, explores the environment and accumulates rewards offered by the environment. The rewards are usually sporadic, not immediate ( e.g. after multiple steps of agent’s exploration ), not easily expressed quantitatively such as loss, etc.</p><p>RL algorithms can be model based or model free. Having a model of the environment and agent <em>a priori</em> is not possible in most situations. Hence, model free approach is often used. Q-learning and SARSA are the most well known in the model free category.</p><p>A <strong>policy</strong> , <em>π(a|s)</em>, is a rule or function used by an agent to decide what actions (<em>a</em>) to take in a state (<em>s</em>). It can be deterministic, in which case it is usually denoted by <em>μ</em>, or it may be stochastic, in which case it is usually denoted by <em>π</em> . Parameters of a policy is denoted by <em>θ</em> .</p><p>Given a policy <em>π</em> and discount factor <em>γ</em> ∈ [0, 1], a <strong>state</strong> <strong>value function</strong> <em>Vπ</em> is an expected sum of discounted rewards (<em>r</em>) over a number of steps (also called horizon).</p><p><em>Vπ (s(t) = s) = Eπ[r(t) + γr(t+1) + γ²r(t+2) + γ³r(t+3) + · · · |s(t) = s] </em>#<em> </em>follow<em> π</em></p><p><em>Q</em> is the state-action value of a policy is defined as follows.</p><p><em>Qπ (s, a) = R(s, a) + γ Σₛₚ P(sp|s, a)Vπ (sp) </em># Take action <em>a</em>, then follow <em>π</em></p><p>The main goal of Reinforcement learning is to find the optimal policy <em>π</em>ᵒᵖᵗ that maximizes the expected cumulative reward</p><p><em>πᵒᵖᵗ(s) = arg max (Vπ(s) )</em></p><p>Value function can be represented by a lookup table where each state has a corresponding entry, <em>V</em>π<em>(s),</em> or each state-action pair has an entry, <em>Q</em>π<em>(s, a)</em>. This is the essence of model free approach called <em>Q-learning</em>. However, lookup table approach does not generalize well with very large state and/or action spaces, or in other cases it might be preferable to quickly learn an approximations function over converged values of each state. A popular way to represent this approximate function currently is deep neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ECOZFDdnIn_5RnWN5GhypA.png" /><figcaption>The SARSA Algorithm ( from CS234 lecture4 slide)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*yyG5lGlEO9GLPWVfoGeICg.png" /><figcaption>The Q-Learning Algorithm ( from CS234 lecture4 slide )</figcaption></figure><p><em>Q-Learning</em> learns a Q-function that satisfies the Bellman Equation. Bellman Equation is a recursive relation on value function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*JLNSsAT1jGWDmk5YiYLDpA.png" /><figcaption>Bellman equation (from CS234 lecture2 slide)</figcaption></figure><p>Learning the Q-function is accomplished by minimizing the Mean Squared Bellman Error (MSBE) loss function. The Q-function is then used to obtain a policy (e.g. ε-greedy ) as shown in the previous picture.</p><p>In Deep Q-Learning, Q is represented by a Deep Neural Network, <em>Q(s,a,w)</em> with parameters <em>w</em>. The update to Q in the algorithm is through SGD on some measure ( e.g. MSE) of difference between oracle/true/correct/target value and the function approximation.</p><p><em>Policy Gradient methods</em> directly try to maximize the expected return by taking small steps in the direction of the policy gradient. Policy gradient algorithms search for a local maximum in value, <em>V(θ) = Vπ(θ), </em>by ascending the gradient of the policy, <em>π(θ)</em>, w.r.t parameters <em>θ , ∆θ = α∇θV(θ). ∇θV(θ) </em>is the policy gradient. Which after some approximation and algebraic works is captured in the Policy Gradient Theorem as follows. The point to note is that it is independent of agent and environment model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*icPy4Fv5huIxz-zOLmTrrA.png" /><figcaption>The Policy Gradient Theorem ( from CS234 lecture8 slides )</figcaption></figure><p>The policy gradient estimator, <em>∇θV(θ)</em> , can be obtained by differentiating the policy objective, <em>J(θ) </em>(or<em> LPG(θ) , </em>policy gradient loss).</p><p>Unlike general RL, in a <strong>Multi-Armed Bandit </strong>environment<strong> </strong>at each time step, the agent takes an action ( based on its policy) where the next state does not depend on the action chosen by the agent.</p><p><strong>PPO-</strong> is a simpler algorithm with the all the stability and reliability benefits of trust region policy optimization (TRPO) algorithm. In TRPO, a surrogate objective function is maximized subject to a KL divergence constraint on the size of the policy update. PPO replaces the KL divergence constraint with a clipping hyper-parameter to limit the updates.</p><p>Whereas standard policy gradient methods perform one gradient update per data sample, PPO objective function enables multiple epochs of mini-batch updates. PPO alternates between sampling data from the policy and performing several epochs of optimization on the sampled data.</p><p>With a neural network architecture that shares parameters between the policy and value function, a loss function that combines the policy surrogate and a value function error term is used. TRPO does not share parameters.</p><p>The following shows the PPO algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xz8L-aCLvRJs_tP4Xyc8w.png" /><figcaption>The PPO Algorithm ( from paper Proximal Policy Optimization )</figcaption></figure><p>In the shared policy and value approach, networks are the same ( see papers “The 37 Implementation Details of Proximal Policy Optimization” and “value_latent”) .</p><p><strong>References:</strong></p><ol><li>HuggingFace Transformers Notebooks , <a href="https://huggingface.co/docs/transformers/notebooks">https://huggingface.co/docs/transformers/notebooks</a></li><li><a href="https://platform.openai.com/docs/models">https://platform.openai.com/docs/models</a></li><li>Improving Language Understanding by Generative Pre-Training, <a href="https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf">https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf</a></li><li>GPT2 — <a href="https://github.com/openai/gpt-2">https://github.com/openai/gpt-2</a> ( implemented in TensorFlow)</li><li>HF GPT2’s gpt2 (124M/12L/768W), gpt2-medium(355M), <a href="https://huggingface.co/gpt2-large">gpt2-large</a> (774M), gpt-XL(1.5B/48L/1600W), —<a href="https://github.com/huggingface/transformers/tree/main/src/transformers/models/gpt2"> https://huggingface.co/gpt2</a> , <a href="https://github.com/huggingface/transformers/tree/main/src/transformers/models/gpt2">https://github.com/huggingface/transformers/tree/main/src/transformers/models/gpt2</a> ( has both TF and PT codes) .</li><li>Language Models are Unsupervised Multitask Learners, <a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf">https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf</a></li><li>GPT3 — <a href="https://en.wikipedia.org/wiki/GPT-3">https://en.wikipedia.org/wiki/GPT-3</a></li><li>GPT3 — Language Models are Few-Shot Learners, <a href="https://arxiv.org/abs/2005.14165">https://arxiv.org/abs/2005.14165</a></li><li>Deep Reinforcement Learning from Human Preferences, <a href="https://arxiv.org/pdf/1706.03741.pdf">https://arxiv.org/pdf/1706.03741.pdf</a></li><li>Scalable agent alignment via reward modeling:<br>a research direction, <a href="https://arxiv.org/pdf/1811.07871.pdf">https://arxiv.org/pdf/1811.07871.pdf</a></li><li>Better Rewards Yield Better Summaries:<br>Learning to Summarise Without Reference, <a href="https://arxiv.org/pdf/1909.01214.pdf">https://arxiv.org/pdf/1909.01214.pdf</a></li><li>Fine-Tuning Language Models from Human Preferences, <a href="https://arxiv.org/pdf/1909.08593.pdf">https://arxiv.org/pdf/1909.08593.pdf</a></li><li>Learning to summarize from human feedback, <a href="https://arxiv.org/pdf/2009.01325.pdf">https://arxiv.org/pdf/2009.01325.pdf</a> , <a href="https://github.com/openai/summarize-from-feedback">https://github.com/openai/summarize-from-feedback</a> , <a href="https://openaipublic.blob.core.windows.net/summarize-from-feedback/website/index.html#/">https://openaipublic.blob.core.windows.net/summarize-from-feedback/website/index.html#/</a> ,</li><li>InstructGPT, <a href="https://openai.com/research/instruction-following">https://openai.com/research/instruction-following</a>,</li><li>InstructGPT, Training language models to follow instructions<br>with human feedback, <a href="https://arxiv.org/pdf/2203.02155.pdf">https://arxiv.org/pdf/2203.02155.pdf</a></li><li>Introducing ChatGPT, <a href="https://openai.com/blog/chatgpt">https://openai.com/blog/chatgpt</a></li><li>GPT-4 Technical Report, <a href="https://arxiv.org/pdf/2303.08774.pdf">https://arxiv.org/pdf/2303.08774.pdf</a></li><li>GPT-Neo <a href="https://github.com/EleutherAI/gpt-neo">https://github.com/EleutherAI/gpt-neo</a></li><li>GPT-NeoX <a href="https://github.com/EleutherAI/gpt-neox/">https://github.com/EleutherAI/gpt-neox/</a></li><li><a href="https://github.com/Lightning-AI/lit-gpt">https://github.com/Lightning-AI/lit-gpt</a></li><li>C4 dataset . <a href="https://huggingface.co/datasets/allenai/c4">https://huggingface.co/datasets/allenai/c4</a></li><li>Scaling Language Model Training to a Trillion Parameters Using Megatron, <a href="https://developer.nvidia.com/blog/scaling-language-model-training-to-a-trillion-parameters-using-megatron/">https://developer.nvidia.com/blog/scaling-language-model-training-to-a-trillion-parameters-using-megatron/</a></li><li>Llam2 — <a href="https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/">https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/</a><br>Llama 2: Open Foundation and Fine-Tuned Chat Models, <br><a href="https://github.com/facebookresearch/llama-recipes/blob/main/docs/Dataset.md">https://github.com/facebookresearch/llama-recipes/blob/main/docs/Dataset.md</a><br><a href="https://github.com/facebookresearch/llama-recipes/tree/main/examples">https://github.com/facebookresearch/llama-recipes/tree/main/examples</a><br><a href="https://github.com/facebookresearch/llama-recipes/tree/main">https://github.com/facebookresearch/llama-recipes/tree/main</a></li><li>Llama 2 is here — get it on Hugging Face, <a href="https://huggingface.co/blog/llama2">https://huggingface.co/blog/llama2</a>, <a href="https://github.com/huggingface/blog/blob/main/llama2.md">https://github.com/huggingface/blog/blob/main/llama2.md</a></li><li>Understanding Encoder And Decoder LLMs <a href="https://magazine.sebastianraschka.com/p/understanding-encoder-and-decoder">https://magazine.sebastianraschka.com/p/understanding-encoder-and-decoder</a></li><li>Gradient Checkpointing — Training Deep Nets with Sublinear Memory Cost, <a href="https://arxiv.org/pdf/1604.06174v2.pdf">https://arxiv.org/pdf/1604.06174v2.pdf</a></li><li><a href="https://huggingface.co/datasets/timdettmers/openassistant-guanaco">https://huggingface.co/datasets/timdettmers/openassistant-guanaco</a> — subset of oasst highest-rated paths in the conversation tree, with a total of 9,846 samples.</li><li>Dolly (Databricks) -15,000 instruction-context-response triples, <a href="https://github.com/databrickslabs/dolly">https://github.com/databrickslabs/dolly</a> , <a href="https://huggingface.co/datasets/databricks/databricks-dolly-15k">https://huggingface.co/datasets/databricks/databricks-dolly-15k</a></li><li>MMLU (Massive Multitask Language Understanding) — <a href="https://arxiv.org/abs/2009.03300v3">https://arxiv.org/abs/2009.03300v3</a>, <a href="https://github.com/hendrycks/test">https://github.com/hendrycks/test</a>, <a href="https://huggingface.co/datasets/cais/mmlu">https://huggingface.co/datasets/cais/mmlu</a></li><li>HF LLM Leaderboard — <a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard">https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard</a></li><li>LLM Inference Performance Engineering: Best Practices, <a href="https://www.databricks.com/blog/llm-inference-performance-engineering-best-practices">https://www.databricks.com/blog/llm-inference-performance-engineering-best-practices</a></li><li>Prometheus: Inducing Fine-grained Evaluation Capability in Language Models, <a href="https://arxiv.org/abs/2310.08491">https://arxiv.org/abs/2310.08491</a>, <a href="https://huggingface.co/datasets/kaist-ai/Feedback-Collection">https://huggingface.co/datasets/kaist-ai/Feedback-Collection</a>, <a href="https://huggingface.co/kaist-ai/prometheus-13b-v1.0">https://huggingface.co/kaist-ai/prometheus-13b-v1.0</a></li><li>Rejection Sampling <a href="https://web.mit.edu/urban_or_book/www/book/chapter7/7.1.3.html">https://web.mit.edu/urban_or_book/www/book/chapter7/7.1.3.html</a>, <a href="https://people.eecs.berkeley.edu/~jordan/courses/260-spring10/lectures/lecture17.pdf">https://people.eecs.berkeley.edu/~jordan/courses/260-spring10/lectures/lecture17.pdf</a></li><li>Reducing Activation Recomputation in Large Transformer Models, <a href="https://arxiv.org/abs/2205.05198">https://arxiv.org/abs/2205.05198</a>677</li><li>MQAN , The Natural Language Decathlon: Multitask Learning as Question Answering, <a href="https://arxiv.org/pdf/1806.08730.pdf">https://arxiv.org/pdf/1806.08730.pdf</a></li><li>Introduction to RL , <a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html">https://spinningup.openai.com/en/latest/spinningup/rl_intro.html</a></li><li>Learning from human preferences, <a href="https://openai.com/research/learning-from-human-preferences">https://openai.com/research/learning-from-human-preferences</a></li><li>RLHF: Reinforcement Learning from Human Feedback, <a href="https://towardsdatascience.com/rlhf-reinforcement-learning-from-human-feedback-faa5ff4761d1">https://towardsdatascience.com/rlhf-reinforcement-learning-from-human-feedback-faa5ff4761d1</a></li><li>RLHF, <a href="https://en.wikipedia.org/wiki/Reinforcement_learning_from_human_feedback">https://en.wikipedia.org/wiki/Reinforcement_learning_from_human_feedback</a></li><li>Proximal Policy Optimization (PPO), <a href="https://openai.com/research/openai-baselines-ppo">https://openai.com/research/openai-baselines-ppo</a></li><li>Proximal Policy Optimization Algorithms, <a href="https://arxiv.org/pdf/1707.06347.pdf">https://arxiv.org/pdf/1707.06347.pdf</a></li><li>The 37 Implementation Details of Proximal Policy Optimization, <a href="https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/">https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/</a></li><li>value_latent , <a href="https://github.com/openai/baselines/blob/master/README.md?plain=1#L92">https://github.com/openai/baselines/blob/master/README.md?plain=1#L92</a></li><li>Temperature sampling , top-k samplng — THE CURIOUS CASE OF NEURAL TEXT DeGENERATION, <a href="https://arxiv.org/pdf/1904.09751.pdf">https://arxiv.org/pdf/1904.09751.pdf</a></li><li>CSC 411 Lecture 21–22: Reinforcement learning, <a href="https://www.cs.toronto.edu/~jlucas/teaching/csc411/lectures/lec21_22_handout.pdf">https://www.cs.toronto.edu/~jlucas/teaching/csc411/lectures/lec21_22_handout.pdf</a></li><li>SARSA — <a href="https://en.wikipedia.org/wiki/State-action-reward-state-action">https://en.wikipedia.org/wiki/State-action-reward-state-action</a></li><li>Q-Learning — <a href="https://en.wikipedia.org/wiki/Q-learning">https://en.wikipedia.org/wiki/Q-learning</a></li><li>CS234: Reinforcement Learning Winter 2019, <a href="https://web.stanford.edu/class/cs234/CS234Win2019/schedule.html">https://web.stanford.edu/class/cs234/CS234Win2019/schedule.html</a></li><li>David Silver’s UCL Course on RL , <a href="https://www.davidsilver.uk/teaching/">https://www.davidsilver.uk/teaching/</a> , <a href="https://www.davidsilver.uk/wp-content/uploads/2020/03/pg.pdf">https://www.davidsilver.uk/wp-content/uploads/2020/03/pg.pdf</a></li><li>HuggingFace Deep Reinforcement Learning Course <a href="https://huggingface.co/learn/deep-rl-course/unit0/introduction">https://huggingface.co/learn/deep-rl-course/unit0/introduction</a></li><li>Introduction to Multi-Armed Bandits, <a href="https://www.tensorflow.org/agents/tutorials/intro_bandit">https://www.tensorflow.org/agents/tutorials/intro_bandit</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b581da9adbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network and AI Bottlenecks]]></title>
            <link>https://whatdhack.medium.com/neural-network-and-ai-bottlenecks-f9c7357b73fa?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c7357b73fa</guid>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 01:38:50 GMT</pubDate>
            <atom:updated>2023-07-10T01:38:50.406Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a relatively high-level and simplified view of where the limitations are in modern Deep Learning (DL) based AI stack. Compute can be thought of as composed of arithmetic operations and memory access. In recent times, arithmetic throughput has increased significantly, but memory access throughput has lagged behind. This divergence has resulted in low utilization of hardware resources at the application level.</p><p>DL applications are unique in that they require huge amounts of data and use relatively simple matrix or linear algebra that does not require control flow. These characteristics make GPUs with thousands of cores ideal for DL parallelization.</p><p>Deep Learning application training requires repeating the same computation using the back-propagation algorithm over many iterations that uses new data from a dataset over many epochs that reuses the same dataset. That then slowly converges to a set of weights( matrices) that can be used for inference. On a single GPU, that process can take months.</p><p>Another form of parallelism called Distributed Computing, also known as High-Performance Computing (HPC) is used to bring down the convergence time. A cluster of 1000&#39;s of GPUs that are connected through high bandwidth network ( e.g. multiple 25 GB/s NICs, etc.) are run in parallel. Every GPU runs the same code over the same set of data. After one or more iterations, the GPUs synchronize. This is called data parallelism and is the most widely used parallelization technique.</p><p>In recent times, AI models (GPT, etc.) have also grown in size of parameters well beyond the memory capacity of a single GPU (~ 80 GB), which has resulted in dividing a large DL network into parts over multiple GPUs. Techniques such as model parallelism, tensor parallelism, etc. are used to divide a network.</p><p><strong>CPUs and GPUs:</strong></p><p>GPUs are parallel processing systems. They usually use Single Instruction Multiple Thread/Data ( SIMT/D). Their cores are simpler, and 1,000s are packed into one chip. All or groups of the cores can run the same code in parallel over different parts of data.</p><p>CPU cores are more complex and can handle complex control flow ( if-then-else, branch prediction, out-of-order execution, interrupt handling, etc. ) type of execution better. The Streaming Multiprocessors (SMs) in Nvidia GPUs contain control logic. Hence, an SM and a CPU core can be considered roughly to be equivalent. However, unlike CPU cores, SMs issue instructions in order with no branch prediction or speculative execution. State-of-the-art CPUs and GPUs contain similar numbers of cores and SMs respectively. The Cuda cores are pure compute units like the ALUs in CPUs.</p><p>The CPU cores are not capable of running in parallel on the same code ( e.g. SIMD/T) as the GPU cores. Vector ( more than 1 operand ) execution is a way to address this limitation in CPU by running several streams of data in one core.</p><p>The following figures show architecture block diagrams of a single AMD Zen x86 CPU core and an SM of Nvidia H100. This particular single Zen CPU core has 4 FP units and 6 INT units. x86 AVX/SSE etc vector instructions use these SIMD units. The AMD EPYC™ 9754 CPU has 128 cores. For comparison, the Nvidia H100 GPU has 16896 FP32 CUDA Cores, 528 TensorCores, and 132 SMs. Hence, 128 CUDA cores per SM vs 4 FP units in Zen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*ujUALNFKEV5gGaeZ.png" /><figcaption>AMD Zen core block diagram ( Wikichip)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Sbwt6BKaKiqjNTckhHljig.png" /><figcaption>Nvidia H100 SM core (Nvidia)</figcaption></figure><p><strong>Memories:</strong></p><p>Both CPUs and GPUs have a hierarchy of memories- L1 to n levels of caches between the processors and the main memory. Caches are Static RAMs. The main memory traditionally has been DDR (DRAM). Recently, the use of High Bandwidth Memory (HBM) has started gaining traction in DL/AI systems. HBMs are high-speed DRAMs made possible by the use of 1,000s of data pins placed close to the CPU or the GPU. DDRs have 100s of pins and are placed further away. SRAMs are 100x faster than DRAMs, but take more area and consumes more power, hence their use is primarily limited to internal caches. The following figure and table show the memory hierarchy (some numbers are educated guesses). With DDR5, ~ 33.5 GB/s throughput can be achieved vs 12.5 GB/s of DDR4 (Rambus). The SRAM numbers are calculated assuming FLOPS is limited by cache memory bandwidth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*-pHZk4ChDOVnGh7bdAyXKg.png" /><figcaption>Bandwidth and latency for memories and NICs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*AmoV_HyN6xJ20xohHYdCcA.png" /><figcaption>Bandwidth and latency for memories and NICs</figcaption></figure><p>The access latency for different types of memories can be hard to get. In the case of DRAMs, a single number for latency is also difficult to define, because of the complex operating principle of DRAM. DRAM operation is very different from that of SRAM and involves many more constraints.</p><p><strong>Measuring Compute :</strong></p><p>Operations per second (OPS), is the number of floating point ( FP32, TF32, FP64, BF16, FP16) or integer (INT8, INT4, INT3) operations that can be performed by a CPU or GPU. The most widely used measure is the number of single precision (FP32) floating operations per second (FLOPS). Although in recent years, lower precision arithmetics (BF16, FP16, INT8) have started gaining traction.</p><p>Arithmetic or Operational Intensity (OI), refers to how many arithmetic operations is executed per byte of memory access.</p><p>The roofline chart is a plot with OI on the horizontal axis and FLOPS on the vertical axis. The following figure shows a conceptual Roofline chart. The low OI region is where memory bandwidth is the limiting factor. The high OI region is where the processor cores are the limiting factor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*w0Zgr2Ivo8B0oNFBmqZEtA.png" /><figcaption>Roofline chart (COMET paper)</figcaption></figure><p>To fully utilize the arithmetic engines of a GPU, one will need at least the OI number of operations per byte of data!</p><p><strong>GPU Operational Intensity:</strong></p><p>The NVDIA V100, A100 and H100 are the 3 generations of GPUs used extensively in DL. Their significant specifications are shown in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*ebhYFuIpoDokFDCmgD731Q.png" /><figcaption>Specifications for 3 generations of Nvidia GPUs and Graphcore IPU</figcaption></figure><p>The following figure shows how TOPS and memory bandwidth TB/s evolved over time from V100 to H100. FP32 TOPS tracked memory bandwidth more or less. With the introduction of TensorCores, INT8 operation performance jumped by orders of magnitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*yeq__UCB_qzD3-rH3jT8ZQ.png" /><figcaption>Evolution of TOPS and TB/s from V100 through A100 to H100.</figcaption></figure><p>The following figure shows the normalized OI for FP32 and INT8 operations. The normalized FP32 memory bandwidth is obtained by dividing the TB/s by 4 as an FP32 uses 4 bytes. Similarly for INT8, the normalization factor is 1, as INT8 just takes 1 byte. Although memory bandwidth is increasing, so is normalized OI. The application OI needed to fully utilize H100 arithmetic engines is 2000 for INT8 and 60 for FP32. In V100 they were 62 and 15.7 respectively for INT8 and FP32. The improvement in FP32 TOPS is entirely attributable to a bigger chip ( which in turn is due to smaller geometry — 4 nm in H100 vs 12 nm in V100 ) and higher frequency — 60/15.7 = 3.82 = 16896/5120*1.78/1.53. The INT8 acceleration is attributable to TensorCores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kDRQ938f7gBzLPCPkhrS7w.png" /><figcaption>Normalized Operational Intensity vs Memory Bandwidth for V100 , A100 and H100.</figcaption></figure><p>From the above anecdotal example, it is apparent that arithmetic execution units are limited by memory bandwidth if application OI is not high enough.</p><p>Both modern CPUs and GPUs are built with a number of accelerators. The most well-known are the TensorCores in Nvidia processors. A100 has 432 third-generation TensorCores. TensorCores are essentially units that can accelerate matrix dot products (e.g. <em>C= A.B</em> ) as shown below. They can compute the dot product for sub-blocks of tensor in one cycle. Hence, they can be several times faster than just using Cuda cores. TensorCores are primarily used through libraries like CuDNN, CuBLAS, etc. They can also be directly programmed through Cuda with the <em>mma</em> instructions. The recent Nvidia H100 also incorporates Transformer Accelerator, which accelerates the transformer architecture used in Large Language Models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPiH8hfYYcweXyxSdekZAw.png" /><figcaption>A100 TensorCore for dense and sparse dot products ( Nvidia)</figcaption></figure><p><strong>Divergence of Memory Bandwidth and Arithmetic Speed:</strong></p><p>The reasons for the divergence in arithmetic and memory throughput are many folds. Some of which are as follows.</p><p>DRAM operation requires extra overhead such as refresh cycles etc., that limits the throughput that can be achieved.</p><p>The physical distance between the processors and the memory is also a factor. DRAMs are placed external to the CPU/GPU. Hence they are separated not only by longer distance but transmitting/receiving data on and off the die ( a piece of silicon) requires more circuitry. The longer the distance between the 2 points, the lower the bit rate that can be achieved between them with the same energy. The more energy is used, the more of it is wasted as heat which then has to be removed for the chip to not “melt”. There is a well-developed branch of engineering and mathematics called Communications Theory and Technology that is devoted to the issue of transmission and reception of data and information.</p><p>The fabrication process for DRAM is also different so it is not easy to integrate DRAMs into a logic chip.</p><p>HBM/DRAMs are capacitors and hence it has been difficult to reduce their dimension below 10 nm. No such limit for the arithmetic units exists! Arithmetic units can continue to become faster and faster as they encounter less and less capacitive effect at lower line width (&lt; 10 nm) and consequent higher frequency, whereas the former is limited by the required minimum capacitor size! However, arithmetic unit miniaturization is also beginning to come into contact with fundamental physical limitations like quantum effects at sub-nano-meter gate lengths. The heat dissipation limit has already stagnated logic chip frequency to about 2.5 GHz.</p><p><strong>Nature of Deep Learning Arithmetic:</strong></p><p>Deep Learning applications pass input data (tensors) through a number of layers. The layers are usually tensor dot products followed by a non-linear function called the activation function. The activation function is applied to each tensor element individually and independently. Functions that work on each element individually and independently are called element-wise. The dot product part of a layer is usually a <em>matmul</em> or a <em>convolution</em>. Element-wise functions are <em>add</em>, <em>mul</em>, <em>relu</em>, <em>sigmoid</em>, <em>Batch Norm</em>, <em>Layer Norm</em>, etc.</p><p><em>Matmuls</em> and <em>convolutions</em> at proper sizes have high OI and hence can be arithmetic bound. This can be understood by considering the dot product between 2 <em>NxN</em> matrices ( matrices are 2-dimensional tensors), <em>C = A.B</em> . Very simply, a column of <em>B</em> can be read from memory into the GPU and stored in cache. Which then can be reused to compute all the elements of a column of <em>C</em>. As <em>N</em> increases, there is proportionately more reuse of the column of <em>B</em>, hence OI increases. To fully utilize all the cuda cores (6912 FP32 cores in A100), and achieve specified TOPS requires a large <em>N</em> ( ~ 10K+).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*vZPFLpqynVVtPAn0deEgFA.png" /><figcaption>Matmul of 2-rank tensors</figcaption></figure><p>Whereas <em>add</em>, <em>relu</em>, <em>sigmoid</em>, <em>softmax</em>, etc element-wise operations are memory bound. These operations have low OI, as only 1 operation is performed for one output element. Consider the elementwise multiplication of 2 <em>NxN</em> matrices, <em>C = A * B</em> . Here, unlike the dot product case, each element of <em>A</em> and <em>B</em> are used only once to produce 1 element of C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*pWTrFxDbc_TZsBSNM5bYlg.png" /><figcaption>Elementwise mul (also known as Hadamard product ) of 2-rank tensors.</figcaption></figure><p>Usually during the forward pass a number of intermediate tensors are generated that are required for the backward pass. These intermediate tensors are stored in the memory, hence memory bottlenecks play a big role in application throughput.</p><p>An important property of a layer (and linear algebra) is that each element of the output tensor can be computed independently of other elements. Hence they can be made “embarrassingly” parallel. Which makes them ideal for parallel computing systems like GPUs.</p><p>In a DL model, in addition to <em>matmuls</em> and <em>convolutions</em>, a plethora of element-wise ops are required. This can be seen from the following example of a very small GPT based Language Model (LM ). The following code shows the layers in the very small GPT. Linear layers are <em>matmuls.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*R81MHFZRqmiYE2E-OkFVLg.png" /><figcaption>Small GPT based network ( TinyStories)</figcaption></figure><p>The above model results in 51 different GPU kernels — <em>gemm (matmul)</em>, <em>layer_norm</em>, <em>elementwise</em> <em>mul</em>, etc. Each of these kernels is also executed multiple times. Only about 25% of the end-to-end time is attributable to <em>gemms</em> (<em>matmul</em>), and the rest is used by element-wise ops, memory copy, a multitude of software/hardware overhead, etc.</p><p><strong>Techniques to Improve OI :</strong></p><p>One of the easiest techniques is increasing the batch size. Which increases the one dimension of the tensors. If <em>matmul</em> and/or <em>convolutions</em> dominate the application, then OI increases.</p><p>Kernel fusion is another approach to accelerate memory-bound operations. When multiple operations can be applied to the same input, the input can be loaded once from HBM, instead of multiple times for each operation, and then hold the intermediate results in cache and registers. Compilers (e.g. XLA) can automatically fuse multiple element-wise operations</p><p>Flash Attention is a technique of trading off memory for compute. Standard attention implementations with inputs <em>Q, K, and V</em> materializes the intermediate matrices <em>S</em> and <em>P</em> to HBM, which takes 𝑂(𝑁²) memory. The main idea behind Flash Attention is tiling and recomputing. Tiling splits the inputs <em>Q, K, </em>and<em> V</em> into blocks, load them from slow HBM to fast SRAM, then computes the attention output with respect to those blocks. By scaling the output of each block by the right normalization factor before adding them up, it is able to get the correct result in the end. The backward pass typically requires the matrices <em>S, P ∈ R ^ (𝑁 ×𝑁 ) </em>to compute the gradients with respect to <em>Q, K, V. </em>However, by storing the output <em>O</em> and the softmax normalization statistics <em>(𝑚, ℓ)</em>, the algorithm can recompute the<br>attention matrix <em>S</em> and <em>P</em> easily in the backward pass from blocks of <em>Q, K, V</em> in SRAM.</p><pre>S = QK^T ∈ R^(𝑁 ×𝑁)<br>P = softmax(S) ∈ R^(𝑁 ×𝑁 )<br>O = PV ∈ R^(𝑁 x d)</pre><p><strong>Techniques to Improve Memory Bandwidth:</strong></p><p>he following table summarizes the SOTA from the 3 main vendors of HBM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*6WYZsLPeJssICBk4gD_5tQ.png" /><figcaption>HBM ( DRAM) specifications</figcaption></figure><p>AMD’s stacked HBM where the HBM memory is physically stacked on top of the GPU, thus reducing the physical distance between arithmetic engines and memory. They claim to have doubled the memory bandwidth this way.</p><p>One fundamental problem for DRAM is that it relies on storing charge in capacitors to represent bits, and shrinking capacitor sizes below a certain dimension is not possible. For this reason, DRAM manufacturing has stagnated at 10 nm. Further shrinking may require breakthroughs or fundamental shifts.</p><p><strong>Distributed or High-Performance Compute :</strong></p><p>The next level of parallelism involves connecting many GPUs together. There are primarily 2 motivations for this. One is to reduce the time to convergence, say from 1 month with a single GPU to 45 minutes with 1,000 GPUs. Another reason is to handle large networks with 100’s of billions of parameters (tensors). A single GPU currently only has of the order of 100 GB of memory. Just one 100 billion FP32 element (dense) tensor requires 400 GB of memory. A large neural network would have many more than just 1 tensor of that size.</p><p>There are usually 2 levels of hierarchy in distributed computing. A number of GPUs are connected by high-speed links like <em>NVLink</em> within a node. A node usually has 1 CPU complex with 1 to 4 CPUs. The OS views all the CPUs as one, albeit with NUMA (Non-Uniform Memory Architecture) constraint. The nodes are then connected by high-speed <em>NICs</em> ( e.g. 200 Gb/s Ethernet) and switches. The commonly used network architecture is called leaf-and-spine.</p><p>The software infrastructure layer most commonly used for distributed computing is Message Passing Interface (MPI). A number of MPIs have been developed over the last few decades in the context of High-Performance Computing (HPC) and they are mature technologies. There are well-developed distributed ops (also called collectives ) called <em>allreduce</em>, <em>allgather</em>, etc., that optimally perform averaging, etc operations across 100 K or even millions of processes.</p><p>The most commonly used MPI algorithm in Deep Learning is <em>allreduce</em>. Conceptually it is the application of a tensor operation such as averaging, summing, etc across the N processes where each process ends up with the exact same value. A naive approach would be to broadcast a copy of each process’ tensor to the rest of the processes ( e.g. <em>N*(N-1)</em> exchanges ). After the exchanges, each process applies a tensor operator ( e.g. average ) to all the N tensors and as a result, has the exact same resultant tensor.</p><p>The most commonly used <em>allreduce</em> algorithm is called ring. The nodes are considered to be in a logical ring, independent of the actual physical network connectivity. The full <em>allreduce</em> is then composed of <em>reduce-scatter</em> and <em>allgather</em>. A 4-rank 4-link example of these steps is shown in the following table. A rank is a process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*L-2JwQN1kjCWqg0MAexxxw.png" /><figcaption>4 rank ring allreduce.</figcaption></figure><p>There are other <em>allreduce</em> algorithms such as Rabenseifner, Recursive Doubling, etc. There is a simple analytical expression for ring allreduce time (<em>tar</em>) as follows. A lot can be understood from this simple equation.</p><p><em>tar = 2(N-1) ( α +βM/N + γM/N)</em> = <em>2(Nα +βM + γM)(N-1)/N ~ 2(Nα +βM + γM)</em></p><p>In the abov<em>e, N</em>- number of ranks, <em>α — </em>latency, <em>β — </em>inverse of network bandwidth<em>, γ — the inverse</em> of memory bandwidth, <em>M — </em>the size of tensor. <em>γ </em>essentially ignores the arithmetic overhead as these are simple elementwise ops, hence memory bound. <em>α </em>is a term that captures the end-to-end latency or setup time.</p><p>The network bandwidth (<em>bwn</em>) on each link at any point in time is as follows. Bandwidth need becomes smaller and smaller as <em>N</em> increases.</p><p><em>bwn = (M/N)/(2(N-1) ( α +βM/N + γM/N)) </em>=</p><p><em>1/(2(N-1)N/M ( α +βM/N + γM/N)) =1/(2(N-1) ( αN/M +β+ γ))</em></p><p><em>~ 1/(2α(N-1) ( αN/M)) ~M/(2αN²)</em></p><p>The total amount of data moved is <em>2(N-1)*M</em> over <em>2(N-1)</em> time steps.</p><p>For large <em>N</em>, the latency determines the <em>allreduce</em> time and network bandwidth utilization. Higher the latency, the longer the <em>allreduce</em> time and the lower the network bandwidth utilization.</p><p>In the Nvidia DGX H100 system, there are 8 H100 GPUs. Each GPU is connected to 1 of 4 NVSwitches with 900 GB/s NVLinks. See the following figure for the conceptual block diagram of a DGX H100 system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*gW5xwxkbMtuCc0r0.png" /><figcaption>Block diagram of a Nvidia DGX H100 system (Nvidia)</figcaption></figure><p>If we just consider one DGX H100 system, hence scale-up, as an example, then <em>β </em>( for FP32 ring )<em> </em>can be estimated as follows. .</p><p><em>1/900e9 = 4.44e-12 = 1.11 ps/B,</em></p><p>Similarly, <em>γ </em>can be estimated as follows.</p><p><em>1/3350e9 = 0.2975 e-12 = 0.2975 ps/B,</em></p><p>Latency numbers are not easily available as mentioned previously. However, can be estimated by running <em>allreduce</em> of very small tensors/buffers. From a couple of publications ( see Reference ) the latency for 2 node DGX A100 was observed to be of the order of <em>50 us</em>. Just scale-up latency would be less than that, but would not get anywhere close to pico-seconds. For our purpose, if we assume that latency scales as the inverse of the bandwidth of the slowest link, ( e.g. NIC for scale-up and NVLink for scale-out), then we get <em>50/(900/200) = 12.5 </em>us. Hence, the latency factor would dominate for tensor sizes below <em>(12.5e-6/1.4e-12)*1e-6 = 8.9 MB </em>, for <em>N</em>=1 and <em>72</em> MB for N=8, and so on.</p><p>The other extreme is a mesh (all-to-all or broadcast) connection. Which minimizes the time at the expense of network and memory bandwidth. Mesh connection can be done easily in DGX H100/A100 because of the NVSwitch architecture. Each GPU can broadcast its content to the 7 other GPUs. In this case, the bandwidth available to each GPU, 900 GB/s, is shared by 7 connections.</p><p>The <em>allreduce</em> time (<em>tar</em>) and network bandwidth (<em>bwn</em>) can be analytically expressed as follows.</p><p><em>tar = α + (β + γ(N-1))M</em></p><p><em>bwn</em> = M/(<em>α + (β + γ(N-1))M) ~ 1/(γN)</em></p><p>The total amount of data moved is <em>N(N-1)M</em> over 1 time step. The memory bandwidth increases with <em>N</em>, hence would not scale well.</p><p>Plugging in the numbers for DGX H100, the following table is obtained. From there it appears that mesh performs better on smaller message/tensor sizes at a smaller scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*gqf64lIBRgFVF7JBfwmilw.png" /><figcaption>Ring vs mesh scale-up in DGX H100</figcaption></figure><p>When many DGX systems are connected into a cluster with switched and fiber-optic cables, additional latencies are added by each component between ranks — multiple switches, signal propagation time in cables, etc. For a 50 feet square cluster, the corner-to-corner distance itself can add ( 1.25 ns/f *100 = 125 ns) due to the speed of signal propagation. The NVIDIA Spectrum SN5000 Series Switches have latency of 0.3 micro-second. In a single spine-leaf architecture, a packet might have to traverse 4 switches, hence end-to-end latency from switches is 1.2 micro-second. These additional latencies increase the <em>allreduce</em> time.</p><p><strong>Scaling Efficiency:</strong></p><p>A common measure for scaling is scaling efficiency. Which is a measure of how much of the TOPS available is usable. It is commonly calculated as the ratio iteration time of just 1 process or no collectives to the iteration time with collectives. In the worst-case scenario, all the time for collectives gets added to the 1 process iteration time (<em>t1iter</em>). The scaling efficiency ( SE) is then as follows</p><p><em>SE</em> = <em>t1iter/</em>(<em>t1iter+tar)</em></p><p><em>Allreduce</em> is a synchronization operation that makes all processes run somewhat in lockstep. In reality, each process may experience slightly different iteration times which again may vary from iteration to iteration ( <em>tvar</em>). This variation also reduces <em>SE</em>. There is also additional overhead involved with TensorFlow or PyTorch ( <em>tfw</em> ) as the tensors reside in them and have to copied to <em>NICs</em> etc. Hence the <em>SE</em> with these 3 additional overhead incorporated looks as follows.</p><p><em>SE</em> = <em>t1iter/</em>(<em>t1iter+tar+tfw+tvar)</em></p><p>From the above equation, it is apparent that for best <em>SE</em>, <em>t1iter </em>should be as high as possible. However as GPUs and memories become faster, <em>t1iter</em> decreases and consequently, <em>SE</em> decreases, unless the other 3 components also go down proportionately.</p><p>A simple technique to improve <em>SE</em> is to increase batch size. Batch size does not influence the weight/parameter size that needs to be <em>allreduced</em> ( or other collectives) but increases the iteration time. Another simple technique is to do collectives only every n-th iteration. Both of these techniques have been found to work well, although convergence could become an issue at higher values of batch size and iteration aggregation.</p><p>Another technique is to hide or overlap the overhead of collectives behind compute. In this case, only part or none is exposed or gets added to the iteration time.</p><p><strong>End Note:</strong></p><p>The relatively simple linear algebraic arithmetic used in Deep Learning is well suited for the large-scale parallel computing made possible by 10,000s of simpler cores of a single GPU compared to 100s of more complex cores in CPUs.</p><p>Arithmetic throughput and memory bandwidth mismatch result in low utilization of the formidable arithmetic resources available in modern GPUs. This mismatch is exacerbated by the introduction of higher-performance arithmetic units like TensorCores.</p><p>Memory bandwidth is limited by DRAM technology limitations at this point. HBM partially addresses this by adding 1000s of data pins and reducing the physical distance to the arithmetic units.</p><p>A second level of parallelism is achieved through networking 1,000s+ of GPUs through complex and expensive hardware and software. The overhead of this complex system results in the utilization of less than 100% of single GPU performance.</p><p><strong>Used References:</strong></p><p>Contents from the following are used in some form in the above piece.</p><ol><li>DDR5 vs DDR4 DRAM — All the Advantages &amp; Design Challenges, <a href="https://www.rambus.com/blogs/get-ready-for-ddr5-dimm-chipsets/#:~:text=DDR5%20Scales%20to%208.4%20GT,increase%20to%204.8%20GT%2Fs">https://www.rambus.com/blogs/get-ready-for-ddr5-dimm-chipsets/#:~:text=DDR5%20Scales%20to%208.4%20GT,increase%20to%204.8%20GT%2Fs</a>.</li><li>Roofline model, <a href="https://en.wikipedia.org/wiki/Roofline_model">https://en.wikipedia.org/wiki/Roofline_model</a></li><li>COMET: A Comprehensive Cluster Design Methodology for Distributed Deep Learning Training, <a href="https://arxiv.org/abs/2211.16648">https://arxiv.org/abs/2211.16648</a></li><li>A Systematic Methodology for Analysis of Deep<br>Learning Hardware and Software Platforms, <a href="https://mlsys.org/media/mlsys-2020/Slides/1435.pdf">https://mlsys.org/media/mlsys-2020/Slides/1435.pdf</a>, <a href="https://github.com/Emma926/paradnn">https://github.com/Emma926/paradnn</a></li><li>DictFormer: Tiny Transformer with Shared Dictionary <a href="https://openreview.net/forum?id=GWQWAeE9EpB">https://openreview.net/forum?id=GWQWAeE9EpB</a></li><li>AI chip features hardware support for transformer models, <a href="https://www.embedded.com/ai-chip-features-hardware-support-for-transformer-models/">https://www.embedded.com/ai-chip-features-hardware-support-for-transformer-models/</a></li><li>TinyStories: How Small Can Language Models Be and Still Speak<br>Coherent English? , <a href="https://arxiv.org/pdf/2305.07759.pdf">https://arxiv.org/pdf/2305.07759.pdf</a>, <a href="https://huggingface.co/roneneldan">https://huggingface.co/roneneldan</a>, <a href="https://huggingface.co/roneneldan/TinyStories-1M">https://huggingface.co/roneneldan/TinyStories-1M</a>,</li><li>FlashAttention, <a href="https://github.com/HazyResearch/flash-attention">https://github.com/HazyResearch/flash-attention</a></li><li>Memory-Limited Layers User’s Guide, <a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-memory-limited/index.html#mem-limited">https://docs.nvidia.com/deeplearning/performance/dl-performance-memory-limited/index.html#mem-limited</a></li><li>GPU Performance Background User’s Guide, <a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html">https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html</a></li><li>NVIDIA A100 Tensor Core GPU Architecture, <a href="https://images.nvidia.com/aem-dam/en-zz/Solutions/data-center/nvidia-ampere-architecture-whitepaper.pdf">https://images.nvidia.com/aem-dam/en-zz/Solutions/data-center/nvidia-ampere-architecture-whitepaper.pdf</a></li><li>Ampere (microarchitecture), <a href="https://en.wikipedia.org/wiki/Ampere_(microarchitecture)">https://en.wikipedia.org/wiki/Ampere_(microarchitecture)</a></li><li><a href="https://www.anandtech.com/show/17327/nvidia-hopper-gpu-architecture-and-h100-accelerator-announced">https://www.anandtech.com/show/17327/nvidia-hopper-gpu-architecture-and-h100-accelerator-announced</a></li><li>NVIDIA H100 Tensor Core GPU Architecture, <a href="https://resources.nvidia.com/en-us-tensor-core">https://resources.nvidia.com/en-us-tensor-core</a></li><li>NVIDIA TESLA V100 GPU ARCHITECTURE, <a href="https://images.nvidia.com/content/volta-architecture/pdf/volta-architecture-whitepaper.pdf">https://images.nvidia.com/content/volta-architecture/pdf/volta-architecture-whitepaper.pdf</a></li><li>Inside the NVIDIA Ampere Architecture. <a href="https://developer.download.nvidia.com/video/gputechconf/gtc/2020/presentations/s21730-inside-the-nvidia-ampere-architecture.pdf">https://developer.download.nvidia.com/video/gputechconf/gtc/2020/presentations/s21730-inside-the-nvidia-ampere-architecture.pdf</a></li><li>Nvidia’s H100: Funny L2, and Tons of Bandwidth, <a href="https://i0.wp.com/chipsandcheese.com/wp-content/uploads/2023/06/h100_latency_vs_a100.png?ssl=1">https://i0.wp.com/chipsandcheese.com/wp-content/uploads/2023/06/h100_latency_vs_a100.png?ssl=1</a></li><li>Introduction to the NVIDIA DGX H100 System, <a href="https://docs.nvidia.com/dgx/dgxh100-user-guide/introduction-to-dgxh100.html">https://docs.nvidia.com/dgx/dgxh100-user-guide/introduction-to-dgxh100.html</a></li><li>Dissecting Tensor Cores via Microbenchmarks: Latency, Throughput and Numeric Behaviors, <a href="https://arxiv.org/pdf/2206.02874.pdf">https://arxiv.org/pdf/2206.02874.pdf</a>, <a href="https://github.com/sunlex0717/DissectingTensorCores">https://github.com/sunlex0717/DissectingTensorCores</a></li><li>CUDA C++ Programming Guide, <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#hardware-implementation">https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#hardware-implementation</a></li><li>Zen — Microarchitectures — AMD, <a href="https://en.wikichip.org/wiki/amd/microarchitectures/zen">https://en.wikichip.org/wiki/amd/microarchitectures/zen</a></li><li>Scaling the ‘Scaling Wall’ to Future Compute Systems, <a href="https://www.eetimes.eu/scaling-the-scaling-wall-to-future-compute-systems/">https://www.eetimes.eu/scaling-the-scaling-wall-to-future-compute-systems/</a></li><li>AMD Envisions Stacked DRAM on top of Compute Chiplets in the Near Future, <a href="https://www.techpowerup.com/305060/amd-envisions-stacked-dram-on-top-of-compute-chiplets-in-the-near-future">https://www.techpowerup.com/305060/amd-envisions-stacked-dram-on-top-of-compute-chiplets-in-the-near-future</a></li><li>High Bandwidth Memory, <a href="https://en.wikipedia.org/wiki/High_Bandwidth_Memory">https://en.wikipedia.org/wiki/High_Bandwidth_Memory</a></li><li>Insights into DDR5 Sub-timings and Latencies, <a href="https://www.anandtech.com/show/16143/insights-into-ddr5-subtimings-and-latencies">https://www.anandtech.com/show/16143/insights-into-ddr5-subtimings-and-latencies</a></li><li>DRAM Bandwidth and Latency Stacks: Visualizing DRAM Bottlenecks, <a href="https://heirman.net/papers/eyerman2022dram.pdf">https://heirman.net/papers/eyerman2022dram.pdf</a></li><li>Memory Bandwidth Per Core and Per Socket for Intel Xeon and AMD EPYC, <a href="https://www.servethehome.com/memory-bandwidth-per-core-and-per-socket-for-intel-xeon-and-amd-epyc/">https://www.servethehome.com/memory-bandwidth-per-core-and-per-socket-for-intel-xeon-and-amd-epyc/</a></li><li>THE FUTURE OF LOW-LATENCY MEMORY ,<a href="https://objective-analysis.com/wp-content/uploads/2022/12/2021-04-18-Objective-Analysis-White-Paper-The-Future-of-Low-Latency-Memory.pdf">https://objective-analysis.com/wp-content/uploads/2022/12/2021-04-18-Objective-Analysis-White-Paper-The-Future-of-Low-Latency-Memory.pdf</a></li><li>Optimization of Collective Communication Operations in MPICH, <a href="https://web.cels.anl.gov/~thakur/papers/ijhpca-coll.pdf">https://web.cels.anl.gov/~thakur/papers/ijhpca-coll.pdf</a></li><li>A Survey of Methods for Collective Communication<br>Optimization and Tuning, <a href="https://arxiv.org/pdf/1611.06334.pdf">https://arxiv.org/pdf/1611.06334.pdf</a></li><li>Horovod, <a href="https://www.uber.com/blog/horovod/">https://www.uber.com/blog/horovod/</a></li><li>Why Tree has better bandwidth performance than Ring on only 2 DGX-A100 ? <a href="https://github.com/NVIDIA/nccl/issues/812">https://github.com/NVIDIA/nccl/issues/812</a></li><li>Performance of MVAPICH2-GDR on DGX A100, <a href="http://mug.mvapich.cse.ohio-state.edu/static/media/mug/presentations/21/mug21_dgx2a100.pdf">http://mug.mvapich.cse.ohio-state.edu/static/media/mug/presentations/21/mug21_dgx2a100.pdf</a></li><li>Characterizing Off-path SmartNIC for Accelerating Distributed Systems, <a href="https://arxiv.org/pdf/2212.07868.pdf">https://arxiv.org/pdf/2212.07868.pdf</a></li><li>Maximizing Network Performance for Storage with NVIDIA Spectrum Ethernet, <a href="https://developer.nvidia.com/blog/maximizing-network-performance-for-storage-with-nvidia-spectrum-ethernet/">https://developer.nvidia.com/blog/maximizing-network-performance-for-storage-with-nvidia-spectrum-ethernet/</a></li></ol><p><strong>Additional References:</strong></p><ol><li>An In-Depth Look at the Transformer Based Models, <a href="https://medium.com/@yulemoon/an-in-depth-look-at-the-transformer-based-models-22e5f5d17b6b">https://medium.com/@yulemoon/an-in-depth-look-at-the-transformer-based-models-22e5f5d17b6b</a></li><li>Matrix Multiplication Background User’s Guide, <a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html">https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html</a></li><li>GPU Performance Background User’s Guide <a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html#understand-perf">https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html#understand-perf</a></li><li><a href="https://gpuopen.com/learn/amd-lab-notes/amd-lab-notes-matrix-cores-readme/">https://gpuopen.com/learn/amd-lab-notes/amd-lab-notes-matrix-cores-readme/</a>, <a href="https://gpuopen.com/learn/amd-lab-notes/amd-lab-notes-matrix-cores-readme/">https://gpuopen.com/learn/amd-lab-notes/amd-lab-notes-matrix-cores-readme/</a></li><li>Hardware Accelerator Integration Tradeoffs for<br>High-Performance Computing: A Case Study of<br>GEMM Acceleration in N-Body Methods, <a href="http://lca.ece.utexas.edu/pubs/Hardware_Accelerator_Integration_Tradeoffs_for_High-Performance_Computing_A_Case_Study_of_GEMM_Acceleration_in_N-Body_Methods.pdf">http://lca.ece.utexas.edu/pubs/Hardware_Accelerator_Integration_Tradeoffs_for_High-Performance_Computing_A_Case_Study_of_GEMM_Acceleration_in_N-Body_Methods.pdf</a></li><li>Anatomy of High-Performance GEMM with Online Fault<br>Tolerance on GPUs, <a href="https://arxiv.org/pdf/2305.01024.pdf">https://arxiv.org/pdf/2305.01024.pdf</a></li><li>Performance Analysis of GEMM Mappings in<br>CPU Architectures</li><li>CUTLASS 3, <a href="https://www.youtube.com/watch?v=PWWOGrLZtZg">https://www.youtube.com/watch?v=PWWOGrLZtZg</a></li><li>Parallel Thread Execution ISA Version 8.1, <a href="https://docs.nvidia.com/cuda/parallel-thread-execution/">https://docs.nvidia.com/cuda/parallel-thread-execution/</a></li><li>CUDA Binary Utilities, <a href="https://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#maxwell-pascal">https://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#maxwell-pascal</a></li><li>Imec Reveals Sub-1nm Transistor Roadmap, 3D-Stacked CMOS 2.0 Plans, <a href="https://www.tomshardware.com/news/imec-reveals-sub-1nm-transistor-roadmap-3d-stacked-cmos-20-plans">https://www.tomshardware.com/news/imec-reveals-sub-1nm-transistor-roadmap-3d-stacked-cmos-20-plans</a></li><li>[DGIST Series] How the Quest for AI Led to Next-Generation Memory &amp; Computing Processors, <a href="https://news.skhynix.com/how-the-quest-for-ai-led-to-next-generation-memory-computing-processors/">https://news.skhynix.com/how-the-quest-for-ai-led-to-next-generation-memory-computing-processors/</a></li><li>Tutorial 6: Transformers and Multi-Head Attention, <a href="https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/tutorial6/Transformers_and_MHAttention.html">https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/tutorial6/Transformers_and_MHAttention.html</a></li><li>In-Memory Processing ISVLSI 2022 Special Session, <a href="https://safari.ethz.ch/safari_public_wp/wp-content/uploads/ISVLSI2022_Introduction_SpecialSession.pdf">https://safari.ethz.ch/safari_public_wp/wp-content/uploads/ISVLSI2022_Introduction_SpecialSession.pdf</a></li><li>A Formal Instruction-Level GPU Model for Scalable Verification, <a href="https://www.cs.princeton.edu/~aartig/papers/iccad18-gpu.pdf">https://www.cs.princeton.edu/~aartig/papers/iccad18-gpu.pdf</a></li><li>Design and Implementation of a PTX Emulation Library, <a href="https://upcommons.upc.edu/bitstream/handle/2099.1/7589/PFC.pdf">https://upcommons.upc.edu/bitstream/handle/2099.1/7589/PFC.pdf</a></li><li>Vortex: Extending the RISC-V ISA for GPGPU and 3D-Graphics Research,<a href="https://ar5iv.labs.arxiv.org/html/2110.10857">https://ar5iv.labs.arxiv.org/html/2110.10857</a></li><li>Demystifying the Characteristics of High Bandwidth Memory<br>for Real-Time Systems, <a href="https://upcommons.upc.edu/bitstream/handle/2117/362010/HBM.pdf?sequence=1">https://upcommons.upc.edu/bitstream/handle/2117/362010/HBM.pdf?sequence=1</a></li><li>DDR4: Double the speed, double the latency?<br>Make sure your system can handle next-generation DRAM, <a href="https://www.chipestimate.com/DDR4-Double-the-speed-double-the-latencyMake-sure-your-system-can-handle-next-generation-DRAM/Cadence/Technical-Article/2011/11/22">https://www.chipestimate.com/DDR4-Double-the-speed-double-the-latencyMake-sure-your-system-can-handle-next-generation-DRAM/Cadence/Technical-Article/2011/11/22</a></li><li>NVIDIA GPU P2P Benchmark bandwidth/throughput and latency, <a href="https://gist.github.com/joshlk/bbb1aca6e70b11d251886baee6423dcb">https://gist.github.com/joshlk/bbb1aca6e70b11d251886baee6423dcb</a></li><li>A Visual Guide to MPI All-to-all, <a href="https://tcpp.cs.gsu.edu/curriculum/?q=system/files/1786_A%20Visual%20Guide%20to%20MPI%20All-to-all.pdf">https://tcpp.cs.gsu.edu/curriculum/?q=system/files/1786_A%20Visual%20Guide%20to%20MPI%20All-to-all.pdf</a></li><li>NCCL: ACCELERATED MULTI-GPU COLLECTIVE COMMUNICATIONS, <a href="https://images.nvidia.com/events/sc15/pdfs/NCCL-Woolley.pdf">https://images.nvidia.com/events/sc15/pdfs/NCCL-Woolley.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c7357b73fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diffusion Models for Generative AI]]></title>
            <link>https://whatdhack.medium.com/diffusion-models-for-generative-ai-194c5f877972?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/194c5f877972</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[latent-diffusion]]></category>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 02:45:43 GMT</pubDate>
            <atom:updated>2023-02-27T02:45:43.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently diffusion based generative networks such as Stable Diffusion, DALL-E2, Imagen, etc have garnered lot of publicity. In this article, I try to cover some of the basics of diffusion models. Fundamentals of diffusion models are steeped in statistics and mathematics. Hence, a Statistics Refresher is included for some of the concepts.</p><p>The article is divided into a number of sections — Begining, Basic Concepts, DULNT and the DDPM codes, Derivations of a few Equations in the DDPM Paper, βt Schedule and Training, State of the Art(ish, ), Statistics Refresher , Glossary, and References. The last sections have more content than needed for understanding diffusion model.</p><p>Lot of the contents in this article , specially the Statistics Refresher section, were derived or liberally lifted from the excellent books and articles mentioned in the References section.</p><p>The equations in the article are written in a number of forms — pseudo-code, Mathcha etc. The pseudo-code equations are easier to write, but quickly becomes hard to understand. Writing Mathcha equation is somewhat laborious, but the end result is more pleasing.</p><h3><strong>Beginning:</strong></h3><p>Generative diffusion models are considered to have started with the following two papers.</p><ol><li>Deep Unsupervised Learning using Non-equilibrium Thermodynamics (DULNT) (March 2015)</li></ol><p>This is the breakthrough paper with a number of original ideas . At a general level, the authors showed that is possible to model images as a combination of simple functions. Roughly analogous to how very short straight lines ( called splines) can approximate a complex curve. This paper is generally regarded as the first that attempted image generation through diffusion process. The authors used a Markov chain to gradually convert one distribution to another. Some of the basic forward and backward diffusion equations ( section 2. Algorithms ) are much more detailed in this paper. This paper also considers both Gaussian and Binomial noise.</p><p>2. Denoising Diffusion Probabilistic Models (DDPM)(June 2020)</p><p>This paper extends the previous paper’s work. Hence we will look at both the papers together in more detail here. Advances in the DDPM paper are : simplification of training. simplification of the forward diffusion by keeping diffusion parameters constant, comparison with auto-regressive decoding, derivation closed form expression that removes the need for Monte Carlo simulation.</p><h3><strong>Basic Concepts:</strong></h3><p>The original notion of the DULNT<strong> </strong>paper<strong> </strong>was to fit a probabilistic model to a dataset. Simple probabilistic models are not capable of capturing the essence of complex structured data. On the other hand, flexible and complex probabilistic models are not tractable (e.g. the normalization constant is not integrable). The authors of the DULNT paper devised a novel way to generate tractable complex probabilistic model. They used ideas from Simulated Annealing, Annealed Importance Sampling (AIS), Statistical Physics ( Jarzynski Equality ), diffusion equations of Fokker-Plank and Langevin Equation.</p><p>They used Markov chain to gradually convert one distribution into another. They do this by adding noise ( Gaussian or Binomial) to the original image in small steps till the resulting image becomes just noise. This step of adding noise is similar to how noise accumulates in Langevin Dynamics. Each step in the diffusion chain has an analytically tractable probability, hence the full chain is also analytically tractable. Kolmogorov forward and backward equations show that for many forward diffusion processes, the reverse diffusion processes can be described using the same functional form.</p><p>The authors formulate a joint probability distribution of all the steps of the diffusion. To evaluate this intractable joint probability distribution, the authors took cues from AIS and evaluate relative probability of forward and reverse trajectories and integrate over forward trajectory.</p><p>The forward process adds small amount of Gaussian Noise to the original image over a number of time steps till the image becomes almost a Gaussian. The reverse process goes in the other direction to arrive at the original image. The goal is to find best possible forward (noise) and reverse functions (de-noise) that maximizes the fit to the original from the corrupted image (almost pure noise).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*cA5FssSwFjU4iIxIsClPrw.png" /><figcaption><strong>Forward diffusion noising ( from Hugging Face annotated-diffision.ipynb)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*MqMOXzTDOYc0g3czWDfpMw.png" /><figcaption><strong>Reverse diffusion denoising ( from DDPM)</strong></figcaption></figure><p>The original image, <strong><em>x</em></strong><em>₀</em>, is a sample from the data probability distribution, <strong><em>q</em></strong><em>(</em><strong><em>x</em></strong><em>₀),</em>here <strong><em>x</em></strong><em>₀ </em>indicates that the distribution is “centered” at <strong><em>x</em></strong><em>₀ . </em>For example<em> </em><strong><em>x</em></strong><em>₀</em>, can be a 3 dimensional tensor of pixel values ( in practice, raw pixel values are transformed into other forms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*2Wt24QJOgQ0IE8tFNWOnkA.png" /><figcaption>Forward and reverse diffusion ( from DDPM)</figcaption></figure><p>This distribution is then gradually converted into to an analytically tractable distribution like Gaussian in <strong><em>T</em></strong> steps. At each step, a conditional probability,<strong> <em>𝑞</em></strong>(<strong>x</strong><em>𝑡</em>|<strong>x</strong><em>𝑡</em>−1) is used to generate a noisier image. If the conditional probability is Gaussian, as commonly is, then the distribution is just characterized by 2 numbers— mean and variance as in the following equation. Where, <em>βt, </em>is a time step dependent scalar constant, and <em>I</em> is the identity tensor of the same shape as <strong><em>x</em></strong><em>₀</em>. <em>βt </em>increases with step <em>t .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*LR0V9XH-xqiqzOgtzXU9og.png" /></figure><p>When t=1 , we have the following equation. <strong><em>q</em></strong><em>(</em><strong><em>x</em></strong><em>₀) ~ </em><strong><em>x</em></strong><em>₀ , </em>or is proportional to<em> </em><strong><em>x</em></strong><em>₀ .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*TKzkfUlLqhsPECKyjis9TA.png" /></figure><p><strong><em>x</em></strong>₁ is a sample from <strong><em>q</em></strong><em>(</em><strong><em>x</em></strong>₁) or <strong><em>q</em></strong><em>(</em><strong><em>x</em></strong>₁|<strong><em>x</em></strong><em>₀</em>) as in the following equation, where ε is a sample from the the 0-mean 1-variance Gaussian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*G9PdXBPZPa7zBtlZHZm2OA.png" /></figure><p>The final corrupted data, <em>p(xT )</em>, after <em>T</em> steps is a Normal/Gaussian distribution with 0 mean and variance 1. Tn the following equation <em>xT</em> represents the image tensor at time step <em>T</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*U8FgxE9QPYwaqHoxypuHFw.png" /></figure><p>The probability of generating the original data through the reverse process is an integration of the joint probability distribution of each reverse step with respect to data at each step.</p><blockquote>p(x0, θ) = ∫p(x0,x1,x2,…xT)dx1dx2…dxT = ∫p(x0:T)dx1:T</blockquote><p>In the above equation, <em>p(x0:T)</em> is the joint probability distribution of all the steps. <em>x1..xT</em> are the image tensor at those steps. also known as latent variables. <em>θ</em> is a set of parameters that describe the distribution. The above integral is intractable, but is made tractable by the Importance Sampling trick of using a ratio of functions.</p><blockquote>p(x0, θ) = ∫q(x1,…xT) ( p(x0,…xT) /q(x1,..xT) dx1dx2…dxT</blockquote><p>Equation (3) of DDPM , shown below, is a derivation from the above — detailed in DULNT and also in DDPM. The expectation, <em>Eq</em>, is the integral with respect to <em>q</em> above. The KL terms appears after application of Jensen’s inequality ( e.g. log-expectation to expectation-log ) and with most integrals evaluating to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*s8U4Ap59DmyN_LEPdUWWbg.png" /><figcaption>Equations 1,2 and 3 of DDPM paper</figcaption></figure><p>Mathematically, the goal then is to maximize the likelihood (or log likelihood or minimize the negative ), <em>L,</em> of <em>p(</em><strong><em>x</em></strong><em>₀) </em>,<em> </em>the prediction or generation<em>, </em>with respect to <em>q(</em><strong><em>x</em></strong><em>₀) , </em>the original.</p><blockquote>L = ∫ln (p(x0)) q(x0) dx0</blockquote><blockquote>p(x(t-1)|xt) = N(x(t-1), μ (θ,xt,t),Σ(θ,xt,t))</blockquote><blockquote>p(x0:T)= p(xT ) Π p(x(t-1)|xt)</blockquote><blockquote>q(xt|x(t-1)) = N(xt, sqrt(1-βt)x(t-1),βtI)</blockquote><blockquote>q(x1:T|x0)= Π q(x(t)|x(t-1))</blockquote><blockquote>q(x(t)|x0)= N (x(t); sqrt(αbar(t))x0, (1-αbar(t))I) — see below for derivation of DDPM Equation 4.</blockquote><p>The DULNT paper applies Jensen’s inequality to arrive at a lower bound , <em>K</em>, where <em>L ≥ K</em> . K is composed of KL divergence terms and entropies . The expressions that are optimized in the 2 papers are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*xTFxrNFF_jxWrURJcJOljQ.png" /><figcaption>Log likelihood and variational lower bound expression in the DULNT paper</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*OVzLXwBsmm_Kd48BWrwKPA.png" /><figcaption>Variational lower bound of negative log likelihood (L) in the DDPM paper</figcaption></figure><p>The DULNT paper ( section 2.2 Reverse Trajectory) mentions that for small <em>β</em>, the reverse of a diffusion process has identical functional form as forward. Hence, Gaussian in forward process implies Gaussian in reverse.</p><p>The DDPM paper keeps the <em>βt’s</em> constant in the forward trajectory. Whereas the DULNT paper learns the <em>βt’</em>s by forward ascent on <em>K</em>.</p><p>Both the DULNT and the DDPM paper optimizes random terms of <em>L</em> through SGD ( see later section on training for a explanation of this ). The DDPM paper, in Section 3, goes through each of the 3 terms above. <em>LT </em>is a constant wrt <em>θ</em>, and <em>L0 </em>is a discrete decoder that constrains the distribution to +-1/255 of the mean, so that mean remains within 1 step of pixel intensity. In a simplified version of <em>L</em>, <em>LSIMPLE</em>, the authors replaced the discrete <em>L0</em> decoder with a Gaussian, and also did away with the time dependent multiplication factor.</p><p>The DULNT paper uses a custom convolution network. The DDPM paper uses a UNet ( PixelCNN++) type of network. The input data used is from images, and the output is also image. The network outputs the mean ( or mean of noise) at every pixel location, hence still retains the tensor shape of image. The UNet model holds the mean of all the reverse direction steps in its architecture. Hence, for the network to distinguish each step it needs to be fed the time step info in some form. A consequence of this is that parameters are shared across time — thus significantly reducing the size of the network and thus compute needs. The DDPM paper embeds time into the model through a sinusoidal positional embedding as used in Transformers.</p><p>The following shows the training and sampling algorithms of the DDPM paper. D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*5FZC2IpPaI3BE2qhoNQHmg.png" /><figcaption>The training and sampling algorithms of the DDPM paper.</figcaption></figure><p>The training algorithm in the DULNT paper looks similar to the Algorithm 1 of the DDPM paper. The DULNT paper handles time dependency with a sequence of time dependent bump functions applied to the output of the convolution network.</p><p>In both papers, the training algorithm at each iteration is run at a random diffusion time step. The sampling is done by running the reverse diffusion through all the time steps one after another.</p><h3><strong>DULNT and DDPM codes :</strong></h3><p>An annotated code of the DDPM paper in PyTorch is available in Hugging Face ( URL in Reference section ). The following shows a summary of the UNet model used for denoising and sampling function. These are the 2 most significant parts of the code from which loss is calculated for convergence with an Adam optimizer.</p><pre>================================================================================<br>Layer (type:depth-idx)                                  Param #<br>================================================================================<br>Unet                                                    --<br>├─Conv2d: 1-1                                           900<br>├─Sequential: 1-2                                       --<br>│    └─SinusoidalPositionEmbeddings: 2-1                --<br>│    └─Linear: 2-2                                      3,248<br>│    └─GELU: 2-3                                        --<br>│    └─Linear: 2-4                                      12,656<br>├─ModuleList: 1-3                                       --<br>│    └─ModuleList: 2-5                                  --<br>│    │    └─ConvNextBlock: 3-1                          26,882<br>│    │    └─ConvNextBlock: 3-2                          33,040<br>│    │    └─Residual: 3-3                               14,476<br>│    │    └─Conv2d: 3-4                                 12,572<br>│    └─ModuleList: 2-6                                  --<br>│    │    └─ConvNextBlock: 3-5                          91,308<br>│    │    └─ConvNextBlock: 3-6                          122,528<br>│    │    └─Residual: 3-7                               28,952<br>│    │    └─Conv2d: 3-8                                 50,232<br>│    └─ModuleList: 2-7                                  --<br>│    │    └─ConvNextBlock: 3-9                          355,096<br>│    │    └─ConvNextBlock: 3-10                         470,848<br>│    │    └─Residual: 3-11                              57,904<br>│    │    └─Identity: 3-12                              --<br>├─ModuleList: 1-4                                       --<br>│    └─ModuleList: 2-8                                  --<br>│    │    └─ConvNextBlock: 3-13                         332,192<br>│    │    └─ConvNextBlock: 3-14                         122,528<br>│    │    └─Residual: 3-15                              28,952<br>│    │    └─ConvTranspose2d: 3-16                       50,232<br>│    └─ModuleList: 2-9                                  --<br>│    │    └─ConvNextBlock: 3-17                         92,400<br>│    │    └─ConvNextBlock: 3-18                         33,040<br>│    │    └─Residual: 3-19                              14,476<br>│    │    └─ConvTranspose2d: 3-20                       12,572<br>├─ConvNextBlock: 1-5                                    --<br>│    └─Sequential: 2-10                                 --<br>│    │    └─GELU: 3-21                                  --<br>│    │    └─Linear: 3-22                                12,656<br>│    └─Conv2d: 2-11                                     5,600<br>│    └─Sequential: 2-12                                 --<br>│    │    └─GroupNorm: 3-23                             224<br>│    │    └─Conv2d: 3-24                                226,016<br>│    │    └─GELU: 3-25                                  --<br>│    │    └─GroupNorm: 3-26                             448<br>│    │    └─Conv2d: 3-27                                225,904<br>│    └─Identity: 2-13                                   --<br>├─Residual: 1-6                                         --<br>│    └─PreNorm: 2-14                                    --<br>│    │    └─Attention: 3-28                             57,456<br>│    │    └─GroupNorm: 3-29                             224<br>├─ConvNextBlock: 1-7                                    --<br>│    └─Sequential: 2-15                                 --<br>│    │    └─GELU: 3-30                                  --<br>│    │    └─Linear: 3-31                                12,656<br>│    └─Conv2d: 2-16                                     5,600<br>│    └─Sequential: 2-17                                 --<br>│    │    └─GroupNorm: 3-32                             224<br>│    │    └─Conv2d: 3-33                                226,016<br>│    │    └─GELU: 3-34                                  --<br>│    │    └─GroupNorm: 3-35                             448<br>│    │    └─Conv2d: 3-36                                225,904<br>│    └─Identity: 2-18                                   --<br>├─Sequential: 1-8                                       --<br>│    └─ConvNextBlock: 2-19                              --<br>│    │    └─Conv2d: 3-37                                1,400<br>│    │    └─Sequential: 3-38                            28,476<br>│    │    └─Identity: 3-39                              --<br>│    └─Conv2d: 2-20                                     29<br>================================================================================<br>Total params: 2,996,315<br>Trainable params: 2,996,315<br>Non-trainable params: 0<br>================================================================================<br><br>The sampling  code implements Algorithm 2 of the paper. <br>@torch.no_grad()<br>def p_sample(model, x, t, t_index):<br>    betas_t = extract(betas, t, x.shape)<br>    sqrt_one_minus_alphas_cumprod_t = extract(<br>        sqrt_one_minus_alphas_cumprod, t, x.shape<br>    )<br>    sqrt_recip_alphas_t = extract(sqrt_recip_alphas, t, x.shape)<br><br>    # Equation 11 in the paper<br>    # Use our model (noise predictor) to predict the mean<br>    model_mean = sqrt_recip_alphas_t * (<br>        x - betas_t * model(x, t) / sqrt_one_minus_alphas_cumprod_t<br>    )<br><br>    if t_index == 0:<br>        return model_mean<br>    else:<br>        posterior_variance_t = extract(posterior_variance, t, x.shape)<br>        noise = torch.randn_like(x)<br>        # Algorithm 2 line 4:<br>        return model_mean + torch.sqrt(posterior_variance_t) * noise<br><br></pre><p>The DULNT paper has an implementation in Theano (URL in the Reference section). Although it was written in 2015, and not in TensorFlow or PyTorch, it is not hard to follow the code. The network is called MLP and the variables names match the names in the paper. The following is a pseudo call stack of the code.</p><pre># in model.py<br>generate_forward_diffusion_sample(self, X_noiseless):<br>  # choose a timestep in [1, self.trajectory_length-1].<br>    <br>cost(self, X_noiseless):<br>  cost_single_t(self, X_noiseless):<br>     X_noisy, t, mu_posterior, sigma_posterior = \<br>            self.generate_forward_diffusion_sample(X_noiseless)<br>     mu, sigma = self.get_mu_sigma(X_noisy, t)<br>     negL_bound = self.get_negL_bound(mu, sigma, mu_posterior, sigma_posterior)<br><br># in train.py<br>    ## initialize the model<br>    dpm = model.DiffusionModel(spatial_width, n_colors, uniform_noise=uniform_noise, **model_args)<br>    dpm.initialize()<br><br>    ## set up optimization<br>    features = T.matrix(&#39;features&#39;, dtype=theano.config.floatX)<br>    cost = dpm.cost(features)<br>    blocks_model = blocks.model.Model(cost)</pre><h3><strong>Derivations of a few equations in the DDPM paper :</strong></h3><p>Equation 3 of DDPM:</p><p>Derivation parallels equations 10–14 in the DULNT paper and also in equations 17–26 in DDPM paper. Both papers leave out some details. DDPM does not explicitly show Jensen’s Inequality step , the DULNT paper shows that in equations 11–12. Neither paper explicitly shows some integrals computing to 1. The KL terms results from application of these tricks.</p><p>Equation 4 of DDPM :</p><blockquote>q(x(t)|x0) = Π q(x(t)|x(t-1))</blockquote><blockquote>x(1)= sqrt(1-β(1)) x(0) + sqrt(β(1))ε(1) , ε(1) is N(0,I) sample</blockquote><blockquote>x(2) = sqrt(1-β(2)) [sqrt(1-β(1)) x(0) + sqrt(β(1))ε(1)]+ sqrt(β</blockquote><blockquote>(2))εt(2)</blockquote><blockquote>x(2) = sqrt((1-β(1)) (1-β(2))) x(0) + sqrt(1-β(2))sqrt(β(1))ε(1)+ sqrt(β(2))ε(2)</blockquote><blockquote>invoking variance law of sum of Gaussian random variable on ε(2) and ε(2) (e.g. equal to sum of variances )</blockquote><blockquote>= sqrt((1-β(1)) (1-β(2))) x(0) + sqrt( (1-β(2)) β(1) +β(2))ε</blockquote><blockquote>= sqrt((1-β(1)) (1-β(2))) x(0) + sqrt(1- (1-β(2) <strong>(1-β(1)</strong>)ε</blockquote><blockquote>… so on till t , gives the following</blockquote><blockquote>q(x(t)|x0)= N (x(t); sqrt(αbar(t))x0, (1-αbar(t))I)</blockquote><blockquote>where αbar(t)= (1-β(1)) (1-β(2)) … (1-β(t)) = Π(1-β(s))</blockquote><p>Equation 8 of DDPM :</p><p>It is a straight forward application of KL divergence of 2 Gaussians. See KL Divergence in the Statistics Refresher below.</p><h3>βt Schedule and Training:</h3><p>There appears to be a number of reasons for choosing <em>sqrt(1 — βt)</em> to scale the mean. First is the closed form expression obtainable above. The second, is to gradually move the mean to 0. Setting to 0 removes any history of the original pixel value. However, diffusion models scales <em>βt </em>between 1e-4 and 2e-2 and diffuses for a fixed number of steps (e.g. 1000). Hence, the mean does not get scaled to 0 , but to a small number ( e.g. 6.4e-3 ). This scaling is also deterministic. The noise term that is added is random. As a result the noised image is random, but still likely a vestige of the original picture. The starting image, called <em>x_start</em> in the code, has values ranging between -1 and 1 for each element. The <em>noise</em>, which is a tensor of same shape as the image, varies between — ∞ and +∞ with a standard deviation of 1 before multiplication by the scaling term ( Equation 4 of DDPM )</p><p>As mentioned above, both the DULNT and the DDPM paper optimizes random terms of <em>L</em> (see the Log likelihood and variational lower bound expression above) through SGD. The rationale for this is that sum of squared values are minimized when each value is minimized. Also makes training simpler and less compute intensive. Another reason for optimizing individual terms of L is that the networks also learns to include individual steps thus preserving the priciples of AIS.</p><h3><strong>State of the Art(ish):</strong></h3><ol><li><strong>High-Resolution Image Synthesis with Latent Diffusion Models (LDM):</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhhtyUJ7Bj34ynjcyE-8EQ.png" /><figcaption><strong>LDM block diagram ( from LDM)</strong></figcaption></figure><p>This paper introduced new features and changes to the base diffusion model. Namely as follows.</p><p>i) An encoder to generate features from image pixels. The diffusion model works in this feature space. This reduces the compute required and hence makes higher resolution image generation practical. The encoder from a VQVAE is used for the features .</p><p>The following figure shows the high level block diagram of a VQGAN (Vector Quantized GAN). It essentially has 4 parts — CNN encoder and decoder, a codebook and a transformer. The CNN encoder produces features of the input image. The codebook further simplifies the features into a fixed number of buckets — hence the name quantization. The transformer learns the relationship between the quantized features. The codebook length is denoted by Z, the encoder step down of the input image is denoted by f, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m-WEIDt7y9lvdrau.png" /><figcaption>VQGAN ( from <a href="https://compvis.github.io/taming-transformers/">Taming Transformers </a>)</figcaption></figure><p>ii) A conditioning mechanisms ( e.g. a text prompt) to generate specific category of images.</p><p><strong>Latent Diffusion code :</strong></p><p>Unconditional Model ( wihout prompt) :</p><p>The high level torchinfo summary of the CelebAHQ model with VQVAE ( f=4, VQ (Z=8192, d=3) ) corresponding to the config celebahq-ldm-vq-4.yam l shows the 3 main parts — VQVAE, the UNet denoiser without any conditioner depicted in the LDM architecture picture shown earlier. The VQVAE does not appear to have the transformer or VQGAN for this specific model.</p><pre>=====================================================================================                                                                                                                      <br>Layer (type:depth-idx)                                       Param #                                                                                                                                       <br>=====================================================================================                                                                                                                      <br>LatentDiffusion                                              --                                      <br>├─DiffusionWrapper: 1-1                                      --                                                                                                                                            <br>│    └─UNetModel: 2-1                                        --                                      <br>│    │    └─Sequential: 3-1                                  1,005,312                                                                                                                                     <br>│    │    └─ModuleList: 3-2                                  73,170,272                              <br>│    │    └─TimestepEmbedSequential: 3-3                     33,736,192                              <br>│    │    └─ModuleList: 3-4                                  166,137,888                                                                                                                                   <br>│    │    └─Sequential: 3-5                                  6,499                                   <br>├─LitEma: 1-2                                                --<br>├─VQModelInterface: 1-3                                      --                                      <br>│    └─Encoder: 2-2                                          --                                      <br>│    │    └─Conv2d: 3-6                                      (3,584)<br>│    │    └─ModuleList: 3-7                                  (11,824,000)<br>│    │    └─Module: 3-8                                      (10,494,976)<br>│    │    └─GroupNorm: 3-9                                   (1,024)<br>│    │    └─Conv2d: 3-10                                     (13,827)<br>│    └─Decoder: 2-3                                          --<br>│    │    └─Conv2d: 3-11                                     (14,336)<br>│    │    └─Module: 3-12                                     (10,494,976)<br>│    │    └─ModuleList: 3-13                                 (22,447,744)<br>│    │    └─GroupNorm: 3-14                                  (256)<br>│    │    └─Conv2d: 3-15                                     (3,459)<br>│    └─Identity: 2-4                                         --<br>│    └─VectorQuantizer2: 2-5                                 --<br>│    │    └─Embedding: 3-16                                  (24,576)<br>│    └─Conv2d: 2-6                                           (12)<br>│    └─Conv2d: 2-7                                           (12)<br>=====================================================================================<br>Total params: 329,378,945<br>Trainable params: 274,056,163<br>Non-trainable params: 55,322,782<br>=====================================================================================<br><br><br>  | Name              | Type             | Params<br>-------------------------------------------------------<br>0 | model             | DiffusionWrapper | 274 M <br>1 | model_ema         | LitEma           | 0     <br>2 | first_stage_model | VQModelInterface | 55.3 M<br>-------------------------------------------------------<br>274 M     Trainable params<br>55.3 M    Non-trainable params<br>329 M     Total params<br>1,317.516 Total estimated model params size (MB)         </pre><p>In the above code, <em>ModuleList 3–2</em> and <em>3–4</em> are the down sampling and up sampling parts of UNet respectively. The following model summary shows one <em>TimestepEmbedSequential</em> layer in mode detail. This particular one contains the first attention block of the UNet decoder.</p><pre>    │    │    └─TimestepEmbedSequential: 4-27               --<br>│    │    │    │    └─ResBlock: 5-53                         --<br>│    │    │    │    │    └─Sequential: 6-176                 --<br>│    │    │    │    │    │    └─GroupNorm32: 7-145           1,344<br>│    │    │    │    │    │    └─SiLU: 7-146                  --<br>│    │    │    │    │    │    └─Conv2d: 7-147                2,709,952<br>│    │    │    │    │    └─Identity: 6-177                   --<br>│    │    │    │    │    └─Identity: 6-178                   --<br>│    │    │    │    │    └─Sequential: 6-179                 --<br>│    │    │    │    │    │    └─SiLU: 7-148                  --<br>│    │    │    │    │    │    └─Linear: 7-149                401,856<br>│    │    │    │    │    └─Sequential: 6-180                 --<br>│    │    │    │    │    │    └─GroupNorm32: 7-150           896<br>│    │    │    │    │    │    └─SiLU: 7-151                  --<br>│    │    │    │    │    │    └─Dropout: 7-152               --<br>│    │    │    │    │    │    └─Conv2d: 7-153                1,806,784<br>│    │    │    │    │    └─Conv2d: 6-181                     301,504<br>│    │    │    │    └─AttentionBlock: 5-54                   --<br>│    │    │    │    │    └─GroupNorm32: 6-182                896<br>│    │    │    │    │    └─Conv1d: 6-183                     603,456<br>│    │    │    │    │    └─QKVAttentionLegacy: 6-184         --<br>│    │    │    │    │    └─Conv1d: 6-185                     201,152<br>│    │    │    │    └─Upsample: 5-55                         --<br>│    │    │    │    │    └─Conv2d: 6-186                     1,806,784</pre><p>Conditional Model ( with prompt) :</p><p>The configs/latent-diffusion/cin-ldm-vq-f8.yaml config in the git repo uses a simple class embedder and has the following parts and parameters.</p><pre>===============================================================================================<br>Layer (type:depth-idx)                                                 Param #<br>===============================================================================================                                                                                                            <br>LatentDiffusion                                                        --<br>├─DiffusionWrapper: 1-1                                                --                            <br>│    └─UNetModel: 2-1                                                  --                                                                                                                                  <br>│    │    └─Sequential: 3-1                                            1,312,768<br>│    │    └─ModuleList: 3-2                                            109,752,320<br>│    │    └─TimestepEmbedSequential: 3-3                               61,901,824                                                                                                                          <br>│    │    └─ModuleList: 3-4                                            222,007,552<br>│    │    └─Sequential: 3-5                                            9,732<br>├─LitEma: 1-2                                                          --                                                                                                                                  <br>├─VQModelInterface: 1-3                                                --<br>│    └─Encoder: 2-2                                                    --<br>│    │    └─Conv2d: 3-6                                                (3,584)                                                                                                                             <br>│    │    └─ModuleList: 3-7                                            (16,879,744)<br>│    │    └─Module: 3-8                                                (10,494,976)<br>│    │    └─GroupNorm: 3-9                                             (1,024)                                                                                                                             <br>│    │    └─Conv2d: 3-10                                               (18,436)<br>│    └─Decoder: 2-3                                                    --<br>│    │    └─Conv2d: 3-11                                               (18,944)                                                                                                                            <br>│    │    └─Module: 3-12                                               (10,494,976)<br>│    │    └─ModuleList: 3-13                                           (29,736,320)<br>│    │    └─GroupNorm: 3-14                                            (256)                                                                                                                               <br>│    │    └─Conv2d: 3-15                                               (3,459)                                                                                                                             <br>│    └─Identity: 2-4                                                   --                                                                                                                                  <br>│    └─VectorQuantizer2: 2-5                                           --                                                                                                                                  <br>│    │    └─Embedding: 3-16                                            (65,536)<br>│    └─Conv2d: 2-6                                                     (20)                                                                                                                                <br>│    └─Conv2d: 2-7                                                     (20)                                                                                                                                <br>├─ClassEmbedder: 1-4                                                   --                            <br>│    └─Embedding: 2-8                                                  512,000<br>===============================================================================================                                                                                                            <br>Total params: 463,213,491                                                                                                                                                                                  <br>Trainable params: 395,496,196                                                                        <br>Non-trainable params: 67,717,295                                                                                                                                                                           <br>===============================================================================================                                                                                                            <br><br>LatentDiffusion: Also optimizing conditioner params!<br><br>  | Name              | Type             | Params<br>-------------------------------------------------------<br>0 | model             | DiffusionWrapper | 394 M <br>1 | model_ema         | LitEma           | 0     <br>2 | first_stage_model | VQModelInterface | 67.7 M<br>3 | cond_stage_model  | ClassEmbedder    | 512 K <br>-------------------------------------------------------<br>395 M     Trainable params<br>67.7 M    Non-trainable params<br>463 M     Total params<br>1,852.854 Total estimated model params size (MB)</pre><p>The input data has 5 more component in addition to image which has a shape of [1, 256, 256, 3] for batch size 1.</p><p>The DDPM part of the code, in <em>ddpm.py</em>, is somewhat similar to the code for the original DDPM paper. The file defines 3 classes — <em>DDPM(pl.LightningModule)</em> , <em>LatentDiffusion(DDPM)</em>, and <em>DiffusionWrapper(pl.LightningModule)</em>. As in the original DDPM paper, in the linear schedule, <em>βt </em>is varied between 1e-4 and 2e-2.</p><p>The input to the PyTorch Lightning fit callback method <em>on_train_batch_start</em> has 5 more component in addition to image as shown in the following trace The image at this point has a shape of [1, 256, 256, 3] for batch size 1. The class_label and human_label are the corresponding ImageNet for that image — 992 and agaric in this case. The image gets encoded to [1, 4, 32, 32] by the method <em>first_stage_model.encode(x)</em> . The condition string gets encoded by the method <em>get_learned_conditioning</em>() to a tensor of shape [1, 1, 512] .</p><pre>latent-diffusion/main.py(749)&lt;module&gt;()<br>-&gt; trainer.fit(model, data)<br>-&gt; self.trainer._call_callback_hooks(&quot;on_train_batch_start&quot;, batch, batch_idx)<br>  lib/python3.10/site-packages/pytorch_lightning/trainer/trainer.py(1597)_call_callback_hooks()<br>-&gt; fn(self, self.lightning_module, *args, **kwargs)<br>&gt; latent-diffusion/main.py(429)on_train_batch_start()<br>-&gt; print(&quot;Batch train  starting&quot;)<br><br>Input data:<br>p batch.keys()<br>dict_keys([&#39;image&#39;, &#39;relpath&#39;, &#39;synsets&#39;, &#39;class_label&#39;, &#39;human_label&#39;, &#39;file_path_&#39;])p batch[&#39;image&#39;].shape, batch[&#39;class_label&#39;], batch[&#39;human_label&#39;]<br>(torch.Size([1, 256, 256, 3]), tensor([992], device=&#39;cuda:0&#39;), [&#39;agaric&#39;])<br><br>#.............................<br><br>latent-diffusion/main.py(749)&lt;module&gt;()<br>-&gt; trainer.fit(model, data)<br>latent-diffusion/ldm/models/diffusion/ddpm.py(864)encode_first_stage()<br>-&gt; return self.first_stage_model.encode(x)<br><br>p type(self)<br>&lt;class &#39;ldm.models.diffusion.ddpm.LatentDiffusion&#39;&gt;<br><br>#..............................................<br><br>ib/python3.10/site-packages/torch/nn/modules/module.py(1110)_call_impl()<br>-&gt; return forward_call(*input, **kwargs)<br>latent-diffusion/ldm/models/diffusion/ddpm.py(876)forward()<br>-&gt; c = self.get_learned_conditioning(c)<br>latent-diffusion/ldm/models/diffusion/ddpm.py(563)get_learned_conditioning()<br>-&gt; return c<br><br>#before the call to get_learned_conditioning<br>p c.keys()                                                                                                                                                                                           <br>dict_keys([&#39;image&#39;, &#39;relpath&#39;, &#39;synsets&#39;, &#39;class_label&#39;, &#39;human_label&#39;, &#39;file_path_&#39;])<br><br>#after the call to get_learned_conditioning<br>p c.shape<br>torch.Size([1, 1, 512])<br> </pre><p>For training of conditional network ( e.g. with text prompt) usually both the VQVAE and text embedder ( e.g. BERT, CLIP, etc.) are pre-trained. However. the ClasssEmbedder as it has only 51K parameters is trained togather with the UNet. UNet gets 2 types of inputs simultaneously — the image and the corresponding textual description in embedded form. The embedded text can be pre-generated also.</p><p>The following stack trace shows the forward call phase of the UNet model. The input to the UNet model has 3 parts — <em>x</em> (the noised image tensor), <em>t</em> ( the diffusion step), <em>context/cc </em>( the condition cross-attention ). The shapes are [1, 4, 32, 32] , [1], and [1, 1, 512] for <em>x</em>,<em>t</em>, and <em>cc</em> respectively.</p><pre>  latent-diffusion/ldm/models/diffusion/ddpm.py(880)forward()<br>-&gt; return self.p_losses(x, c, t, *args, **kwargs)<br>  latent-diffusion/ldm/models/diffusion/ddpm.py(1016)p_losses()<br>-&gt; model_output = self.apply_model(x_noisy, t, cond)<br>  latent-diffusion/ldm/models/diffusion/ddpm.py(988)apply_model()<br>-&gt; x_recon = self.model(x_noisy, t, **cond)<br>  lib/python3.10/site-packages/torch/nn/modules/module.py(1110)_call_impl()<br>-&gt; return forward_call(*input, **kwargs)<br>&gt; latent-diffusion/ldm/models/diffusion/ddpm.py(1411)forward()<br>-&gt; out = self.diffusion_model(x, t, context=cc)<br><br>x.shape, t.shape, cc.shape<br>(torch.Size([1, 4, 32, 32]), torch.Size([1]), torch.Size([1, 1, 512]))<br><br><br>type(self.diffusion_model)<br>&lt;class &#39;ldm.modules.diffusionmodules.openaimodel.UNetModel&#39;&gt;</pre><p>A TensorFlow Keras version is also available in Kaggle ( see reference below ) with succinct descriptions of training on the Laion 6.5+ datasets.</p><p><strong>2. Stable Diffusion (SDM) —</strong></p><p>Stable Diffusion v1 is a specific configuration of the LDM architecture that uses a down sampling-factor 8 auto-encoder with an 860M parameter UNet and a CLIP ViT-L/14 text encoder . The model was pre-trained on 256x256 images and then fine tuned on 512x512 images.</p><h3><strong>Statistics Refresher:</strong></h3><p>The <strong>marginal probability</strong> is the probability of a single event occurring, independent of other events. A <strong>conditional probability</strong>, is the probability that an event occurs given that another specific event has already occurred. This means that the calculation for one variable is dependent on another variable. Marginal probability is the sum all conditional probability of a single event with respect to another event. The name marginal originates from writing down the sum on the margin of a row or column of a table of conditional probability.</p><p><strong>Probability Space </strong><em>(Ω, 𝓕, P) </em>is composed of 3 parts — the sample space of all possible outcomes; a set of events, an event is subset of the sample space; a probability function that assigns a probability to each event.</p><p><strong>σ-algebra</strong> is a family of subsets , <em>F, </em>of Ω with the properties — Ø∈<em>F </em>and Ω∈<em>F ; </em>If <em>A</em>∈<em>F</em>, then (Ω -<em>A) </em>∈<em>F; F </em>is closed under countable unions and intersection, that is if <em>A</em>1, <em>A</em>2, … are events in <em>F</em>, then union of As and intersection of As are both in <em>F</em>.</p><p><strong>Filtration</strong> is a family or sequence of σ-algebras that is increasing, that is, if <em>s ≤ t</em> , then <em>Fs</em> is a subset of <em>Ft</em> .</p><p><strong>Random variable</strong> , <em>X</em>(<em>w</em>), is a single-valued real function that assigns a real number, called the value of <em>X</em>(<em>w</em>), to each sample point <em>w</em>∈Ω , where Ω is the sample space. Thus random variable is a mapping of the sample space onto the real line.</p><p><strong>Random Process or Stochastic Process </strong>is a family of random variables defined over a given probability space and indexed by the time parameter <em>t</em> . A stochastic process is also called a random process. A stochastic process becomes a random variable when time is fixed at some particular value.</p><p>Given probability space (Ω,B,P), random variable is a measurable map</p><blockquote>X:Ω→R</blockquote><p>Stochastic process is a family of random variables, where T is a set or continuous space of time.</p><blockquote>𝑋:Ω×T→R</blockquote><p><strong>Martingale</strong> is a stochastic process where all of its random variables have finite means, and best prediction of its future value is based on its current value.</p><p>A <strong>stochastic process</strong> [ <em>X(t), t ∈ T</em> ] is called a first-order Markov process if for any <em>t0&lt;t1…tn-1&lt;tn</em>, the conditional CDF of <em>X(tn ) </em>depends only on <em>X(tn-1) . </em>This means that, the future state is dependent only on the present and independent of the past. A Markov process can be either a discrete-state Markov process or a continuous-state. A discrete-state Markov process is also called a Markov chain.</p><p><strong>Brownian Motion</strong> of random walk can be thought of as a continuous-time process in which over every infinitely small time interval, the entity moves one “step” in a certain direction. A Brownian Motion is sometimes also called a Wiener Process. Norbert Wiener first laid the mathematical foundation of Brownian Motion. Brownian motion is also a <br>stochastic process that models random continuous motion. The following expresses classical Brownian Motion algebraically. This equation intuitively implies that as time goes on, the particle has higher probability of being farther away as variance increases with time.</p><blockquote><em>W(t)=N(0,</em>σ²t)</blockquote><blockquote><em>B(t) = W(t)/</em>σ , <em>E(B(t))= 0</em>, <em>σ²(B(t)) = 1,</em></blockquote><blockquote><em>=&gt; B(t) =N(0,</em>t)</blockquote><p><strong>Diffusion process</strong>, is a Markov chain that gradually adds noise to the<br>data in the forward direction, opposite direction of sampling, until the signal is destroyed. Diffusion processes are continuous-time, continuous-state processes whose sample paths are everywhere continuous but nowhere differentiable. Diffusion can be considered as the spontaneous “spreading” of particles from region of high concentration to lower concentration. Brownian motion is a diffusion process on the interval (-∞ , +∞) with 0 mean and constant variance. The forward diffusion process provides probability of state in some future time. The backward diffusion provides probability of state in the past.</p><p><strong>The Diffusion Equation</strong>, also called the Fokker-Planck equation, can be derived from random walk. In 1 dimension (<em>x</em>) it is as follows, where <em>D₀</em> is the diffusion coefficient and <em>μ</em> is the drift .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*lqN5BcC10g7VOxa65qHIyg.png" /></figure><p>When <em>D₀</em> is 0 , the Diffusion Equation becomes the Heat Equation.</p><p><strong>Langevin Equation (LE) </strong>describes the evolution of a system that is subjected to random forces. The LE for Brownian motion starts with the basic force equation that has a velocity based drag and a noise term, <em>ma = -λv + N(0,</em><strong><em>σ²). </em></strong>Fokker-Planck equation can be derived from Langevin equation. Hence shows how to define a Gaussian diffusion process which has any target distribution as its equilibrium.</p><p><strong>Stochastic gradient Langevin dynamics </strong>(Welling &amp; Teh 2011) can produce samples from a probability density using only the gradients in a Markov chain of updates. Compared to standard SGD, stochastic gradient Langevin dynamics injects Gaussian noise into the parameter updates to avoid collapses into local minima.</p><p><strong>Stochastic Differential Equation (SDE)</strong> — can be considered an Ordinary Differential Equation (ODE) with a noise term. ODE are deterministic description of a dynamical ( function of time or other variable ) system. SDE can be viewed as description of dynamics of a stochastic process.</p><p><strong>Geometric Brownian Motion (GBM)</strong> — GBM is a continuous-time stochastic process in which the logarithm of a randomly varying parameter ( <em>Y(t)</em>) follows a Brownian motion (<em>B(t)).</em></p><blockquote><em>log(Y(t)) = X(t) = μ*t+ </em>σ<em>*B(t),</em></blockquote><p><strong>Latent variable</strong> is a random variable that is not observable directly.</p><p>In Bayesian statistics, the <strong>conditional</strong> p(z/x) of random variable z on random variable x is written as follows. The joint probability is <em>p(z,x)</em> and <em>p(x)</em> is the <strong>marginal</strong> ( unconditional ) probability of observable variable x, also called evidence. Inference in a Bayesian model amounts to computing the posterior p(z |x)</p><blockquote>p(z/x) = p(z,x)/p(x) , p(x) = ∫p(z,x)dz</blockquote><p><strong>Probability</strong> refers to the occurrence of future events, while a <strong>likelihood</strong> refers to past events with known outcomes.</p><p>A <strong>Likelihood function</strong> of variable X1,X2,.. and parameter θ is defined as follows.</p><blockquote>L(θ) = L(θ|X1,X2, …) = p(X1,X2, …, θ)</blockquote><p>The value of the parameter of a distribution function that maximizes the probability of observing the data is called a maximum-likelihood estimate. Log likelihood is the natural log (<em>ln</em>) of the likelihood function. Often it is easier to work with log ( as probabilities mostly rely on multiplications ), and as <em>ln</em> is monotonic, the maxima of the likelihood and log likelihood coincide. Maximization of log likelihood is same a minimization of negative log likelihood.</p><p><strong>The Kullback-Leibler (KL) divergence</strong> is a non-symmetric (KL from p to q can be different from q to p) measure of the difference between two probability distributions p(x) and q(x) and is defined as follows for discrete distributions. It is closely related to relative entropy, information divergence, and information for discrimination. In case of continuous variables, the summation (<em>Σ</em>) over <em>x</em> is replaced by an integral (<em>∫</em>) . The divergence for 2 Gaussians can be derived by just plugging in the expression and plain algebraic reduction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*JyzCX166nXPY04unWltQRw.png" /><figcaption>Kullback-Leibler (KL) divergence</figcaption></figure><p><strong>Entropy </strong>— the statistical definition of entropy (Gibbs) is as follows. If <em>p’s</em> are equal, then Boltzman’s entropy results. Entropy is a measure of disorder — higher the entropy higher the disorder</p><blockquote>H = -k Σp ln(p)</blockquote><p>Information Entropy or Shannon Entropy is defined as follows.</p><blockquote>H = minimial #bits = — Σp log2(p)</blockquote><p><strong>Variational Inference</strong> — the goal of variational inference is to approximate a conditional density of latent variables of observed variables. A family of densities over the latent variables is used, pameterized by free “variational parameters”. The optimization finds the member of this family (i.e. the setting of the parameters) that is closest in KL divergence to the conditional of interest. The fitted variational density then serves as a proxy for the exact conditional density. MCMC ( Markov Chain Monte Carlo) and variational inference (VI) are different approaches to solving the same problem. MCMC algorithms sample a Markov chain, variational algorithms solve an optimization problem. MCMC algorithms approximate the posterior with samples from the chain, variational algorithms approximate the posterior with the result of the optimization.</p><p><strong>Evidence Lower Bound (ELBO)</strong>, in variational Bayesian methods, often abbreviated ELBO, also sometimes called the variational lower bound or negative variational free energy) is a lower bound on the log-likelihood of observed data. It is derived by employing <strong>Jensen’s Inequality</strong> that exchanges log -expectation for expectation-log as follows. Integral is replaced with expectation (<em>E</em>) in the following.</p><blockquote>p(x) = ∫p(x,z)dz = ∫ p(x/z)p(z) dz = ∫ p(x/z)(p(z)/q(z))q(z)dz</blockquote><blockquote>ln p(x) = ln ∫ p(x/z)(p(z)/q(z))q(z)dz =</blockquote><blockquote>ln Eq ( p(z/x)(p(z)/q(z))) ≥ Eq (ln p(z/x) ) — KL (q(z) || p(z))</blockquote><p><strong>Monte Carlo (MC)</strong> — MC methods are essentially drawing samples from a distribution and then using those sample values to compute task such as integration, expected value, variance etc. The samples are independent and are drawn from same distribution — independent and identically distributed ( IID).</p><p><strong>Monte Chain Monte Carlo (MCMC)</strong> — A Marckov Chain is a sequence of random variables, where the value of variable depends only on the previous variable. It is memory less, as future value is dependent only on the current state.</p><p><strong>Metropolis-Hastings (MH)</strong> — is a way of drawing samples from a target distribution. It handles distributions that are known upto a constant. In other words, the normalizing constant or partition function is not calculable. In that scenario, it is not possible to sample directly from the distribution function. It constructs a Markov Chain such that the probability of choosing the next state is based on the ratio probabilities of the generated propasal state ( not yet the next state) and current state . In the following equation, accept x(t+1) with probability <em>a</em> . Metropolis first came up with the idea which Hastings later extended.</p><blockquote>a = min (p(x(t+1))/p(x(t) ,1)</blockquote><p><strong>Gibbs Sampling</strong> , is a type of Markov Chain sampler. Gibbs sampling starts with joint probability distribution function of many random variables and a random initiial values of thise variables. Then for the next state, each variable is sampled independently according to the joint probability distribution function where all the other variables are held constant. It is a special case of MH that accepts every proposed state unconditionally. it is helpfull in handling high-dimensional ( e.g. many variable) functions. Also, the distribution function has to be known exactly, not upto a constant as in MH.</p><p><strong>Importance Sampling (IS)</strong> — often in many areas science and mathematics, function (e.g. probability density function ) integration needs to performed to normalize the function. This integration can be untractable analytically. Monte Carlo methods (e.g. sampling ) are used to numerically and approximately perform these type of integration. IS is a collection of Monte Carlo methods where a mathematical expectation (<em>E</em>) of a function <em>f(x)</em> with respect to a target distribution (<em>h(y)</em>) is approximated by a weighted average of random draws from another distribution called the proposal distribution (<em>g(y)</em>). These methods become important when the target distribution is not accessible for Monte Carlo (MC) integration (the normalizeing constant is not known, hence samples can not drawn to mimic the distribution), and a proposal distribution ( normalizign constant is known) is used to approximate the target distribution. The proposal distribution has higher values for big values of the function f(x). In other words, it provides more importance to those points that significantly effect expectation. Mathematically it is expressed as follows</p><blockquote>Ef(h) = ∫ h(y)f(y)dy</blockquote><blockquote>∫ h(y)f(y)dy =∫ (h(y)f(y)/g(y))g(y)dy <em>~ 1/N </em>Σi (h(yi)f(yi)/g(yi))</blockquote><p><em>f(y)/g(y)</em> is the importance weight in the weighted sum above. Importance sampling works well if <em>g(y)</em> is a good approximation of <em>h(y)</em>, else the importance weights are not going to be appropriate. Finding a good proposal distribution can be hard.</p><p><strong>Annealed Importance Sampling (AIS) </strong>addresses the shortcoming of IS by applying well known simple probability distribution function (pdf) over a number of steps. In other words anneals one distribution into another. AIS is a type of algorithm called Simulated Annealing. AIS essentially is a marriage of Simulated Annealing and Importance Sampling. Loosely it can viewed as analogous to fitting a curve with very short straight lines. AIS is considered same as Jarzynski Equality used in estimating free energy in statistical physics. The following equation is one example distribution function used at step <em>t</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*KST9yKKNUx1PFoV83V1jbA.png" /><figcaption>Example AIS function</figcaption></figure><p><strong>Score function</strong> ( Stein) is the gradient of the log probability density with respect to data. Maximum likelihood training feasible, likelihood-based models either restricts their model architectures to make normalizing constant tractable, or use computationally expensive approximation of the normalizing constant. A score function does not require a tractable normalizing constant as the following expression shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*NVzJDbgq51eFUKK2R6v8oQ.png" /><figcaption>Score function does not require normalization constant</figcaption></figure><p><strong>Score matching</strong> (Hyvärinen (2005) ) methods reduces the L2 distance between a score function and the score of the true data distribution. Naive score matching suffers from by low contribution from low density region. Multiple noise perturbation score matching applies noise to the original data in number of scales ( e.g. higher and higher variance ) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*sghESlJtkNPu7R3fFU_gdg.png" /><figcaption>Naive score matching (Song)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*Xqigrdcf06yyBd8Fo0zShQ.png" /><figcaption>Multiple noise perturbation score matching (Song)</figcaption></figure><p>Score matching with Langevin dynamics (SMLD) — estimates the score at each noise scale, and then uses Langevin dynamics to sample from a sequence of decreasing noise scales during generation.</p><h3><strong>Glossary:</strong></h3><p><strong>Autoregressive Models </strong>(ARM) — Autoregression models forecast the variable using a linear combination of past values of the variable<em>.</em></p><p><strong>Autoencoder</strong> has 2 part — encoder and decoder. The encoder takes the input and outputs value/values . This is called the bottleneck, the latent space. The decoder takes this output as input, and outputs values that are supposed to be same as the input to the encoder.</p><p><strong>Denoisng Autoencoder</strong> also has 2 stages as in autoencoder. However instead of feeding the data directly into the encode, it is fed a corrupted input data and the decoder is asked to reconstruct the original uncorrupted data.</p><p>Variational Auto-encoder (VAE) are Auto-encoders that outputs probability distribution (e.g. Gaussian mean and variance ) at the bottleneck. The decoder starts with a sample from the encoder output probability distribution and expands it to match the encoder input as in auto-encoders.</p><p>Vector Quantized Variational AutoEncoder ( VQ-VAE) — an autoregressive model. The latent space is quantized or discrete vector instead of continuous.</p><p>VQGAN (Vector Quantized GAN)</p><p><strong>Inception Score (IS)</strong> — IS uses Inception V3 ( without the classifier layer) to generate the conditional label probability distribution, <em>p(y|x) ∈ [0, 1]¹⁰⁰⁰</em> , <em>to</em> define a metric with 2 specific properties. The first property is that the conditional label distribution has low entropy. A low entropy indicates the network is able to distinguish among labels well. The second property is that the marginal probability, <em>p(y ) = </em>∫<em>p(y|x = G(z))dz</em>, should have high entropy. A high entropy indicates that the network can generate many labels with more or less equal probability. The expression , <em>exp(ExKL(p(y|x)||p(y)))</em>, is defined as the IS.</p><p><strong>Frechet Distance (FD)</strong> — is a measure of closeness between 2 distributions. It is also known as Wasserstein-2 distance .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*ky8rzEnRCTrqPSkJvyINDw.png" /><figcaption><strong>Frichet Distance ( from Statistics 18 )</strong></figcaption></figure><p><strong>Fréchet Dnception Distance (FID)</strong></p><p>While in Inception Score, the label probability is used. In FID, the output of coding layer of Inception is used an a Gaussian distribution. Then Frechet Distance is taken between the original and generated image Gaussians. Both original and generated are available during training of the model.</p><h3><strong>References:</strong></h3><p>Statistics :</p><ol><li>Score-based generative modeling through stochastic differential equations, <a href="https://arxiv.org/abs/2011.13456">https://arxiv.org/abs/2011.13456</a></li><li><a href="http://bactra.org/notebooks/stoch-diff-eqs.html">http://bactra.org/notebooks/stoch-diff-eqs.html</a></li><li><a href="https://www.sciencedirect.com/topics/mathematics/standard-brownian-motion">https://www.sciencedirect.com/topics/mathematics/standard-brownian-motion</a></li><li>Oliver Ibe, Markov Processes for Stochastic Modeling, Springer.</li><li>Importance Sampling, <a href="https://dept.stat.lsa.umich.edu/~jasoneg/Stat406/lab7.pdf">https://dept.stat.lsa.umich.edu/~jasoneg/Stat406/lab7.pdf</a>, <a href="http://www2.stat.duke.edu/~st118/Publication/impsamp.pdf">http://www2.stat.duke.edu/~st118/Publication/impsamp.pdf</a>, <a href="https://astrostatistics.psu.edu/su14/lectures/cisewski_is.pdf">https://astrostatistics.psu.edu/su14/lectures/cisewski_is.pdf</a></li><li>Variational Inference: A Review for Statisticians <a href="https://arxiv.org/pdf/1601.00670.pdf">https://arxiv.org/pdf/1601.00670.pdf</a></li><li>Maximum Likelihood Estimates, <a href="https://ocw.mit.edu/courses/18-05-introduction-to-probability-and-statistics-spring-2014/4a8de32565ebdefbb7963b4ebda904b2_MIT18_05S14_Reading10b.pdf">https://ocw.mit.edu/courses/18-05-introduction-to-probability-and-statistics-spring-2014/4a8de32565ebdefbb7963b4ebda904b2_MIT18_05S14_Reading10b.pdf</a></li><li>Kullback-Leibler Divergence <a href="http://hanj.cs.illinois.edu/cs412/bk3/KL-divergence.pdf">http://hanj.cs.illinois.edu/cs412/bk3/KL-divergence.pdf</a></li><li>Importance sampling, <a href="https://www.statlect.com/asymptotic-theory/importance-sampling">https://www.statlect.com/asymptotic-theory/importance-sampling</a></li><li><a href="https://agustinus.kristia.de/techblog/2017/12/23/annealed-importance-sampling/">https://agustinus.kristia.de/techblog/2017/12/23/annealed-importance-sampling/</a></li><li>Annealed Importance Sampling Meets Score Matching, <a href="https://www.deepmind.com/publications/annealed-importance-sampling-meets-score-matching">https://www.deepmind.com/publications/annealed-importance-sampling-meets-score-matching</a></li><li>Annealed Importance Sampling, <a href="https://arxiv.org/pdf/physics/9803008.pdf">https://arxiv.org/pdf/physics/9803008.pdf</a></li><li>MCMC, MH, <a href="https://www.statlect.com/fundamentals-of-statistics/Metropolis-Hastings-algorithm">https://www.statlect.com/fundamentals-of-statistics/Metropolis-Hastings-algorithm</a>, <a href="https://www.statlect.com/fundamentals-of-statistics/Markov-chains">https://www.statlect.com/fundamentals-of-statistics/Markov-chain, s</a><a href="https://www.statlect.com/fundamentals-of-statistics/Markov-Chain-Monte-Carlo">https://www.statlect.com/fundamentals-of-statistics/Markov-Chain-Monte-Carlo</a>, <a href="https://stephens999.github.io/fiveMinuteStats/MH_intro.html">https://stephens999.github.io/fiveMinuteStats/MH_intro.html</a>, <a href="https://www.cs.ubc.ca/~schmidtm/Courses/540-W20/L31.pdf">https://www.cs.ubc.ca/~schmidtm/Courses/540-W20/L31.pdf</a></li><li>Prof Chris Jarzynski — Scaling Down the Laws of Thermodynamics, <a href="https://www.youtube.com/watch?v=TKmC5GzxEgk">https://www.youtube.com/watch?v=TKmC5GzxEgk</a></li><li>A Statistical Definition of Entropy, <a href="https://web.mit.edu/16.unified/www/FALL/thermodynamics/notes/node56.html">https://web.mit.edu/16.unified/www/FALL/thermodynamics/notes/node56.html</a></li><li>STAT 414, <a href="https://online.stat.psu.edu/stat414/">https://online.stat.psu.edu/stat414/</a></li><li>Kullback Leibler divergence between two normal pdfs, <a href="https://www.youtube.com/watch?v=TNJwYuKjqVM">https://www.youtube.com/watch?v=TNJwYuKjqVM</a></li><li>The Frichet distance between two multivariate normal, <a href="https://core.ac.uk/download/pdf/82269844.pdf">https://core.ac.uk/download/pdf/82269844.pdf</a></li></ol><p>Diffusion, Latent Variable, VAE:</p><ol><li>Understanding Diffusion Models: A Unified Perspective, <a href="https://arxiv.org/pdf/2208.11970.pdf">https://arxiv.org/pdf/2208.11970.pdf</a></li><li>How diffusion models work: the math from scratch, <a href="https://theaisummer.com/diffusion-models/">https://theaisummer.com/diffusion-models/</a></li><li>Diffusion Models: A Comprehensive Survey of Methods and Applications, <a href="https://arxiv.org/pdf/2209.00796.pdf">https://arxiv.org/pdf/2209.00796.pdf</a></li><li>The theory behind Latent Variable Models: formulating a Variational Autoencoder, <a href="https://theaisummer.com/latent-variable-models/">https://theaisummer.com/latent-variable-models/</a></li><li>What are Diffusion Models?, <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">https://lilianweng.github.io/posts/2021-07-11-diffusion-models/</a></li><li>Extracting and Composing Robust Features with Denoising Autoencoders, <a href="https://www.cs.toronto.edu/~larocheh/publications/icml-2008-denoising-autoencoders.pdf">https://www.cs.toronto.edu/~larocheh/publications/icml-2008-denoising-autoencoders.pdf</a></li><li>A Connection Between Score Matching and Denoising Autoencoders, <a href="https://www.iro.umontreal.ca/~vincentp/Publications/smdae_techreport.pdf">https://www.iro.umontreal.ca/~vincentp/Publications/smdae_techreport.pdf</a></li><li>Langevin equation, <a href="https://encyclopediaofmath.org/wiki/Langevin_equation">https://encyclopediaofmath.org/wiki/Langevin_equation</a></li><li>The Fokker-Plank equation: equivalence with the Langevin, <a href="https://www2.ph.ed.ac.uk/~dmarendu/ASP/Section15.pdf">https://www2.ph.ed.ac.uk/~dmarendu/ASP/Section15.pdf</a></li></ol><p>Generative AI :</p><ol><li>Tutorial on Denoising Diffusion-based Generative Modeling: Foundations and Applications, <a href="https://www.youtube.com/watch?v=cS6JQpEY9cs">https://www.youtube.com/watch?v=cS6JQpEY9cs</a></li><li>MIT 6.S192 — Lecture 22: Diffusion Probabilistic Models, Jascha Sohl-Dickstein, <a href="https://www.youtube.com/watch?v=XCUlnHP1TNM">https://www.youtube.com/watch?v=XCUlnHP1TNM</a></li><li>MIT 6.S192 — Lecture 20: Generative art using diffusion, Prafulla Dhariwal, <a href="https://www.youtube.com/watch?v=xYJEvihz3OI">https://www.youtube.com/watch?v=xYJEvihz3OI</a></li><li><a href="https://huggingface.co/blog/annotated-diffusion">https://huggingface.co/blog/annotated-diffusion</a>, <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/annotated_diffusion.ipynb">https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/annotated_diffusion.ipynb</a></li><li>Generative Visual Prompt: Unifying Distributional Control of Pre-Trained Generative Models, <a href="https://chenwu98.github.io/PromptGen/">https://chenwu98.github.io/PromptGen/</a></li><li><a href="https://imagen.research.google/">https://imagen.research.google/</a>, <a href="https://imagen.research.google/video/">https://imagen.research.google/video/</a></li><li><a href="https://github.com/Stability-AI/diffusers">https://github.com/Stability-AI/diffusers</a></li><li>CLIP (Contrastive Language-Image Pre-Training), <a href="https://github.com/openai/CLIP">https://github.com/openai/CLIP</a></li><li>Latent Diffusion Models, <a href="https://github.com/compvis/latent-diffusion">https://github.com/compvis/latent-diffusion</a> , <a href="https://github.com/CompVis/stable-diffusion">https://github.com/CompVis/stable-diffusion</a></li><li><a href="https://en.wikipedia.org/wiki/Stable_Diffusion">https://en.wikipedia.org/wiki/Stable_Diffusion</a></li><li><a href="https://github.com/lucidrains/DALLE2-pytorch">https://github.com/lucidrains/DALLE2-pytorch</a>, <a href="https://github.com/lucidrains/x-transformers">https://github.com/lucidrains/x-transformers</a>, <a href="https://github.com/lucidrains/imagen-pytorch">https://github.com/lucidrains/imagen-pytorch</a></li><li>The Annotated Diffusion Model, <a href="https://huggingface.co/blog/annotated-diffusion">https://huggingface.co/blog/annotated-diffusion</a></li><li>Generating Diverse High-Fidelity Images<br>with VQ-VAE-2, <a href="https://arxiv.org/pdf/1906.00446.pdf">https://arxiv.org/pdf/1906.00446.pdf</a></li><li>Understanding VQ-VAE (DALL-E Explained Pt. 1), <a href="https://ml.berkeley.edu/blog/posts/vq-vae/">https://ml.berkeley.edu/blog/posts/vq-vae/</a></li><li>DIFFEDIT: DIFFUSION-BASED SEMANTIC IMAGE EDITING WITH MASK GUIDANCE, <a href="https://arxiv.org/pdf/2210.11427.pdf">https://arxiv.org/pdf/2210.11427.pdf</a></li><li>High-Resolution Image Synthesis with Latent Diffusion Models, <a href="https://arxiv.org/pdf/2112.10752.pdf">https://arxiv.org/pdf/2112.10752.pdf</a></li><li>Diffusion Models Beat GANs on Image Synthesis, <a href="https://arxiv.org/pdf/2105.05233.pdf">https://arxiv.org/pdf/2105.05233.pdf</a></li><li>Denoising Diffusion Probabilistic Models, Jonathan Ho, Ajay Jain, and Pieter Abbeel, In NeurIPS, 2020. <a href="https://arxiv.org/pdf/2006.11239.pdf">https://arxiv.org/pdf/2006.11239.pdf</a>, <a href="https://github.com/hojonathanho/diffusion">https://github.com/hojonathanho/diffusion</a>, <a href="https://hojonathanho.github.io/diffusion/">https://hojonathanho.github.io/diffusion/</a>, <a href="https://medium.com/mlearning-ai/enerating-images-with-ddpms-a-pytorch-implementation-cef5a2ba8cb1">https://medium.com/mlearning-ai/enerating-images-with-ddpms-a-pytorch-implementation-cef5a2ba8cb1</a> , <a href="https://github.com/labmlai/annotated_deep_learning_paper_implementations">https://github.com/labmlai/annotated_deep_learning_paper_implementations</a>,</li><li>Deep Unsupervised Learning using Nonequilibrium Thermodynamics, <a href="https://arxiv.org/pdf/1503.03585.pdf">https://arxiv.org/pdf/1503.03585.pdf</a> ;<a href="https://github.com/Sohl-Dickstein/Diffusion-Probabilistic-Models">https://github.com/Sohl-Dickstein/Diffusion-Probabilistic-Models</a></li><li>Elucidating the Design Space of Diffusion-Based<br>Generative Models, <a href="https://arxiv.org/pdf/2206.00364.pdf">https://arxiv.org/pdf/2206.00364.pdf</a>, <br><a href="https://github.com/NVlabs/edm">https://github.com/NVlabs/edm</a></li><li>symbols, <a href="https://medium.com/@greekalphabet/list-of-greek-alphabet-letters-22bf2f751700">https://medium.com/@greekalphabet/list-of-greek-alphabet-letters-22bf2f751700</a>, <a href="https://www.rapidtables.com/math/symbols/Basic_Math_Symbols.html">https://www.rapidtables.com/math/symbols/Basic_Math_Symbols.html</a></li><li>Online Mathematics Editor, <a href="https://www.mathcha.io/">https://www.mathcha.io/</a></li><li>LION: Latent Point Diffusion Models for 3D Shape Generation, <a href="https://nv-tlabs.github.io/LION/">https://nv-tlabs.github.io/LION/</a></li><li>Prafulla Dhariwal and Alex Nichol. Diffusion models beat<br>GANs on image synthesis</li><li>Yang Song, Jascha Sohl-Dickstein, Diederik P. Kingma, Abhishek Kumar, Stefano Ermon, and Ben Poole. Scorebased generative modeling through stochastic differential equations.</li><li><a href="https://twitter.com/s_scardapane/status/1405182634616049665">https://twitter.com/s_scardapane/status/1405182634616049665</a></li><li>Generative Modeling by Estimating Gradients of the Data Distribution, <a href="https://yang-song.net/blog/2021/score/">https://yang-song.net/blog/2021/score/</a></li><li>DreamBooth: Fine Tuning Text-to-Image Diffusion Models<br>for Subject-Driven Generation, <a href="https://arxiv.org/pdf/2208.12242.pdf">https://arxiv.org/pdf/2208.12242.pdf</a></li><li>Cold Diffusion: Inverting Arbitrary Image Transforms Without Noise, <a href="https://arxiv.org/abs/2208.09392">https://arxiv.org/abs/2208.09392</a>, github.com/arpitbansal297/Cold-Diffusion-Models,</li><li>DiffusionDB is the first large-scale text-to-image prompt dataset., <a href="https://poloclub.github.io/diffusiondb/#dataset-summary">https://poloclub.github.io/diffusiondb/#dataset-summary</a></li><li>Diffusion Models in Vision: A Survey, <a href="https://arxiv.org/pdf/2209.04747.pdf">https://arxiv.org/pdf/2209.04747.pdf</a></li><li>Stable Diffusion colab notebook in HuggingFace , <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_diffusion.ipynb">https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_diffusion.ipynb</a></li><li>Semi-Parametric Neural Image Synthesis, <a href="https://arxiv.org/abs/2204.11824">https://arxiv.org/abs/2204.11824</a></li><li>Inception Score (IS) ; Improved Techniques for Training GANs, <a href="https://arxiv.org/pdf/1606.03498.pdf">https://arxiv.org/pdf/1606.03498.pdf</a> .</li><li>FID ; GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium, <a href="https://arxiv.org/pdf/1706.08500.pdf">https://arxiv.org/pdf/1706.08500.pdf</a></li><li>Taming Transformers for High-Resolution Image Synthesis, <a href="https://github.com/CompVis/taming-transformers">https://github.com/CompVis/taming-transformers</a></li><li>Train Latent Diffusion in Keras from Scratch, <a href="https://www.kaggle.com/code/apapiu/train-latent-diffusion-in-keras-from-scratch/notebook">https://www.kaggle.com/code/apapiu/train-latent-diffusion-in-keras-from-scratch/notebook</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=194c5f877972" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TensorFlow — Graph, GraphDef, Grappler, XLA, MLIR, LLVM, etc]]></title>
            <link>https://whatdhack.medium.com/tensorflow-graph-graphdef-grappler-xla-mlir-llvm-etc-615191e96ebc?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/615191e96ebc</guid>
            <category><![CDATA[llvm]]></category>
            <category><![CDATA[computation-graph]]></category>
            <category><![CDATA[xla]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[nvcc]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 20:33:55 GMT</pubDate>
            <atom:updated>2022-07-23T20:33:55.369Z</atom:updated>
            <content:encoded><![CDATA[<h3>TensorFlow — Graph, GraphDef, Grappler, XLA, MLIR, LLVM, etc</h3><p>TensorFlow is a large and evolving code base with mix of mostly C++ and Python code. It has grown immensely since its first public appearance in 2015. One of its fundamental parts is the processing and optimization of computation graph. This article is an attempts to understand some aspects of TensorFlow’s graph processing and optimizations. The article is not expected to be complete, comprehensive and even fully coherent by any imagination. A lot of the texts here are directly and liberally copied from comments in code in TensorFlow github repo.</p><p>A list of glossary provides introduction to the many terms and acronyms used in the article , TensorFlow code base and other texts. Some of these are broad subjects by themselves.</p><p>The model code used for this publication is one of the TensorFlow XLA examples [1] — the source is also in the Appendix section. Although XLA did not accelerate this particular code, it is small enough to allow probing, as verbose logging from a complex model can be so voluminous so as to make it intractable. Several different techniques were used in addition to reading the source code — very verbose logging, profiling, graph dumping, gdb stack tracing, etc. Details of how these were done are provided in the appendix. Mostly TensorFlow version 2.9.1 was used for this article.</p><p>This article’s focus is Grappler and XLA .However, some peripheral areas get touched upon also for better understanding.</p><h3>Grappler (non-XLA) Path :</h3><p>Internally the computation graph is held in a structure called Graph ( see the Glossary for more details). GraphDef is a serialized form of the computation graph that can be written to a file.</p><p>Grappler is the main graph optimizer in TensorFlow and transforms the computation graph to run better and faster. It runs several types of optimizations on the graph [2]. It divides the optimizations into 4 groups ( <em>OptimizationPassRegistry::RunGrouping</em> ) — <strong>PRE_PLACEMENT, POST_PLACEMENT, POST_REWRITE_FOR_EXEC, </strong>and<strong> POST_PARTITIONING. </strong>Each group runs a number of optimization called phases. A phase may contain a number of pass. See Appendix 5 for the complete list.</p><p>Grappler phases are initiated from <em>ProcessFunctionLibraryRuntime::InstantiateMultiDevice </em>in <em>process_function_library_runtime.cc .</em>In non-XLA execution, the example code runs each phase 7 times.</p><p>The pass <em>generic_layout_optimzier </em>converts from NHWC layout to NCWH for running some kernels optimally.</p><p>Even when XLA jit is not used, passes like <em>MarkForCompilation</em> are still used. This pass marks nodes of the graph as clusterable for XLA.</p><p>Non-XLA execution has more Grappler calls than in XLA executions. Primarily, <em>analytical_cost_estimator.cc </em>, <em>op_level_cost_estimator.cc</em> , <em>graph_memory.cc</em> , and <em>vitual_scheduler.cc</em> . These appear to be called outside of the groups/phases/passes.</p><p>The <em>AnalyticalCostEstimator</em> estimates the cost of running a Grappler item based on the theoretical performance of the hardware that will run the model. This internally uses static shape inference. An option for aggressive shape inference is provided to minimize unknown shapes, and this is only applicable with static shape inference.</p><p>The <em>op_level_cost_estimator</em> makes cost estimate based on the given operations count and the given total IO size in bytes.</p><p>In the execution of the example code, the first iteration used more kernels than succeeding iterations. The additional kernels are <em>Conv2D</em>, <em>Conv2DBackpropFiler</em>, <em>Conv2DBackpropInput</em>, and <em>Fill</em>. For example, in the forward pass of the first iteration, during the second convolution ( <em>conv2d_1</em>), 5 different kernels were used. Whereas in the succeeding iterations, only the one with shortest time is used The convolution kernels tried and chosen are shown below.</p><pre>iter0 conv2d_1:</pre><pre>maxwell_scudnn_winograd_128x128_ldg1_ldg4_relu_tile228n_nt_v1, <br>maxwell_scudnn_winograd_128x128_ldg1_ldg4_relu_tile418n_nt_v1, <br>maxwell_scudnn_winograd_128x128_ldg1_ldg4_relu_tile244t_nt_v1, <br>maxwell_scudnn_winograd_128x128_ldg1_ldg4_relu_tile424n_nt_v1, <br>maxwell_scudnn_winograd_128x128_ldg1_ldg4_mobile_relu_tile148t_nt_v0</pre><pre>iter1+ conv2d_1:</pre><pre>maxwell_scudnn_winograd_128x128_ldg1_ldg4_mobile_relu_tile148t_nt_v0</pre><p>The first iteration includes tuning to find the fastest algorithm. It is controlled by a variable called <em>TF_CUDNN_USE_AUTOTUNE</em> in <em>tensorflow/core/util/use_cudnn.cc</em> . Shown in the following code-snippet is one such call stack.</p><pre>tensorflow/core/kernels/conv_ops.cc Conv2DOp.Compute() <a href="https://github.com/tensorflow/tensorflow/blob/v2.9.1/tensorflow/core/kernels/conv_ops.c">tensorflow/core/kernels/conv_ops.c</a>c LaunchConv2DOp()<br>tensorflow/core/kernels/conv_ops_gpu.cc AutotuneUnfusedConv()<br>tensorflow/core/kernels/gpu_utils.cc BestCudnnConvAlgorithm()</pre><p>With VLOG ≥2, the fastest kernel for an op is printed to the log.</p><pre>tensorflow/core/kernels/gpu_utils.cc:296] fastest algorithm: 580.864us with algo ConvFwd_eng12_k5=1_k6=0_k7=1_k10=1, workspace bytes 102528</pre><p>When profiling is enabled (<em>cupti_tracer.cc:384 </em>), the kernel can also be viewed in a timeline trace — see figure below. However the names in these two domains are not same. For example, the name <em>ConvFwd_eng12_k5=1_k6=0_k7=1_k10=1</em> in <em>gpu_uitls.cc</em> and <em>cuda/cuda_dnn.cc</em> corresponds to <em>maxwell_scudnn_winograd_128x128_ldg1_ldg4_mobile_relu_tile148t_nt_v0</em> in <em>cupti_tracer.cc</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*5_G7wXFvbAvqEQUGlbeVgg.jpeg" /><figcaption>Fig 1: Autotunning to select best convolution kernel iter0 ( top) and using the fastest in iter1 (bottom)</figcaption></figure><p>The following code snippet shows the call stack trace in <em>cupti_tracer.cc</em> .</p><pre>#0  tensorflow::profiler::(anonymous namespace)::AddKernelEventUponApiExit () at tensorflow/core/profiler/internal/gpu/cupti_tracer.cc:384<br>#1  tensorflow::profiler::CuptiDriverApiHook::AddDriverApiCallbackEvent () at tensorflow/core/profiler/internal/gpu/cupti_tracer.cc:1537<br>#2  tensorflow::profiler::(anonymous namespace)::CuptiDriverApiHookWithActivityApi::OnDriverApiExit () at tensorflow/core/profiler/internal/gpu/cupti_tracer.cc:869<br>#3  tensorflow::profiler::CuptiTracer::HandleCallback () at tensorflow/core/profiler/internal/gpu/cupti_tracer.cc:1889<br>#4  tensorflow::profiler::(anonymous namespace)::ApiCallback () at tensorflow/core/profiler/internal/gpu/cupti_tracer.cc:335<br>#5  libcupti.so.11.4<br>#6  libcupti.so.11.4<br>#7  libcupti.so.11.4<br>#8  libcuda.so.1<br>#9  libcudnn_cnn_infer.so.8<br>#10 libcudnn_cnn_infer.so.8<br>#11 cask_cudnn::WinogradShader::run() libcudnn_cnn_infer.so.8<br>#12 cudnn::cnn::infer::WinogradInferSubEngine&lt;&gt;::execute_internal_impl() () from libcudnn_cnn_infer.so.8<br>#13 cudnn::cnn::EngineInterface::execute()() from libcudnn_cnn_infer.so.8<br>#14 cudnn::cnn::EngineContainer () from libcudnn_cnn_infer.so.8<br>#15 cudnn::cnn::EngineInterface::execute()() from libcudnn_cnn_infer.so.8<br>#16 cudnn::cnn::AutoTransformationExecutor::execute_pipeline()  libcudnn_cnn_infer.so.8<br>#17 cudnn::cnn::BatchPartitionExecutor::operator()() libcudnn_cnn_infer.so.8<br>#18 cudnn::cnn::GeneralizedConvolutionEngine&lt;&gt;::execute_internal_impl() () from libcudnn_cnn_infer.so.8<br>#19 cudnn::cnn::EngineInterface::execute(cudnn::backend::VariantPack const&amp;, CUstream_st*) () libcudnn_cnn_infer.so.8<br>#20 cudnn::backend::execute() () libcudnn_cnn_infer.so.8<br>#21 cudnnBackendExecute () libcudnn_cnn_infer.so.8<br>#22 cudnnBackendExecute () at ./tensorflow/stream_executor/cuda/cudnn_8_0.inc:1398<br>#23 stream_executor::gpu::CudnnExecutionPlanRunner&lt;&gt;::operator()() at tensorflow/stream_executor/cuda/cuda_dnn.cc:4367<br>.<br>.<br>.<br>#30 tensorflow::ExecutorState&lt;&gt;::ProcessSync () tensorflow/core/common_runtime/executor.cc:584<br>#31 tensorflow::ExecutorState&lt;&gt;::Process () at tensorflow/core/common_runtime/executor.cc:830<br>#32 tensorflow::ExecutorState&lt;&gt;::&lt;lambda()&gt;::operator()(void) const () at tensorflow/core/common_runtime/executor.cc:1197<br>#33 tensorflow::ExecutorState&lt;&gt;::&lt;lambda()&gt;::operator()(void) () at tensorflow/core/common_runtime/executor.cc:468</pre><p>TensorFlow guards memory with <em>redzone_checker</em>. It is an allocator that allocates a bit of extra memory around the beginning/end of every allocation and checks that this memory is unmodified.</p><p>A <em>ptx</em> cache is also maintained , <em>CompileGpuAsmOrGetCached</em>. Only <em>redzone_checker</em> appears to have triggered access to the cache.</p><p><em>RunAsync()</em> executes the graph computation (<em>executor.cc, executor.h</em>). It eventually gets called from <em>GraphRunner::Run(raph* graph ,….)</em> ( <em>graph_runner.cc </em>) .</p><p>From the <em>tf2xla</em> directory, <em>xla_op_registry.cc</em> and <em>const_analysis.cc</em> are used in the Grappler only flow. <em>const_analysis.cc</em> is backwards dataflow analysis that finds nodes in a graph that must be compile-time constants to be able to lower the graph to XLA.</p><p><em>cudaLaunchKernel</em> ( from <em>libcudart.so</em> , <em>tensorflow/stream_executor/cuda/cuda_runtime_XX</em> ) is the API used for launching kernels in GPU. Which is eventually called from <em>cudnnBackendExecute</em> in <em>tensorflow/stream_executor/cuda/cuda_dnn.cc</em> .</p><h3>XLA (+Grappler) Path:</h3><p>There are number of debug flags that can be set to see what XLA is doing [3] . Nvidia also provides some additional info on XLA [4]. A high level roadmap of XLA migration to MLIR in TensorFlow is provided in [5]. A few papers describe features and limitations of XLA at a high level [6,7 ]. XLA focuses on the memory bound ops and uses library kernels ( <em>cudnn</em>, <em>cublas</em>, etc.) for compute intensive ops such as convolutions and gemms.</p><p><strong>XLA path files :</strong></p><p>XLA execution runs more codes from <em>jit</em>, <em>tf2xla</em> and <em>xla</em> directories in <em>tensorflow/compiler </em>than the Grappler-only path<em>. </em>A number of flies in the <em>tf2xla</em> and <em>jit</em> directories are also used in the Grappler-only path. It should be no surprise that 88 additional files are used from the <em>xla</em> directory in the XLA path. The file names, at a high level, hints at the transforms and optimizations applied to the ops and the graph.</p><p>Common in both XLA and Grappler paths.</p><pre>tensorflow/compiler/jit/build_xla_ops_pass.cc<br>tensorflow/compiler/jit/compilability_check_util.cc<br>tensorflow/compiler/jit/deadness_analysis.cc<br>tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc<br>tensorflow/compiler/jit/encapsulate_xla_computations_pass.cc<br>tensorflow/compiler/jit/introduce_floating_point_jitter_pass.cc<br>tensorflow/compiler/jit/mark_for_compilation_pass.cc<br>tensorflow/compiler/jit/resource_operation_safety_analysis.cc<br>tensorflow/compiler/jit/xla_activity_logging_listener.cc<br>tensorflow/compiler/jit/xla_cluster_util.cc<br>tensorflow/compiler/jit/xla_cpu_device.cc<br>tensorflow/compiler/jit/xla_gpu_device.cc</pre><pre>tensorflow/compiler/tf2xla/const_analysis.cc<br>tensorflow/compiler/tf2xla/xla_op_registry.cc</pre><pre>tensorflow/compiler/xla/parse_flags_from_env.cc</pre><pre>tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc</pre><pre><strong>Code: Files used in both XLA and Grappler paths</strong></pre><p>Additional files used in XLA path.</p><pre>tensorflow/compiler/jit/clone_constants_for_better_clustering.cc<br>tensorflow/compiler/jit/kernels/xla_ops.cc<br>tensorflow/compiler/jit/xla_compilation_cache.cc<br>tensorflow/compiler/jit/xla_launch_util.cc</pre><pre>tensorflow/compiler/tf2xla/graph_compiler.cc<br>tensorflow/compiler/tf2xla/kernels/reduction_ops_common.cc<br>tensorflow/compiler/tf2xla/kernels/reshape_op.cc<br>tensorflow/compiler/tf2xla/xla_compilation_device.cc<br>tensorflow/compiler/tf2xla/xla_compiler.cc<br>tensorflow/compiler/tf2xla/xla_context.cc</pre><pre>tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc<br>tensorflow/compiler/mlir/tensorflow/translate/import_model.cc<br>tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.cc<br>tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc<br>tensorflow/compiler/mlir/xla/transforms/xla_legalize_tf.cc</pre><pre>tensorflow/compiler/xla/literal_comparison.cc<br>tensorflow/compiler/xla/parse_flags_from_env.cc<br>tensorflow/compiler/xla/service/all_gather_combiner.cc<br>tensorflow/compiler/xla/service/all_reduce_combiner.cc<br>tensorflow/compiler/xla/service/batchnorm_expander.cc<br>tensorflow/compiler/xla/service/bfloat16_normalization.cc<br>tensorflow/compiler/xla/service/buffer_assignment.cc<br>tensorflow/compiler/xla/service/call_graph.cc<br>tensorflow/compiler/xla/service/call_inliner.cc<br>tensorflow/compiler/xla/service/conditional_canonicalizer.cc<br>tensorflow/compiler/xla/service/conditional_simplifier.cc<br>tensorflow/compiler/xla/service/copy_insertion.cc<br>tensorflow/compiler/xla/service/dfs_hlo_visitor.cc<br>tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h<br>tensorflow/compiler/xla/service/dot_merger.cc<br>tensorflow/compiler/xla/service/dump.cc<br>tensorflow/compiler/xla/service/dynamic_dimension_inference.cc<br>tensorflow/compiler/xla/service/dynamic_dimension_simplifier.cc<br>tensorflow/compiler/xla/service/dynamic_padder.cc<br>tensorflow/compiler/xla/service/executable.cc<br>tensorflow/compiler/xla/service/flatten_call_graph.cc<br>tensorflow/compiler/xla/service/generic_transfer_manager.cc<br>tensorflow/compiler/xla/service/gpu/buffer_comparator.cc<br>tensorflow/compiler/xla/service/gpu/cudnn_fused_conv_rewriter.cc<br>tensorflow/compiler/xla/service/gpu/fusion_merger.cc<br>tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.cc<br>tensorflow/compiler/xla/service/gpu/gemm_thunk.cc<br>tensorflow/compiler/xla/service/gpu/gpu_compiler.cc<br>tensorflow/compiler/xla/service/gpu/gpu_conv_algorithm_picker.cc<br>tensorflow/compiler/xla/service/gpu/gpu_conv_rewriter.cc<br>tensorflow/compiler/xla/service/gpu/gpu_conv_runner.cc<br>tensorflow/compiler/xla/service/gpu/gpu_executable.cc<br>tensorflow/compiler/xla/service/gpu/hlo_to_ir_bindings.cc<br>tensorflow/compiler/xla/service/gpu/horizontal_input_fusion.cc<br>tensorflow/compiler/xla/service/gpu/horizontal_loop_fusion.cc<br>tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.cc<br>tensorflow/compiler/xla/service/gpu/kernel_thunk.cc<br>tensorflow/compiler/xla/service/gpu/launch_dimensions.cc<br>tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.cc<br>tensorflow/compiler/xla/service/gpu/multi_output_fusion.cc<br>tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc<br>tensorflow/compiler/xla/service/gpu/nvptx_helper.cc<br>tensorflow/compiler/xla/service/gpu/parallel_loop_emitter.cc<br>tensorflow/compiler/xla/service/gpu/reduction_dimension_grouper.cc<br>tensorflow/compiler/xla/service/gpu/reduction_layout_normalizer.cc<br>tensorflow/compiler/xla/service/gpu/reduction_splitter.cc<br>tensorflow/compiler/xla/service/gpu/stream_assignment.cc<br>tensorflow/compiler/xla/service/gpu/tree_reduction_rewriter.cc<br>tensorflow/compiler/xla/service/heap_simulator.cc<br>tensorflow/compiler/xla/service/hlo_alias_analysis.cc<br>tensorflow/compiler/xla/service/hlo_computation.cc<br>tensorflow/compiler/xla/service/hlo_computation.h<br>tensorflow/compiler/xla/service/hlo_constant_folding.cc<br>tensorflow/compiler/xla/service/hlo_cse.cc<br>tensorflow/compiler/xla/service/hlo_dataflow_analysis.cc<br>tensorflow/compiler/xla/service/hlo_dce.cc<br>tensorflow/compiler/xla/service/hlo_evaluator.cc<br>tensorflow/compiler/xla/service/hlo_graph_dumper.cc<br>tensorflow/compiler/xla/service/hlo_instruction.cc<br>tensorflow/compiler/xla/service/hlo_instructions.cc<br>tensorflow/compiler/xla/service/hlo_instructions.h<br>tensorflow/compiler/xla/service/hlo_memory_scheduler.cc<br>tensorflow/compiler/xla/service/hlo_module.cc<br>tensorflow/compiler/xla/service/hlo_parser.cc<br>tensorflow/compiler/xla/service/hlo_pass_fix.h<br>tensorflow/compiler/xla/service/hlo_pass_pipeline.cc<br>tensorflow/compiler/xla/service/hlo_phi_graph.cc<br>tensorflow/compiler/xla/service/hlo_proto_util.cc<br>tensorflow/compiler/xla/service/hlo_schedule.cc<br>tensorflow/compiler/xla/service/hlo_verifier.cc<br>tensorflow/compiler/xla/service/instruction_fusion.cc<br>tensorflow/compiler/xla/service/layout_assignment.cc<br>tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.cc<br>tensorflow/compiler/xla/service/local_service.cc<br>tensorflow/compiler/xla/service/platform_util.cc<br>tensorflow/compiler/xla/service/reduce_scatter_combiner.cc<br>tensorflow/compiler/xla/service/reshape_mover.cc<br>tensorflow/compiler/xla/service/service.cc<br>tensorflow/compiler/xla/service/shape_inference.cc<br>tensorflow/compiler/xla/service/slow_operation_alarm.cc<br>tensorflow/compiler/xla/service/sort_simplifier.cc<br>tensorflow/compiler/xla/service/stream_pool.cc<br>tensorflow/compiler/xla/service/tuple_points_to_analysis.cc<br>tensorflow/compiler/xla/service/while_loop_constant_sinking.cc<br>tensorflow/compiler/xla/service/while_loop_simplifier.cc<br>tensorflow/compiler/xla/shape.cc<br>tensorflow/compiler/xla/shape_util.cc<br>tensorflow/compiler/xla/util.cc</pre><pre><strong>Code: Additional files used in XLA-pat</strong>h</pre><p><strong>XLA Ops:</strong></p><p><em>XlaLaunch</em>, <em>_XlaCompile</em>, <em>XlaRun</em> , <em>_XlaMerge</em>, and <em>XlaClusterOutput</em> are the ops that XLA rewrites a Grappler graph with ( <em>tensorflow/compiler/jit/ops/xla_ops.cc</em>).</p><p>The <em>encapsulate_xla_computations_pass/EncapsulateXlaComputationsPass</em> rewrites computations generated by <em>xla.compile()</em> Python code into <em>XlaLaunch</em> nodes. <em>xla.compile()</em> does two things — marks operators that make up an XLA computation with a unique id (e.g. <em>_xla_compile_id</em>=<em>XYZ</em>), and add <em>XlaClusterOutput</em> nodes to represent outputs of the computation.</p><p><em>XlaLaunch ( XlaLocalLaunchOp</em>) is used to replace a region of the TensorFlow graph that will be compiled and executed using XLA. The <em>XlaLocalLaunchOp</em> is responsible for handling interactions with the TensorFlow executor. Once all inputs are present, and their shapes are known, the op can use a ‘<em>XlaCompilationCache</em>’ to compile and execute code which is specific to the shapes of input Tensors.</p><p><em>_XlaCompile</em> compiles a TensorFlow function into an XLA LocalExecutable and returns a key that <em>_XlaRun</em> can use to look up the LocalExecutable and execute it. <em>XlaCompiler</em> ( <em>tensorflow/compiler/tf2xla/xla_compiler.h</em> ) is typically invoked from an <em>XlaLaunch</em> operator once the shapes of all input parameters to the computation are known, as symbolic execution requires known shapes for all operations. Eventually the nvtx compiler (e.g. nvcc) is invoked here to compile llvm into machine code ( <em>tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc</em> )</p><p><em>XlaCompileOnDemandOp ( tensorflow/compiler/jit/xla_compile_on_demand_op.h</em> ) is an <em>OpKernel</em> when its Compute method is called, generates <em>xla::Computation</em> and runs it asynchronously. Unlike <em>XlaLaunch,</em> it does not rely on any rewrites of the GraphDef — it runs a vanilla TensorFlow op as long as the bridge supports it.</p><p>The <em>XlaCompiler</em> class is responsible for compilation of a self-contained subgraph of a TensorFlow computation using XLA linear algebra runtime. It does a symbolic execution of the graph starting from specific input shapes, using a JIT device to convert operators into XLA computations. It is typically invoked from an `XlaLaunch` operator once the shapes of all input parameters to the computation are known. This is because the symbolic execution requires known shapes for all operations.</p><p>The <em>XlaCompilationCache</em> class caches the results of the XlaCompiler class, which converts a Tensorflow graph into a compiled XLA compilation. Since XLA computations must have static shapes, the cache generates a new XLA computation for each new set of input shapes.</p><p><em>_XlaMerge</em> merges the outputs from the <em>PartitionedCall</em> node and the <em>_XlaRun</em> node. Unlike the TensorFlow Merge op, which requires inputs of some types to be placed on the host, the <em>_XlaMerge</em> op can merge inputs of all types when placed on the device. This prevents the need for copy operations, in particular when an XLA cluster has int32 outputs. The <em>_XlaMerge</em> up does not have a value_index output that identifies the chosen input.</p><p><em>GraphCompiler</em> ( <em>tensorflow/compiler/tf2xla/graph_compiler.h/cc</em> ) compiles the graph in topological order. It also resolves the nondeterminism in the graph by enforcing a total order on all inputs to a node. This abstraction helps in creating the same XLA computation given two structurally equivalent TensorFlow graphs. If a function call is visited during the graph traversal, it is then compiled through the <em>xla_context</em> into a computation and a `Call` operation is inserted to call into that computation. It is called from <em>XlaCompiler </em>class<em>.</em></p><p><strong>XLA Flow:</strong></p><p>TensorFlow computation graph starts to get processed for XLA in <em>MarkForCompilationPassImpl::Run()</em>. It runs <em>RunEdgeContractionLoop()</em>, <em>DeclusterNodes()</em>, <em>CreateClusters()</em>, and <em>DumpDebugInfo() </em>.</p><p><em>RunEdgeContractionLoop() </em>method<em> c</em>ontracts as many edges as possible to create XLA clusters. After this finishes clustering , decisions made are stored in name `<em>clusters_X</em>`, where X is an integer.</p><p>Autoclustering sometimes be overeager. For example, clustering large constants (or large broadcasts of constants) can increase the live range of those constants, and increase overall memory usage. <em>DeclusterNodes()</em> removes “obviously bad” cases like these.</p><p><em>MarkForCompilationPassImpl::CreateClusters ()</em> , marks clusters for compilation that are placed on a device that requires compilation (an <em>XlaDevice</em>), are explicitly marked for compilation (<em>_XlaCompile=true</em>), or have more than <em>debug_options_.xla_min_cluster_size</em> elements (applicable only if compilation is enabled, otherwise there will be no such candidates). Marks nodes that are to be compiled with attribute <em>kXlaClusterAttr</em>. Nodes with the same cluster ID will be compiled together. Marks a subset of nodes in the graph which are to be clustered with an attribute <em>_XlaCluster=&lt;cluster id&gt;</em> so they are picked up by the <em>EncapsulateSubgraphsPass</em>. This method makes call to <em>ShouldCompileCluster ()</em> to determine whether to proceed with clustering (e.g. Grappler-only path when XLA is not enabled, etc.). Hence, the XLA-path has lot more activity during this period.</p><p>The call stack at this point is shown below.</p><pre>tensorflow/compiler/jit/mark_for_compilation_pass.cc:980,1534,1825,1856<br>#0  MarkForCompilationPassImpl::CreateClusters<br>#1  MarkForCompilationPassImpl::Run (this=0x7fffffff8f60)<br>#2  MarkForCompilation ( options=..., debug_options=...)<br>#3  MarkForCompilationPass::Run ( this=0x555555ea7ef0, options=...)</pre><pre>tensorflow/core/common_runtime/optimization_registry.cc:73<br>#4  OptimizationPassRegistry::RunGrouping(grouping=POST_REWRITE_FOR_EXE,..)</pre><pre>tensorflow/core/common_runtime/process_function_library_runtime.cc:949,1466<br>#5  ProcessFunctionLibraryRuntime::InstantiateMultiDevice (function_name=..., )<br>#6  ProcessFunctionLibraryRuntime::Instantiate (function_name=...,)</pre><pre>tensorflow/core/common_runtime/eager/kernel_and_device.cc:239,247<br>#7  KernelAndDeviceFunc::InstantiateFunc (ndef=..., graph_collector=0x0)<br>#8  KernelAndDeviceFunc::Init (ndef=..., graph_collector=0x0)</pre><pre>tensorflow/core/common_runtime/eager/execute.cc:1123,1289,1694<br>#9  GetOrCreateKernelAndDevice ()<br>#10 EagerLocalExecute ()<br>#11 EagerExecute ()</pre><pre>tensorflow/core/common_runtime/eager/core.cc:204<br>#12 EagerOperation::Execute ()</pre><pre>tensorflow/core/common_runtime/eager/custom_device_op_handler.cc:95<br>#13 tensorflow::CustomDeviceOpHandler::Execute ()</pre><pre>tensorflow/c/eager/c_api.cc:879<br>#14 TFE_Execute ()</pre><pre><strong>Code: MarkForCompilationPass call stack</strong></pre><p>The TF computation graph is then converted into MHLO in <em>BuildHloFromGraph</em> . The call stack at this stage is listed below. <em>MlirXlaOpKernel</em> is an <em>XlaOpKernel</em> that is implemented by lowering MLIR TensorFlow to HLO legalization. MLIR Tensoflow is defined in <em>tensorflow/compiler/mlir/tensorflow/ir/tf_dialect.h</em>. <em>BuildHloFromGraph</em> first calls <em>GraphToModule</em> to generate an MLIR module from graph. It lowers TF IR to MHLO and insert HLO into the XlaBuilder, xla_params are HLO-level inputs to module_op that have already been added to the XlaBuilder, returns are the XlaOps.</p><p><em>BuildHloFromTfInner</em> converts MLIR module to XLA HLO proto contained in XlaComputation. <em>BuildHloFromTfInner</em> calls <em>mlir::BuildHloFromMlirHlo</em> , which in turn calls <em>ConvertToHloModule.lower() </em>that eventually lowers to XLA HLO <em>.</em></p><pre><em>tensorflow/</em>compiler/mlir/xla/mlir_hlo_to_hlo.cc:1907,2526<br>#0  ConvertToHloModule::Lower () at <br>#1  mlir::BuildHloFromMlirHlo ()</pre><pre><em>tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.cc</em><br>#2 BuildHloFromTfInner ()<br>#3 BuildHloFromTf ()<br>#4 BuildHloFromModule ()<br>#5 BuildHloFromGraph ()</pre><pre>tensorflow/compiler/tf2xla/mlir_xla_op_kernel.cc<br>#6 MlirXlaOpKernel::ConstructXlaOp () <br>#7 MlirXlaOpKernel::Compile (this=..., ctx=...)</pre><pre>tensorflow/compiler/tf2xla/xla_op_kernel.cc<br>#8 XlaOpKernel::Compute (this=..., context=...)</pre><pre>tensorflow/compiler/tf2xla/xla_compilation_device.cc<br>#9 XlaCompilationDevice::Compute ()</pre><pre>tensorflow/compiler/tf2xla/graph_compiler.cc<br>#10 GraphCompiler::Compile (this=...)</pre><pre>tensorflow/compiler/tf2xla/xla_compiler.cc<br>#11 ExecuteGraph ()<br>#12 XlaCompiler::CompileGraph ()<br>#13 XlaCompiler::CompileFunction ()</pre><pre>tensorflow/compiler/jit/xla_compilation_cache.cc<br>#14 XlaCompilationCache::&lt;lambda()&gt;::operator()(void) const ()<br>#15 XlaCompilationCache::CompileStrict ()<br>#16 XlaCompilationCache::CompileImpl ()<br>#17 XlaCompilationCache::Compile ()</pre><pre>tensorflow/compiler/jit/kernels/xla_ops.cc<br>#18 CompileToLocalExecutable ()<br>#19 XlaCompileOp::Compute (this=..., ctx=...)</pre><pre>tensorflow/core/common_runtime/gpu/gpu_device.cc<br>#20 BaseGPUDevice::Compute ()</pre><pre>tensorflow/core/common_runtime/executor.cc<br>#21 ExecutorState&lt;tensorflow::PropagatorState&gt;::ProcessSync ()</pre><pre><strong>Code: BuildHloFromGraph call stack</strong></pre><p>The first MLIR file <em>build_hlo_tf_before.mlir</em>, is dumped around here also. Some good comments are in the header file. <em>v2.9.1/tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h </em>.</p><p>HLO instructions are in DAG form and represent the atomic computations built up via the XLA service interface [11]. They are ultimately lowered in a platform-aware way by traversing the HLO DAG and emitting a lowered form (e.g. <em>DfsHloVisitor</em> ) . Nodes do not have total order within their computation, only have a partial ordering determined by data and control dependencies. HLO does not have basic blocks or explicit “branch” instructions. Instead, certain <em>HloInstructions</em> — namely, <em>kWhile</em>, <em>kConditional</em>, and <em>kCall</em> — encode control flow. For example, the <em>kConditional</em> HLO executes one of two possible computations, depending on the runtime value of a predicate. As of TF 2.9.1, HLO IR has 117 opcodes [11].</p><p><em>HloModule</em> is the top-level unit in the HLO IR. It corresponds to a whole “program”. Running a module, from beginning to end, is the only way to run an XLA program. A module contains one “entry computation”, this <em>HloComputation</em> is like main() in a C program. The result of running the module is the result of running this computation. A module also contains some number of “nested computations”. Each nested computation is attached to an <em>HloInstruction</em> within some other computation.</p><p>Then XLA related optimizations are done through codes in files in <em>tensorflow/compiler/xla/* </em>— see <strong>Code: Additional files used in XLA-path</strong> above, for the complete list of files . XLA does not JIT build convolutions and gemms, but picks appropriate kernels from libraries ( <em>gpu_conv_algorithm_picker.cc </em>, <em>gemm_algorithm_picker.cc</em> ) . The following shows the call stack at the convolution kernel picking moment.</p><pre>compiler/xla/service/gpu/gpu_conv_algorithm_picker.cc:497,716,392,915,992,1009<br>#0  xla::gpu::GpuConvAlgorithmPicker::AutotuneOneConvRunner ( )<br>#1  xla::gpu::GpuConvAlgorithmPicker::PickBestAlgorithmNoCacheCuda ()<br>#2  xla::gpu::GpuConvAlgorithmPicker::PickBestAlgorithm ()<br>#3  xla::gpu::GpuConvAlgorithmPicker::RunOnInstruction ()<br>#4  xla::gpu::GpuConvAlgorithmPicker::RunOnComputation ()<br>#5  xla::gpu::GpuConvAlgorithmPicker::Run ()</pre><pre>compiler/xla/service/hlo_pass_pipeline.h:123 180 272<br>#6  xla::HloPassPipeline::RunHelper ()<br>#7  xla::HloPassPipeline::RunPassesInternal&lt;xla::HloModule&gt; ()<br>#8  xla::HloPassPipeline::Run () </pre><pre>compiler/xla/service/gpu/gpu_compiler.cc:749<br>#9  xla::gpu::GpuCompiler::OptimizeHloPostLayoutAssignment ()</pre><pre>compiler/xla/service/gpu/nvptx_compiler.cc:145<br>#10 xla::gpu::NVPTXCompiler::OptimizeHloPostLayoutAssignment ()</pre><pre>compiler/xla/service/gpu/gpu_compiler.cc:548 763<br>#11 xla::gpu::GpuCompiler::OptimizeHloModule ()<br>#12 xla::gpu::GpuCompiler::RunHloPasses ()</pre><pre>compiler/xla/service/service.cc:797<br>#13 xla::Service::BuildExecutable ()</pre><pre>compiler/xla/service/local_service.cc:172<br>#14 xla::LocalService::CompileExecutables ()</pre><pre>compiler/xla/client/local_client.cc:393<br>#15 xla::LocalClient::Compile ()</pre><pre>compiler/jit/xla_compilation_cache.cc:288 539 803 335<br>#16 ::XlaCompilationCache::BuildExecutable ()<br>#17 ::XlaCompilationCache::CompileStrict () <br>#18 ::XlaCompilationCache::CompileImpl () <br>#19 ::XlaCompilationCache::Compile ()</pre><pre>compiler/jit/kernels/xla_ops.cc:271 457 679<br>#20 ::CompileToLocalExecutable ()<br>#21 ::XlaCompileOp::Compute () <br>#22 ::BaseGPUDevice::Compute ()<br> <br>core/common_runtime/executor.cc:584 830 1197 468<br>#23 ::ExecutorState&lt;::PropagatorState&gt;::ProcessSync ()<br>#24 ::ExecutorState&lt;::PropagatorState&gt;::Process ()<br>#25 ::ExecutorState&lt;::PropagatorState&gt;::&lt;lambda()&gt;::operator()() const ()<br>#26 ::ExecutorState&lt;::PropagatorState&gt;::&lt;lambda()&gt;::operator()()()</pre><pre><strong>Code: gpu_conv_algorithm_picker call stack</strong></pre><p>The following trace diagram shows the various XLA transformations optimizations , compiling cascading through time. On the left are the file names in the <em>xla</em> directory — same ones as in in <strong>Code: Additional files used in XLA-path</strong>. Along horizontal is the time as was logged in the log file. Each log line (lines emitted with VLOG ≤ 5 setting ) is charted as one event of 1 ms fixed duration. The trace provides a high level visual view along with finer details on how XLA optimization and compilation progresses. However, not all files have log outputs. In those cases a tool like gdb is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoqt3P-1ztpnpxqUpgLv2A.jpeg" /><figcaption>Fig 2: Time trace of log outputs from files in the xla , jit, grappler, mlir, etc directories.</figcaption></figure><p>At a broad visual level, the top part of the above chart corresponds to the files in the XLA directory. The bottom most part is TensorFlow profiler output. The blue rectangle there corresponds to <em>_XlaCompile</em>, where HLO gets lowered into LLVM , then to NVPTX (through nvcc compiler). The <em>_XlaCompile </em>op is registered to code in <em>XlaCompileOp</em>. The following lists the call stack at nvptx compilation.</p><pre>compiler/xla/service/gpu/nvptx_compiler.cc:480 369 1063 1137<br>#0  xla::gpu::NVPTXCompiler::CompileGpuAsmOrGetCachedResult () <br>#1  xla::gpu::NVPTXCompiler::CompileTargetBinary[abi:cxx11]() <br>#2  xla::gpu::GpuCompiler::&lt;lambda()&gt;::operator()() <br>#3  xla::gpu::GpuCompiler::CompileToTargetBinary[abi:cxx11]()() </pre><pre>tensorflow/compiler/xla/service/gpu/gpu_compiler.cc: 1280<br>#4  xla::gpu::GpuCompiler::RunBackend ()</pre><pre>compiler/xla/service/service.cc:801<br>#5  xla::Service::BuildExecutable ()</pre><pre>compiler/xla/service/local_service.cc:172<br>#6  xla::LocalService::CompileExecutables ()</pre><pre>compiler/xla/client/local_client.cc:393<br>#7  xla::LocalClient::Compile ()</pre><pre>compiler/jit/xla_compilation_cache.cc:288 539 803 335<br>#8  tensorflow::XlaCompilationCache::BuildExecutable ()<br>#9  tensorflow::XlaCompilationCache::CompileStrict () <br>#10 tensorflow::XlaCompilationCache::CompileImpl () <br>#11 tensorflow::XlaCompilationCache::Compile ()</pre><pre>compiler/jit/kernels/xla_ops.cc:271 457<br>#12 tensorflow::CompileToLocalExecutable () <br>#13 tensorflow::XlaCompileOp::Compute ()</pre><pre>core/common_runtime/gpu/gpu_device.cc:679<br>#14 tensorflow::BaseGPUDevice::Compute ()</pre><pre>core/common_runtime/executor.cc:597<br>#15 tensorflow::()::ExecutorState&lt;&gt;::ProcessSync()</pre><pre><strong>Code: NNPTX compiler call stack</strong></pre><p>Just before <em>CompileToTargetBinary()</em> in <em>RunBackend()</em>, <em>CompileModuleToLlvmIrImpl()</em> is called to lower HLO to llvm</p><p><strong>XLA Optimizations:</strong></p><p>XLA does several optimizations on HLO. Each of these are called pass ( <em>tensorflow/compiler/xla/service/hlo_pass_pipeline.cc</em> ). C++ classes for pass inherits from <em>HloModulePass</em> , <em>HloModuleGroupPass</em> and <em>HloPassInterface</em>. The passes are located in the <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/hlo_module_dce.h"><em>tensorflow/compiler/xla/service</em></a> directory. Some examples of passes follow.</p><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/hlo_constant_folding.h"><em>hlo_constant_folding.h</em></a> pass performs constant folding in order to eliminate unnecessary computation on constants ( e.g. 11.1*22.2 , 0*x, etc.) at runtime by performing these computations at compile time.</p><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/batchnorm_expander.h"><em>batchnorm_expander.h</em></a> pass breaks batch norm operations into more operations. Breaking a big operation into smaller operations helps leverage XLA’s generic fusion logic.</p><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/hlo_cse.h"><em>hlo_cse</em>.h</a> pass performs common-subexpression elimination. Identical constants and identical instructions with the same operands are “commoned”. The pass iterates over the instructions in topological order which enables the pass to find arbitrarily large common expressions. A toy example is shown in the code snippet below.</p><pre>a = b * c + g;<br>d = b * c * e;</pre><pre>// b*c is saved in tmp as a cse. </pre><pre>tmp = b * c;<br>a = tmp + g;<br>d = tmp * e;</pre><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h"><em>gemm_algorithm_picker.h</em></a><em> </em>pass, as the name suggests, picks the best gemm.</p><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/gpu/gemm_rewriter.h"><em>gemm_rewriter.h</em></a> pass pattern-matches the most general form of the following HLO instruction ( assuming transposes are already folded), and rewrites it into a custom call, where (A, B, C) are three operands respectively, and `alpha` and `beta` are stored in the backend config.</p><pre>cuBLAS GEMM in the most general form can run the following operation:</pre><pre>(kAdd<br>    (kMultiply (kDot A B) alpha)<br>    (kMultiply C beta))</pre><pre>where A, B, C are matrixes and `alpha` and `beta` are host constants. The additional requirement is that C has no other users (otherwise, it does not make sense to fuse it inside the custom call).</pre><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/dot_merger.h"><em>dot_merger.h</em></a> pass merges dots that share an operand as follows.</p><pre>Transforms<br>//<br>//   x = dot(a, b)<br>//   y = dot(a, c)<br>//<br>// into<br>//<br>//   z = dot(a, concat(b, c))<br>//   x = slice(z)<br>//   y = slice(z).<br>//<br>// This requires that x and y are independent -- that is, <br>// x does not transitively depend on y, and <br>// y does not transitively depend on x.</pre><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/hlo_dce.h"><em>hlo_dce.h</em></a> pass removes dead instructions from each computation in the module and removes dead computations from the module. An instruction is dead if it is not reachable from the root. A computation is dead if it is not the entry computation of the module and it is not reachable from the entry computation.</p><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/gpu/gpu_conv_algorithm_picker.h"><em>gpu_conv_algorithm_picker.h</em></a> pass modifies <em>CustomCalls</em> to cudnn convolutions, choosing the best algorithm for each and adding explicit scratch space to the <em>CustomCalls</em>. Custom calls allow invoking code written in a programming language like C++ or CUDA from an XLA program ( <em>tensorflow/compiler/xla/g3doc/custom_call.md</em> )</p><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/gpu/cudnn_vectorize_convolutions.h"><em>cudnn_vectorize_convolutions.h</em></a> pass changes the shape of cudnn convolutions to use faster “vectorized” algorithms as follows.</p><pre>// On sm61+ will convert int8_t convolutions from<br>//<br>//   - [N, C, H, W] to [N, C/4, H, W, 4],<br>//<br>// assuming C is divisible by 4.<br>//<br>// On sm75+ will convert int8_t convolutions from<br>//<br>//   - [N, C, H, W]      to [N, C/32, H, W, 32],<br>//   - [N, C/4, H, W, 4] to [N, C/32, H, W, 32], and<br>//   - [N, C, H, W]      to [N,  C/4, H, W,  4] (same as sm61+),<br>//<br>// assuming C is divisible by 4 or 32.</pre><p>The <a href="https://github.com/tensorflow/tensorflow/blob/be29b5d32fd132d7f6d75c0ba2e37b7b0347444e/tensorflow/compiler/xla/service/instruction_fusion.h"><em>instruction_fusion.h</em></a> pass performs, as the name suggests, HLO instruction fusion. Instructions are fused “vertically”, meaning producing instructions are fused into their consumers with the intent that the loops which compute their values will be fused in code generation. Derived classes define <em>ShouldFuse</em> method to select which instructions to fuse. The following TensorFlow debug html (see Appendix 2:Generating logs and graphs, on how these were generated ) output shows one such example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*y4DVNkhrao_zbQtlKqoNCQ.jpeg" /><figcaption>Fig 3: XLA HLO instruction fusion .</figcaption></figure><p>The <a href="https://github.com/tensorflow/tensorflow/blob/v2.9.1/tensorflow/compiler/xla/service/gpu/fusion_merger.h"><em>fusion_merger.h</em></a> pass attempts to merge fusion instructions to reduce memory bandwidth requirements and kernel launch overhead. Which is one the major goals of XLA. See the example below on what this does.</p><pre>On the left-hand side, op A is the producer and ops B and C are its consumers. FusionMerger duplicates producer ops and fuses them into all consumers. The result is depicted on the right-hand side below.<br><br>          p                    p<br>          |                  /   \<br>          v                 /     \<br>          A            +fusion+  +fusion+<br>        /   \          |  A&#39;  |  |  A&quot;  |<br>       |     |         |  |   |  |  |   |<br>       v     v         |  v   |  |  v   |<br>       B     C         |  B   |  |  C   |<br>                       +------+  +------+<br><br>Op A has been cloned twice and fused with B and C. The kernel launch overhead is reduced from 3 to 2. The memory bandwidth requirements may be reduced. We trade 1 read of input(A) + 1 write and 2 reads of output(A) for 2 reads of input(A). In general the achievable savings in memory bandwidth depend on the differences in memory read and written and the number of consumers. The FusionMeger pass takes this into account when making fusion decisions.</pre><pre>The pass traverses the HLO module in reverse post-order (defs before uses). Fusion instructions are merged into their users if some conditions are met:<br>* The result of merging the fusion instruction into its users would not increase bytes transferred.<br>* Producer ops are fusible with _all_ consumers. If they are not fusible with at least one consumers, they won&#39;t be fused at all.<br>* Producers are kLoop fusion ops. None of these restrictions are necessary for correctness. In fact, lifting the latter two could be beneficial.<br></pre><h3>Glossary:</h3><p>tf.Module — In TensorFlow, most high-level implementations of layers and models, such as Keras or Sonnet, are built on the same foundational class: tf.Module . Modules and, by extension, layers are deep-learning terminology for “objects”: they have internal state, and methods that use that state.</p><p>Graph is a C++ structure defined in <em>tensorflow/core/graph/graph.h</em> . Node ans Edges are parts of the graph. 31 different types of NodeClass are defined as shown below.</p><pre>— NC_UNINITIALIZED, NC_SWITCH, NC_MERGE, NC_ENTER, NC_EXIT, NC_NEXT_ITERATION, NC_LOOP_COND, NC_CONTROL_TRIGGER, NC_SEND, NC_HOST_SEND, NC_RECV, NC_HOST_RECV, NC_CONSTANT, NC_VARIABLE, NC_IDENTITY, NC_GET_SESSION_HANDLE, NC_GET_SESSION_TENSOR, NC_DELETE_SESSION_TENSOR, NC_METADATA, NC_SCOPED_ALLOCATOR, NC_COLLECTIVE, NC_FAKE_PARAM, NC_PARTITIONED_CALL, NC_FUNCTION_OP, NC_SYMBOLIC_GRADIENT,NC_IF, NC_WHILE, NC_CASE, NC_ARG, NC_RETVAL, NC_OTHER,</pre><p>GraphDef is a serialized version of Graph. This is the low-level definition of a TensorFlow computational graph, including a list of nodes and the input and output connections between them. During training of Python model, this is usually saved out in the same directory as checkpoints, and usually has a ‘.pb’ or ‘.pbtxt’ extension. Should not need to use GraphDefs directly in TF2. To load GraphDefs in TF2, SavedModel can be used.</p><p>SaverDef , a protocol buffer for saver object. A Saver class saves and restores variables to and from checkpoints.</p><p>MetaGraphDef is a protobuf containing meta information regarding the graph to be exported. It contains GraphDef and SaverDef</p><p>pb is the file extension for protocol buffer format files. Tensorflow Saved Models on disk are in this format.</p><p>SavedModel contains a complete TensorFlow program, including trained parameters (i.e, tf.Variables) and computation. SavedModel contains the GraphDef, and does not require the original model code to run. SavedModel is a directory containing serialized signatures and the state needed to run them, including variable values and vocabularies. The saved_model.pb file stores the actual TensorFlow program, or model, and a set of named signatures, each identifying a function that accepts tensor inputs and produces tensor outputs. SavedModels may contain multiple variants of the model (multiple v1.MetaGraphDefs, identified with the — tag_set flag to saved_model_cli). TensorFlow Serving uses SavedModel to run inference.</p><p>Freezing model refers to converting the checkpoint values into embedded constants within the graph file itself. Takes GraphDef proto, SaverDef proto, and a set of variable values stored in a checkpoint file, and output a GraphDef with all of the variable ops converted into const ops containing the values of the variables.</p><p>Grappler is the default graph optimization system in the TF runtime. Grappler applies optimizations in graph mode (within tf.function) to improve performance of TensorFlow computations through graph simplifications and other high-level optimizations such as inlining function bodies to enable inter-procedural optimizations. In the code it is called MetaOptimizer.</p><p>Gradient tape is used to differentiate automatically. TensorFlow needs to remember what operations happen in what order during the forward pass. During the backward pass, TensorFlow traverses this list of operations in reverse order to compute gradients. TensorFlow “records” operations executed inside the context of a tf.GradientTape onto a “tape”.</p><p>AutoGraph is a library that is on by default in tf.function, and transforms a subset of Python eager code into graph-compatible TensorFlow ops — if, for, while. TensorFlow control flow ops like tf.cond and tf.while_ exists, but it is easier to write and understand in Python.</p><p>stream — performs actions with a linear stream of dependencies.</p><p>swig — Simplified Wrapper and Interface Generator for C/C++ code for languages like Python.</p><p>Affine — An affine function is linear — (e.g. 2*x+10 is affine, but not x²+10) . Affine Loops are where the loop bounds and array references are affine functions of loop iterators and program parameters. The MLIR polyhedral loop dialect is called affine.</p><p>Ployhedral model — polyhedron is an n-dimensional geometric object. Each loop in a nested iteration can be considered a dimension in a polyhedron. Polyhedral model provides a mathematical framework to reason about loops in programs. Polyhedral model can be used to reason about Affine Loops.</p><p>MLIR — Multi-level Intermediate Representation. MLIR dialects define operations, types, type constraints, rewrite rules, lowerings, etc. Has 14 builtin dialects. Examples of dialects supported by MLIR are Affine dialect, Func dialect, GPU dialect, LLVM dialect, SPIR-V dialect, Vector dialect , etc. MLIR handles parsing, type checking/inference, line-number tracking, etc. MLIR also provides tools for testing and parallel compilation, documentation, CLI, etc. MLIR allows for multiple dialects, even those outside of the main tree, to co-exist together within one module. Dialects are produced and consumed by certain passes. MLIR provides a framework to convert between, and within, different dialects.</p><p>MLIR Module [10] — A module represents a top-level container ( for IR) operation. It contains a single graph region containing a single block which can contain any operations and does not have a terminator. Operations within this region cannot implicitly capture values defined outside the module, i.e. Modules are <em>IsolatedFromAbove</em>. Modules have an optional symbol name which can be used to refer to them in operations.</p><p>MLIR Block [10] — list of operations</p><p>LLVM — is an Intermediate Representation ( IR) that is usually considered a backend.</p><p>HLO — High Level Operation</p><p>MHLO [ 8,9] — MLIR HLO dilect</p><p>MLIR-HLO — A standalone “HLO” MLIR-based Compiler <a href="https://github.com/tensorflow/tensorflow/tree/v2.9.1/tensorflow/compiler/mlir/hlo">https://github.com/tensorflow/tensorflow/tree/v2.9.1/tensorflow/compiler/mlir/hlo</a></p><p>TensorFlow IR — MLIR dialect to represent TensorFlow graphs.</p><p>LHLO — Late MHLO variant of MLIR dialect, that operates on buffers instead of tensors.</p><p>XLA HloInstruction — XLA Input IR</p><p>Linalg — the linear algebra dialect of MLIR.</p><p>Autograd can automatically differentiate native Python and Numpy code</p><p>JAX is <a href="https://github.com/hips/autograd">Autograd</a> and <a href="https://www.tensorflow.org/xla">XLA</a>, brought together for high-performance machine learning research. JAX uses XLA to compile and run NumPy programs on GPUs and TPUs. JAX provides an implementation of NumPy (with a near-identical API) that works on both GPU and TPU. JAX provides functions transformations — grad() through Autograd, jit() through XLA, vmap() -vectorization, pmap() — SPMD parallelization on TPUs.</p><p>PartitionedCall represents asynchronously executing a function across multiple devices</p><p>PTX (Parallel Thread Execution ) — PTX is a programming model and instruction set (ISA) for general purpose parallel programming on Nvidia. High level language compilers for CUDA and C/C++ generate PTX instructions</p><p>Thunk — ( from tensorflow/compiler/xla/service/gpu/thunk.h) Thunk acts as the bridge between IrEmitter and GpuExecutable. It stores the metadata IrEmitter generates for GpuExecutable to invoke an HloInstruction. Thunk provides the Initialize and ExecuteOnStream interface for GpuExecutable to initialize and execute the invocation respectively. Its subclasses are supposed to override these interfaces to launch a generated kernel or call an external library function (such as operations in cuBLAS). Is runs on CPUs.</p><p>Cubin — CUDA binary (cubin) is an ELF-formatted file consisting of CUDA executable code as well as other sections containing symbols, relocators, debug info, etc. By default, the CUDA compiler nvcc embeds cubin files into the host executable file. They can also be generated separately by using the “-cubin” option of nvcc. cubin files are loaded at run time by the CUDA driver API.</p><p>Fatbin — CUDA fat binary file that contains multiple PTX and CUBIN files. A host compilation synthesis step embeds the fatbinary and transform CUDA specific C++ extensions into standard C++ constructs. The C++ host compiler eventually compiles the synthesized host code with the embedded fatbinary into a host object.</p><p>StreamExecutor — manages a single device, in terms of executing work (kernel launches) and memory management (allocation/deallocation, memory copies to and from the device). It is conceptually the “handle” for a device — Stream objects, which are used to enqueue work to run on the coprocessor, have a StreamExecutor instance as their “parent” object.</p><h3><strong>Appendices</strong>:</h3><p><strong>Appendix 1: Building TensorFlow debug version</strong></p><p>A debug version of TensorFlow is essential to explore the code base. A wheel for debug version is not readily available, hence needs to be built. Debug version build requires more memory during the bazel build linking stage, hence increasing swap space helps. The follow shows the commands for a conda setup</p><pre>cuda driver : 470.129.06 ( Cuda 11.4)</pre><pre>conda create -n tfbuild python=3.9</pre><pre>conda install cudatoolkit-dev=11.4.0 cudatoolkit=11.4.1 cuda-nvcc=11.4.120 cudnn=8.2.1.32 gcc=9.4.0 gxx=9.4.0</pre><pre>bazel — output_base=./bazelout/outputs build — jobs 2 — local_ram_resources=4096 — repository_cache=./bazelout/cache — verbose_failures — config=dbg — config=cuda //tensorflow/tools/pip_package:build_pip_package</pre><pre>./bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg</pre><pre>source $CONDA_PREFIX/lib/python3.9/site-packages/libpython.py</pre><p><strong>Appendix 2:Generating logs and graphs</strong></p><p>The following command was used for generating detailed logs and graph dumps. The .pbtxt format graphs can be viewed on Netron as long as they are not very large. Depending on the network model, the log file can be huge and number of graphs dumped can be large.</p><pre>OUTPUTDIR=./outputs_tf_fmnst/wx_`date +%Y_%m_%d_%H_%m_%S`; mkdir -p $OUTPUTDIR ; TF_XLA_FLAGS= — tf_xla_clustering_debug TF_CPP_MAX_VLOG_LEVEL=5 TF_DUMP_GRAPH_PREFIX=$OUTPUTDIR/graphs XLA_FLAGS=” — xla_gpu_cuda_data_dir=$CONDA_PREFIX/pkgs/cuda-toolkit — xla_dump_to=$OUTPUTDIR/hlo — xla_dump_hlo_as_html — xla_dump_fusion_visualization” LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib python tf_fmnst.py — epochs 1 — xla --profile 2&gt;&amp;1 | tee $OUTPUTDIR/output.log</pre><p><strong>Appendix 3: Running TensorFlow within gdb , breaking and backtracing.</strong></p><pre>LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$VCONDA_PREFIX/lib  gdb --args python  tf_fmnst.py --epochs 1<br>(gdb) b tensorflow/core/profiler/internal/gpu/cupti_tracer.cc:383</pre><p><strong>Appendix 4: Codes for network model and log analysis</strong></p><p>The two main python files used, tf_fmnst.py and analyze_log.py, are shown below.</p><pre>&#39;&#39;&#39;<br>OUTPUTDIR=./outputs_tf_fmnst/wx_`date +%Y_%m_%d_%H_%m_%S`; mkdir -p $OUTPUTDIR ; TF_XLA_FLAGS=--tf_xla_clustering_debug  TF_CPP_MAX_VLOG_LEVEL=5 TF_DUMP_GRAPH_PREFIX=$OUTPUTDIR/graphs XLA_FLAGS=&quot;--xla_gpu_cuda_data_dir=$CONDA_PREFIX/pkgs/cuda-toolkit --xla_dump_to=$OUTPUTDIR/hlo --xla_dump_hlo_as_html --xla_dump_fusion_visualization&quot; LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$VCONDA_PREFIX/lib  python    tf_fmnst.py --epochs 1  --xla 2&gt;&amp;1 | tee $OUTPUTDIR/output.log<br>&#39;&#39;&#39;</pre><pre>import tensorflow as tf<br>import argparse<br>import timeit<br>import time<br>import pandas as pd</pre><pre>parser = argparse.ArgumentParser(description=&#39;To show xla flow.&#39;)<br>parser.add_argument(&quot;--epochs&quot;, type=int, default=10, help=&quot;maximum number of epochs to run. &quot;)<br>parser.add_argument(&quot;--iters&quot;, type=int, default=4, help=&quot;maximum number of iterations per epoch to run. &quot;)<br>parser.add_argument(&quot;--xla&quot;, action=&#39;store_true&#39;, default=False, help=&quot;enable xla&quot;)<br>parser.add_argument(&quot;--warmup&quot;, action=&#39;store_true&#39;, default=False, help=&quot;run warmup&quot;)<br>parser.add_argument(&#39;-f&#39;, type=str, help=&#39;log file&#39;)<br>parser.add_argument(&#39;--logdir&#39;, type=str, help=&#39;log directory&#39;)<br>parser.add_argument(&#39;--bs&#39;, type=int, default=256, help=&#39;batch size&#39;)<br>parser.add_argument(&quot;--profile&quot;, action=&#39;store_true&#39;, default=False, help=&quot;run profiler&quot;)<br>args = parser.parse_args()</pre><pre># Check that GPU is available: cf. <a href="https://colab.research.google.com/notebooks/gpu.ipynb">https://colab.research.google.com/notebooks/gpu.ipynb</a><br>assert(tf.test.gpu_device_name())</pre><pre>tf.keras.backend.clear_session()</pre><pre>if args.xla:<br> #tf.config.optimizer.set_jit(True) <br> tf.config.optimizer.set_jit(&quot;autoclustering&quot;) <br>else:<br> tf.config.optimizer.set_jit(False)</pre><pre>def load_data():<br>  (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()<br>  x_train = x_train.astype(&#39;float32&#39;) / args.bs<br>  x_test = x_test.astype(&#39;float32&#39;) / args.bs</pre><pre># Convert class vectors to binary class matrices.<br>  y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)<br>  y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)<br>  return ((x_train, y_train), (x_test, y_test))</pre><pre>def generate_model():<br>  return tf.keras.models.Sequential([<br>    tf.keras.layers.Conv2D(32, (3, 3), padding=&#39;same&#39;, input_shape=x_train.shape[1:]),<br>    tf.keras.layers.Activation(&#39;relu&#39;),<br>    tf.keras.layers.Conv2D(32, (3, 3)),<br>    tf.keras.layers.Activation(&#39;relu&#39;),<br>    tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),<br>    tf.keras.layers.Dropout(0.25),</pre><pre>tf.keras.layers.Conv2D(64, (3, 3), padding=&#39;same&#39;),<br>    tf.keras.layers.Activation(&#39;relu&#39;),<br>    tf.keras.layers.Conv2D(64, (3, 3)),<br>    tf.keras.layers.Activation(&#39;relu&#39;),<br>    tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),<br>    tf.keras.layers.Dropout(0.25),</pre><pre>#tf.keras.layers.Flatten(input_shape=x_train.shape[1:]),<br>    tf.keras.layers.Flatten(),<br>    tf.keras.layers.Dense(512),<br>    tf.keras.layers.Activation(&#39;relu&#39;),<br>    tf.keras.layers.Dropout(0.5),<br>    tf.keras.layers.Dense(10),<br>    tf.keras.layers.Activation(&#39;softmax&#39;)<br>  ])</pre><pre>class DebugCallback(tf.keras.callbacks.Callback):<br>    def on_train_batch_begin (self, batch, logs=None):<br>        print (f&quot;======= batch {batch} begin =========&quot;) <br>    def on_train_batch_end (self, batch, logs=None):<br>        print (f&quot;======= batch {batch} end =========&quot;) <br>        <br>def compile_model(model):<br>  opt = tf.keras.optimizers.RMSprop(lr=0.0001, decay=1e-6)<br>  model.compile(loss=&#39;categorical_crossentropy&#39;,<br>                optimizer=opt,<br>                metrics=[&#39;accuracy&#39;])<br>  return model</pre><pre>def train_model(model, x_train, y_train, x_test, y_test, epochs=25):<br>  model.fit(x_train, y_train, batch_size=args.bs, epochs=epochs, verbose=2, <br>            validation_steps=0, validation_data=(x_test, y_test), shuffle=True,<br>            callbacks=[DebugCallback()])</pre><pre>def warmup(model, x_train, y_train, x_test, y_test):<br>  # Warm up the JIT, we do not wish to measure the compilation time.<br>  initial_weights = model.get_weights()<br>  train_model(model, x_train, y_train, x_test, y_test, epochs=1)<br>  model.set_weights(initial_weights)</pre><pre>(x_train, y_train), (x_test, y_test) = load_data()<br>model = generate_model()<br>model = compile_model(model)<br>model.summary()</pre><pre>if args.warmup:<br>        warmup(model, x_train, y_train, x_test, y_test)</pre><pre>data_size = args.bs*args.iters<br>time0 = time.time()<br>if args.profile:<br> tf.profiler.experimental.start(args.logdir+&quot;/profile&quot;)<br>train_model(model, x_train[:data_size], y_train[:data_size], x_test, y_test, epochs=args.epochs)<br>if args.profile:<br> tf.profiler.experimental.stop()<br>print (&#39;Train time (s):&#39;, time.time() - time0)</pre><pre>if False: #  args.xla:<br> print ( &quot;hlo ir:&quot;)<br> print(generate_model.experimental_get_compiler_ir(x,y,z,zz)(stage=&#39;hlo&#39;))<br> print ( &quot;optimized hlo ir:&quot;)<br> print(generate_model.experimental_get_compiler_ir(x,y,z,zz)(stage=&#39;optimized_hlo&#39;))<br> print ( &quot;optimized hlo dot:&quot;)<br> print(generate_model.experimental_get_compiler_ir(x,y,z,zz)(stage=&#39;optimized_hlo_dot&#39;))<br>#scores = model.evaluate(x_test, y_test, verbose=1)<br>#print(&#39;Test loss:&#39;, scores[0], &#39;Test accuracy:&#39;, scores[1])</pre><pre>&#39;&#39;&#39;<br># We need to clear the session to enable JIT in the middle of the program.<br>tf.keras.backend.clear_session()<br>tf.config.optimizer.set_jit(True) # Enable XLA.<br>model = compile_model(generate_model())<br>(x_train, y_train), (x_test, y_test) = load_data()</pre><pre>warmup(model, x_train, y_train, x_test, y_test)<br>time0 = time.time()<br>train_model(model, x_train, y_train, x_test, y_test, epochs=EPOCHS)<br>print (&#39;Train time (s):&#39;, time.time() - time0)<br>&#39;&#39;&#39;</pre><pre><strong>Code:  tf_mnst.py</strong></pre><pre>import argparse<br>import json<br>import copy<br>from datetime import datetime, timezone<br><br><br>parser = argparse.ArgumentParser(description=&#39;Process log file.&#39;)<br><br>parser.add_argument(&#39;-f&#39;, type=str, help=&#39;log file&#39;)<br>parser.add_argument(&#39;--splitsec&#39;, type=float, default=0, help=&#39;split at seconds since start &#39;)<br>parser.add_argument(&#39;--tfpf&#39;, type=str, default=None, help=&#39;TF trace  file&#39;)<br>parser.add_argument(&quot;--its&quot;, action=&#39;store_true&#39;, default=False, help=&quot;use iine number as timestamp&quot;)<br><br>args = parser.parse_args()<br><br>print(&quot;args: &quot;, args)<br><br>def load_tf_trace(tracef, time_delta):<br>    tfpf=None<br>    if tracef is None:<br>        return tfpf<br>    with open(tracef) as f:<br>        tfpf=json.load(f) <br>    for te in tfpf[&#39;traceEvents&#39;]:<br>        if &#39;ts&#39; in te.keys():<br>            te[&#39;ts&#39;] = time_delta + te[&#39;ts&#39;]<br>    return tfpf<br><br>def find_start_token(l):<br>        ltoks = l.split()<br>        starttok = -1<br>        for i,tok in enumerate(ltoks):<br>            if tok.startswith (&#39;tensorflow/&#39;):<br>                starttok = i<br>                break<br>            else:<br>                pass<br>        return starttok, ltoks<br><br><br>def runlength_encoding( lines):<br>    encoded = []<br>    runtok = &quot;&quot;<br>    runlength = 0<br>    for l in lines:<br><br>        starttok,ltoks = find_start_token(l)<br>        if starttok == -1: continue<br><br>        if ltoks[starttok] == runtok:<br>            runlength +=1 <br>        else:<br>            encoded.append( (runtok, runlength))<br>            runtok = ltoks[starttok]<br>            runlength = 1<br><br>    return encoded[1:] # removing the first dummy line <br><br><br>def load_log( lines):<br>    encoded = []<br>    runtok = &quot;&quot;<br>    runlength = 0<br>    startts = 0<br>    splitts = -1<br>    splitline = -1<br>    for idx, l in enumerate(lines):<br><br>        starttok,ltoks = find_start_token(l)<br>        if starttok == -1: continue<br><br>        naive = datetime.strptime(&quot; &quot;.join(ltoks[:2]), &quot;%Y-%m-%d %H:%M:%S.%f:&quot;)<br>        ts = naive.timestamp()*1.0e6<br>        if startts == 0:<br>            startts = ts<br><br>        if ltoks[starttok] == runtok:<br>            runlength +=1 <br>        else:<br>            runtok = ltoks[starttok]<br>            runlength = 1<br><br>        encoded.append( (ltoks[starttok], runlength, ts, idx, &quot; &quot;.join(ltoks[:2]+ltoks[4:])  ) )<br><br>        if splitts == -1  and (ts - startts ) &gt;=  (args.splitsec*1e6) :<br>            splitts = ts<br>            splitline = len(encoded) -1 # index starts at 0<br><br>    return encoded[1:], startts, splitts, splitline # removing the first dummy line <br><br>def runlength_encoding( lines):<br>    encoded = []<br>    runtok = &quot;&quot;<br>    runlength = 0<br>    for l in lines:<br><br>        starttok,ltoks = find_start_token(l)<br>        if starttok == -1: continue<br><br>        if ltoks[starttok] == runtok:<br>            runlength +=1 <br>        else:<br>            encoded.append( (runtok, runlength))<br>            runtok = ltoks[starttok]<br>            runlength = 1<br><br>    return encoded[1:] # removing the first dummy line <br><br>def unique_count (lines):<br>    call_dict = {}<br>    for l in lines:<br><br>        starttok,ltoks = find_start_token(l)<br>        if starttok == -1: continue<br><br>        if ltoks[starttok]  not in call_dict.keys():<br>            call_dict[ltoks[starttok]] = 1<br>        else:<br>            call_dict[ltoks[starttok]] += 1<br><br>    return call_dict<br><br>def create_log_trace (tsel, marker=None):<br>    tracedict = {&quot;traceEvents&quot;:[],<br>                 &quot;meta_user&quot;: &quot;sg&quot;,<br>                }<br><br>    multiplier = 1000<br>    its = 0<br>    tsdbegin = None<br>    tsdend   = None<br><br>    for tse in tsel:<br>        fpath,linenum = tse[0].split(&quot;:&quot;)<br>        if &quot;optimization of a group&quot; in tse[-1] or &quot;Running optimization &quot; in tse[-1]:<br>            ph = &quot;i&quot;<br>            s = &quot;g&quot;<br>        else:<br>            ph = &quot;X&quot;<br>            s = None<br><br>        if not args.its:<br>            ts = tse[2]<br>        else:<br>            ts = its*multiplier<br>        fpathl = fpath.split(&quot;/&quot;) <br><br>        if len (fpathl) &gt;3 :<br>            pid = &quot;/&quot;.join(fpathl[:3])<br>            pid += &quot; &quot;*30<br>            #tid = fpath<br>            tid = &quot;/&quot;.join(fpathl[3:])<br>        else:<br>            pid = fpath<br><br>        linerest = &quot; &quot;.join([str(v) for v in tse[3:]])<br>        linerest_max = 100<br>        linerest = linerest[:linerest_max] if len (linerest) &gt; linerest_max else linerest<br>        tsd = {&quot;pid&quot;: pid,<br>               &quot;tid&quot;: tid, #linenum[:-1],<br>               &quot;ts&quot;: ts,<br>               #&quot;dur&quot;:tse[1]*multiplier,<br>               &quot;dur&quot;:multiplier,<br>               &quot;ph&quot;:ph,<br>               &quot;s&quot;:s,<br>               &quot;name&quot;: tse[0][:-1],<br>               &quot;args&quot;: {#&quot;linenum&quot;:linenum[:-1],<br>                        #&quot;seqid&quot;:its,<br>						&quot;runlength&quot;: tse[1],<br>                        &quot;linerest&quot;:linerest},<br>              }<br>        #ts += tse[1] <br>        its += 1 <br>        tracedict[&quot;traceEvents&quot;].append(tsd)<br>        tsdend = tsd<br>        if tsdbegin is None:<br>            tsdbegin = tsd<br><br>    if marker == &quot;end&quot;:<br>        tsdend = copy.deepcopy(tsdend)<br>        tsdend[&quot;ph&quot;] = &quot;i&quot;<br>        tsdend[&quot;s&quot;] = &quot;g&quot;<br>        tsdend[&quot;name&quot;] = &quot;End of log&quot;<br>        tsdend[&quot;args&quot;] = {}<br>        tracedict[&quot;traceEvents&quot;].append(tsdend)<br>    elif marker == &quot;begin&quot;:<br>        tsdbegin = copy.deepcopy(tsdbegin)<br>        tsdbegin[&quot;ph&quot;] = &quot;i&quot;<br>        tsdbegin[&quot;s&quot;] = &quot;g&quot;<br>        tsdbegin[&quot;name&quot;] = &quot;Begining of log&quot;<br>        tsdbegin[&quot;args&quot;] = {}<br>        tracedict[&quot;traceEvents&quot;].append(tsdbegin)<br><br><br>    return tracedict<br><br><br>with open(args.f) as f:<br>    lines = f.readlines()<br><br>call_dict = unique_count (lines)<br>print ( &quot;======unique calls: &quot;, len(call_dict.keys()))<br>for k in call_dict.keys():<br>    print (k, call_dict[k])<br><br>&#39;&#39;&#39;<br>runlength  = runlength_encoding( lines)<br>print (&quot;=======runlength calls: &quot;, len(runlength))<br>for l in runlength:<br>    print ( l )<br><br>print (&quot;summary: &quot;, len(call_dict.keys()) , len(runlength))<br><br>jsonf = args.f+&quot;.runlength.json&quot;<br>crate_trace(runlength, jsonf)<br>&#39;&#39;&#39;<br><br>logfullline,startts, splitts,splitline = load_log(lines)<br>tft = load_tf_trace(args.tfpf, startts)<br>for si in [(0,splitline, &quot;end&quot;), (splitline+1,len(logfullline), &quot;begin&quot;)]:<br>    if si[0] == si[1]:<br>        continue<br>    splitlog = logfullline[si[0]:si[1]]<br>    logtrace = create_log_trace(splitlog, si[2])<br>    if tft is not None:<br>        tft[&#39;traceEvents&#39;] = tft[&#39;traceEvents&#39;]+logtrace[&#39;traceEvents&#39;]<br>    else:<br>        tft = logtrace[&#39;traceEvents&#39;]<br>    jsonf = args.f+f&quot;lines_{si[0]}_{si[1]}.merged.json&quot;<br>    print(&quot;writting to file &quot;, jsonf)<br>    with open ( jsonf, &quot;w&quot;) as fp:<br>        json.dump(tft,fp)<br><br>print (&quot;done&quot;)</pre><pre><strong>Code:  analyze_log.py</strong></pre><p><strong>Appendix 5: Grappler Groups, Phases and Passes</strong></p><pre><strong>Starting optimization of a group 0 — PRE_PLACEMENT</strong><br>Running optimization phase 0 <br>Running optimization pass: <strong>MlirV1CompatGraphOptimizationPass</strong>   (<a href="https://github.com/tensorflow/tensorflow/tree/84a60a8d69c376ad7fb15890ee798cd9759e0937/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/84a60a8d69c376ad7fb15890ee798cd9759e0937/tensorflow/compiler/mlir">mlir</a>/mlir_graph_optimization_pass.h) <br>Running optimization phase 9 <br>Running optimization pass: ControlFlowDepsToChainsPass (<a href="https://github.com/tensorflow/tensorflow/tree/1dea602813ee3958e5e405092abb44be3d74427c/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/1dea602813ee3958e5e405092abb44be3d74427c/tensorflow/core/common_runtime">common_runtime</a>/control_flow_deps_to_chains.h)<br>Running optimization phase 10 <br>Running optimization pass: AccumulateNV2RemovePass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core/common_runtime">common_runtime</a>/accumulate_n_optimizer.cc)<br>Running optimization pass: LowerFunctionalOpsPass (<a href="https://github.com/tensorflow/tensorflow/tree/b6420c583577937d465e1a1436dbb3c09c25d427/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/b6420c583577937d465e1a1436dbb3c09c25d427/tensorflow/core/common_runtime">common_runtime</a>/lower_functional_ops.h)<br>Running optimization pass: ParallelConcatRemovePass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core/common_runtime">common_runtime</a>/parallel_concat_optimizer.cc) <br>Running optimization phase 35 <br>Running optimization pass: IsolatePlacerInspectionRequiredOpsPass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core/common_runtime">common_runtime</a>/isolate_placer_inspection_required_ops_pass.h)<br>Running optimization pass: <strong>IntroduceFloatingPointJitterPass</strong> (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/introduce_floating_point_jitter_pass.h)<br>Running optimization phase 36 <br>Running optimization pass: <strong>EncapsulateXlaComputationsPass</strong> (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/encapsulate_xla_computations_pass.h) <br>maxwell_scudnn_winograd_128x128_ldg1_ldg4_relu_tile228n_nt_v1 Running optimization phase 37 <br>Running optimization pass: <strong>FunctionalizeControlFlowForXlaPass</strong> (<a href="https://github.com/tensorflow/tensorflow/tree/d768ca6b53b74d6b675a23a08f54f43b6ce366af/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/d768ca6b53b74d6b675a23a08f54f43b6ce366af/tensorflow/compiler/tf2xla">tf2xla</a>/functionalize_control_flow.h) <br>Running optimization phase 99999 <br>Running optimization pass: WeakForwardTypeInferencePass (<a href="https://github.com/tensorflow/tensorflow/tree/db4c22380eb9224aa03b9e8b9da74bac65009088/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/db4c22380eb9224aa03b9e8b9da74bac65009088/tensorflow/core/common_runtime">common_runtime</a>/forward_type_inference.h) <br><strong>Starting optimization of a group 1 — POST_PLACEMENT</strong><br>Running optimization phase 0 <br>Running optimization pass: NcclReplacePass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core">core</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/core/nccl">nccl</a>/nccl_rewrite.cc)<br><strong>Starting optimization of a group 2 — POST_REWRITE_FOR_EXEC</strong><br>Running optimization phase 5 <br>Running optimization pass: CloneConstantsForBetterClusteringPass (<a href="https://github.com/tensorflow/tensorflow/tree/f1326e0c98cc382d1e3de1cf461a7a85c33cbea7/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/f1326e0c98cc382d1e3de1cf461a7a85c33cbea7/tensorflow/compiler/jit">jit</a>/clone_constants_for_better_clustering.h)<br>Running optimization phase 9 <br>Running optimization pass: ClusterScopingPass  (<a href="https://github.com/tensorflow/tensorflow/tree/v2.9.0/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/v2.9.0/tensorflow/compiler/jit">jit</a>/cluster_scoping_pass.h)<br>Running optimization phase 10 <br>Running optimization pass: MarkForCompilationPass (compiler/jit/mark_for_compilation_pass.h)<br>Running optimization phase 12 <br>Running optimization pass: ForceXlaConstantsOnHostPass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/force_xla_constants_on_host_pass.h)<br>Running optimization phase 20 <br>Running optimization pass: IncreaseDynamismForAutoJitPass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/increase_dynamism_for_auto_jit_pass.h)<br>Running optimization phase 30 <br>Running optimization pass: PartiallyDeclusterPass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/partially_decluster_pass.h) <br>Running optimization phase 40 <br>Running optimization pass: ReportClusteringInfoPass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/report_clustering_info_pass.h) <br>Running optimization phase 50 <br>Running optimization pass: EncapsulateSubgraphsPass (<a href="https://github.com/tensorflow/tensorflow/tree/f1326e0c98cc382d1e3de1cf461a7a85c33cbea7/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/f1326e0c98cc382d1e3de1cf461a7a85c33cbea7/tensorflow/compiler/jit">jit</a>/encapsulate_subgraphs_pass.h)<br>Running optimization phase 60 <br>Running optimization pass: BuildXlaOpsPass (<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler">compiler</a>/<a href="https://github.com/tensorflow/tensorflow/tree/5dcfc51118817f27fad5246812d83e5dccdc5f72/tensorflow/compiler/jit">jit</a>/build_xla_ops_pass.h)<br><strong>Starting optimization of a group 3 — POST_PARTITIONING</strong><br>Running optimization phase 1 <br>Running optimization pass: MklLayoutRewritePass<br>XLA- before_optimizations, after_optimization, after 4 and 8 th</pre><h3><strong>References:</strong></h3><ol><li>Classifying CIFAR-10 with XLA, <a href="https://www.tensorflow.org/xla/tutorials/autoclustering_xla">https://www.tensorflow.org/xla/tutorials/autoclustering_xla</a></li><li>TensorFlow graph optimization with Grappler, <a href="https://www.tensorflow.org/guide/graph_optimization#:~:text=Grappler%20is%20the%20default%20graph,in%20graph%20mode%20(within%20tf">https://www.tensorflow.org/guide/graph_optimization#:~:text=Grappler%20is%20the%20default%20graph,in%20graph%20mode%20(within%20tf</a></li><li>XLA debug: <br><a href="https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/compiler/xla/debug_options_flags.cc">https://github.com/tensorflow/tensorflow/blob/v2.9.1/tensorflow/compiler/xla/debug_options_flags.cc</a></li><li>Nvidia Xla Best Practices , <a href="https://docs.nvidia.com/deeplearning/frameworks/tensorflow-user-guide/index.html#xla-best-practices">https://docs.nvidia.com/deeplearning/frameworks/tensorflow-user-guide/index.html#xla-best-practices</a></li><li>MLIR CodeGen for XLA <a href="https://www.tensorflow.org/mlir/xla_gpu_codegen">https://www.tensorflow.org/mlir/xla_gpu_codegen</a></li><li>DLVM: A MODERN COMPILER INFRASTRUCTURE FOR<br>DEEP LEARNING SYSTEMS,<a href="https://arxiv.org/pdf/1711.03016.pdf"> https://arxiv.org/pdf/1711.03016.pdf</a></li><li>APOLLO: AUTOMATIC PARTITION-BASED OPERATOR FUSION THROUGH LAYER BY LAYER OPTIMIZATION, <a href="https://proceedings.mlsys.org/paper/2022/file/069059b7ef840f0c74a814ec9237b6ec-Paper.pdf">https://proceedings.mlsys.org/paper/2022/file/069059b7ef840f0c74a814ec9237b6ec-Paper.pdf</a></li><li>‘mhlo’ Dialect, <a href="https://www.tensorflow.org/mlir/hlo_ops">https://www.tensorflow.org/mlir/hlo_ops</a></li><li>MLIR dialects , <a href="https://www.tensorflow.org/mlir/dialects">https://www.tensorflow.org/mlir/dialects</a></li><li><a href="https://mlir.llvm.org/docs/Dialects/Builtin/">https://mlir.llvm.org/docs/Dialects/Builtin/</a> , <a href="https://mlir.llvm.org/docs/LangRef/">https://mlir.llvm.org/docs/LangRef/</a></li><li>tensorflow/compiler/xla/service/hlo_instruction.h, tensorflow/compiler/xla/service/gpu/thunk.h, tensorflow/compiler/xla/service/hlo_opcode.h</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615191e96ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Multiview Stereo (MVS)]]></title>
            <link>https://whatdhack.medium.com/deep-learning-multiview-stereo-mvs-7f1e52f30f9?source=rss-5a25f604a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f1e52f30f9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[point-cloud]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[multi-view-stereo]]></category>
            <dc:creator><![CDATA[Subrata Goswami]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 17:32:31 GMT</pubDate>
            <atom:updated>2022-01-18T17:32:31.168Z</atom:updated>
            <content:encoded><![CDATA[<p>The goal of Multiview Stereo (MVS) is to generate a 3D point cloud or model from pictures taken from different locations. It is a problem with long history, and pre-dates Deep Learning by decades. It is also an area where geometric and photometric consistency and priors are extensively used. Given the long history, there are lot of terms that have been used over time. I have tried to described those is sufficient details in the Glossary section.</p><p>References [8, 24] and [23] provide good overview and a somewhat comprehensive list respectively. In the following, share my understanding of 2 Deep Learning based MVS architectures. Before delving into the details of these architecture, would like mention 2 other publications. PatchmatchNet [13] is the Deep Learning adaptation of the PatchMatch (described in the Glossary section ) method. COLMAP [6] is one of the early architectures, it is not deep learning based, but commonly used for comparison.</p><p><strong>GC-Net:</strong></p><p>The first architecture is <strong>GC-Net</strong> [20], it is one of the earliest end-to-end trainable network for stereo-vision MVS. The paper is well written and the architecture is fairly standard and easy to follow. The following 2 diagrams show the network used by the authors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*pFUJZqNI7uaxH1DwlyNDZQ.png" /><figcaption>Fig 1: Skydio GC-Net block diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*7Tg95qCXDtWvu9pDiLS9Tw.png" /><figcaption>Fig 2: Skydio GC-Net layers.</figcaption></figure><p>The features are generated by 2D convolution network as is the standard. For each stereo image, the network forms a cost volume (see Glossary section for how cost volumes are constructed) of shape <em>height×width×(max disparity + 1)×feature size</em>. This is achieved by concatenating each unary feature with their corresponding unary from the opposite stereo image across each disparity level, and packing these into 4D volume. Hence, 2 branches are visible in the block diagram above. Regularization is commonly used to smooth out noise and produce better results. Hence it is applied to the cost volume. In the architecture, regularization was implemented with 3D convolution, hence learnt instead of using a hand crafted construct. The regularization network consists of 4 levels of sub-sampling through blocks of <em>3D convolution+batch-norm +relu</em> (e.g. layers 21,24,27, and 30 in the figure above ). The 1/32 dimension feature is then up-sampled to the original shape in 5 steps. Each up-sample block is composed of 1 transpose convolution whose output is summed with the convolution feature of the same level, hence same shape. For example, layer 36 is the penultimate transpose convolution layer and layer 20 is the output from the first down sampled block. The residual connection helps in preserving resolution. The authors use a <em>soft argmin</em> for differentiability and sub-pixel accuracy. The <em>soft argmin</em>, unlike <em>argmin</em> is an weighted average, hence could be inaccurate for multi-modal distribution. The authors postulated that the regularization network would prevent a multi-modal distribution. The loss used is a L1 loss of disparity (e.g. average of absolute value of difference in depth between the network output and label).</p><p>The authors used synthetic data to pre-train their network and then fine tune and evaluate on the on the KITTI 2012 and 2015 stereo datasets.</p><p><strong>PatchMatch-RL:</strong></p><p><strong>PatchMatch-RL MVS</strong> [1] is a very recent paper that was orally presented in ICCV 2021. The paper is harder to follow, which is probably attributable to some extent to the architecture being more complex., The authors probably could have provided more details to tie various parts of the architecture better. The following figure shows their architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQytO7fklG5NAtb8G56_hw.png" /><figcaption>Fig 3: PatchMatch-RL MVS [1]</figcaption></figure><p>In multi-image MVS, usually one of the images of the scene is taken as reference and the rest as source images. When there are many images of a scene, only a subset of good ( by some criteria) is selected as source images for 3D point cloud determination. The view selection probability is per pixel and is realized by a MLP that uses geometric priors and feature correlation. The geometric priors used are Triangulation Prior, Resolution Prior and Incident Prior. The following picture shows these 3 priors. Triangulation Prior forces selection of source images that have sufficient baseline and hence different angle of view with respect to the reference image. Resolution Prior forces selection of images that have similar size and shape for patches. This implies preferences for images not taken at extreme distance and angles. Incident prior forces cameras to be in front .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11oLwbdXWatyF9ma9S9D8g.png" /><figcaption>Figure 4: Geometric priors used [6]</figcaption></figure><p>The authors define the correlation value of the oriented point as the attention-aggregated group- wise correlation for matching feature vectors in the source image as shown by the equations in the following figure. In the figure, <em>h</em> stands for attention vector, implemented as a 1x1 convolution. σ is the Normal distribution. <em>W</em> is a squarish window of size <em>α</em> and dilation <em>β</em>. Group-wise correlation is obtained by taking the inner/dot production of the channel dimension after the channels have been evenly divided into number of groups [25].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkkZa9rVsnIoLtUOzzRD2w.png" /><figcaption>Fig 5: Correlation between reference and source images.</figcaption></figure><p>As the authors use FPN to obtain features at different levels, they use the oriented points and hidden state of the immediate coarser level for initialization. At the final level, 3D point cloud is obtained by fusion [9] (e.g. averaging ).</p><p>The randomness used in PatchMatch precludes ordinal relationship between neighbors (e.g. volume or graph). The PatchMatch part in the architecture is implemented by using Loopy Belief Propagation (see Glossary for a description) through RNN. The input to RNN are visibility-weighted feature correlation appended with a pairwise term. The pairwise term is also a smoothness enabler [26]. The outputs of RNN are the estimated regularized costs. The hidden state of RNN corresponds to the belief for each candidate. The best candidate for the next iteration is hard sampled by the regularized cost.</p><p>The <em>argmax</em> based hard selection part of view selection and PatchMatch makes the architecture non-differentiable and hence impossible to train end-to-end with techniques such as back-propagation. The authors use Reinforcement Learning (RL), REINFORCE (Monte-Carlo Policy Gradient ) [28] specifically, to train end-to-end. See Glossary for a brief description of REINFORCE algorithm. They use 2 agents — one scores views and the other scores PatchMatch candidates.</p><p>The authors evaluated against 2 data sets , Tanks &amp; Temples and ETH3D. The authors claim their architecture produced the best result at intermediate resolution of 5 cm, however falls short of hand-crafted traditional methods at lower resolutions.</p><p>The code is based on PyTorch Lightning, and for the most part follows the standard Deep Learning methodology — defines a loss and optimizes parameters through back-propagation. There is very little documentation and the variable names are cryptic. Training happens in a method called <em>run_and_log</em>. This method is eventually called by the <em>fit</em> method of PyTorch Lightning for back-propagation. The following shows the high level pseudo call stack for training.</p><pre>run_and_log(self, batch, batch_idx, train, log_prefix)<br>  inf_p, steps = self.forward(images, ...)<br>    cameras = MVSCamera(K, E, P, images.shape[-2:], ranges)<br>      feature_layers = self.feature_extractor(images)<br>        step(cameras, features, ...)<br>          view_iw = select_views(cameras, features, plane_map,...)<br>            view_ps, view_i = sample(valid_view_s, ....)         <br>          planes = select_plane(cameras, features, view_iw, ...)<br>            plane_ps, plane_i = sample(cost_volume, ...)<br>  gt_n = compute_normal_from_depth(cameras, gt_d, True)<br>  gt_p = normal_depth_to_plane(cameras, gt_n, gt_d)<br>  d_nll = (-d_probs * step_p_probs.log()).sum(0, keepdim=True)<br>  d_loss += resize_bhwc(d_nll, out_shape) # compute depth loss<br>  n_nll = -(d_probs * n_probs * step_p_probs.log()).sum(0,..)<br>  n_loss += resize_bhwc(n_nll, out_shape) # compute normal loss<br>  rs = plane_similarity(cameras, step_p, step_gp, d_sigma, n_sigma)<br>  g_is.append(resize_bhwc(rs, out_shape))<br>  g_t = torch.stack(g_is).sum(0)<br>  v_loss += g_t * resize_bhwc(v_nll, out_shape) # all future reward<br>  loss = d_loss + n_loss + vs_loss</pre><p><strong>Conclusion:</strong></p><p>MVS is considered one of the economical approaches for obtaining rich 3D point cloud with respect to other methods like LIDAR that require specialized and somewhat more expensive equipments. However, it is computationally intensive and suffers from ambiguities. The above are just a couple of examples of the works that have been going on for decades.</p><p><strong>Glossary:</strong></p><p><strong>View Selection</strong>, refers to picking only a subset of images for stereopsis. Although the word stereo means 2, in realty many more than 2 images are used.</p><p><strong>Geometric priors </strong>encourage the selection of views with<br>sufficient baseline (Triangulation Prior ), similar resolution (Resolution Prior ), and non-oblique viewing direction (Incident Prior ) [5].</p><p><strong>Pixelwise selection </strong>refers to independent choice of images per pixel. Improves<strong> </strong>over fixed pre-selection of images for all pixels by reducing sensitivity to noise, better completeness, handing major changes to viewpoint between images better. Also handles occlusion and illumination variations better [12].</p><p><strong>Plan-Sweep</strong> is a stack of planes at various depths parallel to a reference image. Each target image is projected to the reference image for each depth plane with homography producing a warped images. Reference image and each target image is then compared by some metrics (e.g. ZNCC). The most matched depth plane is chosen. See the following figure for a pictorial view. Also see [2] slide deck for a good overview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*n3NXISn2gcArZ501c4lJPg.png" /><figcaption>Figure 6: Plane-Sweep , from [2].</figcaption></figure><p><strong>PatchMatch</strong> conceptually is a matching algorithm between a patch in one image to the approximate nearest one in another image. The brute force approach for such matching is — <em>O(mM**2 ), </em>where <em>m</em> and M<em> </em>are the number of pixels in the patch and image respectively. The <em>M**2 </em>comes from having to look at every scaling of the target image as the images need not be of same scale. The algorithm is fairly simple with just 3 main steps as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*gZ3ePhC4duU9lletuTzwng.png" /><figcaption>Figure 7: PatchMatch algorithm (from [3])</figcaption></figure><p>The intuition behind the algorithm is that patches closer in source image are also closer in the target image. Hence, it is worthwhile to check if a nearby neighbor has a better match. If so, take that. Step <em>c</em> prevents the algorithm from getting stuck in a local minimum by exploring random patches in a concentric route. Step <em>b</em> and <em>c</em> are called propagate and perturb respectively. See [3] and [4] for great overview of the algorithm.</p><p><strong>Cost volume </strong>is a way to incorporate geometrical constrains and priors [20,21,22] into the DL MVS pipeline. The basic idea is to take one of the images of the same scene as reference and project the rest of the images into the reference at a range of expected depths. The (homography) projection is possible as camera intrinsic and extrinsic matrices for each of the images are made available in some way. This volume of HxWxD can be filled with a number of values that in some way represents the cost or discrepancy of a pixel in the reference image and other images.</p><p><strong>Regularization</strong> in the MVS context has similar meaning as in general ML context — prevent over fitting, address ill-posed problem, etc. Regularization can be considered a form of <em>a priori</em> constraint [22]. In the simplest form it is usually represented as minimization of |Az — y|² + λ|Pz|² , where both A and P, called stabilizing function, are linear. λ determines how much “regular” the solution should be.</p><p><strong>Depth map</strong> refers to the depth of each pixel of the reference image. Depth map can be directly projected to space by using extrinsic and intrinsic camera parameters to generate 3D point clouds.</p><p><strong>Pixel normal</strong> refers to a 3D plane in which the 3D point corresponding to a pixel in the reference image lies. This makes photometric values of corresponding regions/patches in two of more images of the same scene more similar through accommodation of perspective projection. In other words, the same 3D plane may not look similar in two images.</p><p><strong>Belief Propagation (BP)</strong> is a message-passing algorithm, where messages are defined as functions from nodes to their neighbors, so that the message <em>Mt→s(us)</em> represents, in words, “node <em>t’s</em> opinion of the [negative log of the] likelihood that node <em>s</em> has value <em>us</em>” [26, 27]. When implemented as an iterative algorithm, messages are updated according to a schedule, like PatchMatch, and messages on the right-hand side of update equation are those of the previous iteration, or those computed earlier in the current iteration. Messages are typically initialized to all-zero and at convergence is the estimate of the minimizer. <strong>Loopy Belief Propagation (LBP) </strong>is BP on a graph with loops or non-tree.</p><p><strong>REINFORCE</strong> (Monte-Carlo Policy Gradient) , there a many good literature/media on Reinforcement Learning [28,29, 30, 31, 32]. REINFORCE is a very popular policy gradient method, also known as Monte Carlo Policy Gradient. The algorithm samples a full trajectory ( hence Monte Carlo) , and then update the policy weights backwards. The algorithm is as follows.</p><pre># Policy gradient algorithms search for a local maximum of J(θ) by <br># gradient ascent in parameter,θ, space. <br># ∆θ = α∇θJ(θ)<br># ∇θπθ(s,a) = πθ(s,a) * ∇θπθ(s,a)/πθ(s, a) = πθ(s,a)∇θ log πθ(s,a)<br># ∇θ log πθ(s, a) is called score function<br># ∇θπθ(s,a)/πθ(s, a) is a likelihood ratio</pre><pre># Policy Gradient Theorem <br># ∇θJ(θ) = Eπθ [∇θ log πθ(s, a) Qπθ (s, a)]<br># J(θ) -&gt; objective function<br># Eπθ -&gt; Expectation over s and a. <br># The policy gradient theorem generalizes the likelihood<br># ratio approach to multi-step Markov Decision Processes (MDP) <br># and replaces instantaneous<br># reward r with long-term value Qπθ (s, a) or vt</pre><pre>def REINFORCE ():<br>Initialize θ arbitrarily <br># s-&gt; state, a -&gt; action , r -&gt; reward<br>  for  _ in episode {s1, a1,r2, …,sT−1, aT−1,rT } : # ∼ πθ <br>    for t in range (1, T − 1) :<br>      # uses the complete return value from time t, vt, as reward<br>      # samples expectation over state and action (hence stochastic)<br>      θ = θ + α∇θ log πθ(st , at)*vt <br>return θ</pre><p><strong>References:</strong></p><ol><li>PatchMatch-RL: Deep MVS With Pixelwise Depth, Normal, and Visibility, paper: <a href="https://openaccess.thecvf.com/content/ICCV2021/papers/Lee_PatchMatch-RL_Deep_MVS_With_Pixelwise_Depth_Normal_and_Visibility_ICCV_2021_paper.pdf">https://openaccess.thecvf.com/content/ICCV2021/papers/Lee_PatchMatch-RL_Deep_MVS_With_Pixelwise_Depth_Normal_and_Visibility_ICCV_2021_paper.pdf</a>, code: <a href="https://github.com/leejaeyong7/patchmatch-rl">https://github.com/leejaeyong7/patchmatch-rl</a>,</li><li>Plane-sweep <a href="https://www.uio.no/studier/emner/matnat/its/nedlagte-emner/UNIK4690/v16/forelesninger/lecture_8_3_multiple_view_stereo.pdf">https://www.uio.no/studier/emner/matnat/its/nedlagte-emner/UNIK4690/v16/forelesninger/lecture_8_3_multiple_view_stereo.pdf</a></li><li>The PatchMatch Randomized Matching Algorithm for Image Manipulation, <a href="http://www.connellybarnes.com/work/publications/2011_patchmatch_cacm.pdf">http://www.connellybarnes.com/work/publications/2011_patchmatch_cacm.pdf</a></li><li><a href="http://vis.berkeley.edu/courses/cs294-69-fa11/wiki/images/1/18/05-PatchMatch.pdf">http://vis.berkeley.edu/courses/cs294-69-fa11/wiki/images/1/18/05-PatchMatch.pdf</a></li><li>Deep Multi-View Stereo gone wild, <a href="https://arxiv.org/pdf/2104.15119.pdf">https://arxiv.org/pdf/2104.15119.pdf</a></li><li>Pixelwise View Selection for Unstructured Multi-View Stereo, <a href="https://demuc.de/papers/schoenberger2016mvs.pdf">https://demuc.de/papers/schoenberger2016mvs.pdf</a> ; <a href="https://github.com/colmap/colmap">https://github.com/colmap/colmap</a>.</li><li>Multi-view stereo, <a href="https://slazebni.cs.illinois.edu/spring19/lec19_multiview_stereo.pdf">https://slazebni.cs.illinois.edu/spring19/lec19_multiview_stereo.pdf</a></li><li>Deep Learning for Multi-view Stereo via Plane Sweep: A Survey, <a href="https://arxiv.org/pdf/2106.15328.pdf">https://arxiv.org/pdf/2106.15328.pdf</a></li><li>MVSNet: Depth Inference for Unstructured Multi-view Stereo, <a href="https://arxiv.org/pdf/1804.02505.pdf">https://arxiv.org/pdf/1804.02505.pdf</a></li><li>Recurrent MVSNet for High-resolution Multi-view Stereo Depth Inference, <a href="https://arxiv.org/pdf/1902.10556.pdf">https://arxiv.org/pdf/1902.10556.pdf</a></li><li>MVSCRF: Learning multi-view stereo with conditional random fields, <a href="https://openaccess.thecvf.com/content_ICCV_2019/papers/Xue_MVSCRF_Learning_Multi-View_Stereo_With_Conditional_Random_Fields_ICCV_2019_paper.pdf">https://openaccess.thecvf.com/content_ICCV_2019/papers/Xue_MVSCRF_Learning_Multi-View_Stereo_With_Conditional_Random_Fields_ICCV_2019_paper.pdf</a></li><li>PVSNet: Pixelwise Visibility-Aware Multi-View Stereo Network, <a href="https://arxiv.org/pdf/2007.07714.pdf">https://arxiv.org/pdf/2007.07714.pdf</a></li><li>PatchmatchNet: Learned multi-view patchmatch stereo, 2020, <a href="https://arxiv.org/abs/2012.01411">https://arxiv.org/abs/2012.01411</a></li><li>PatchMatch Based Joint View Selection and Depthmap Estimation, <a href="https://openaccess.thecvf.com/content_cvpr_2014/papers/Zheng_PatchMatch_Based_Joint_2014_CVPR_paper.pdf">https://openaccess.thecvf.com/content_cvpr_2014/papers/Zheng_PatchMatch_Based_Joint_2014_CVPR_paper.pdf</a></li><li>Dense Hybrid Recurrent Multi-view Stereo Net with Dynamic Consistency Checking, <a href="https://arxiv.org/pdf/2007.10872.pdf">https://arxiv.org/pdf/2007.10872.pdf</a></li><li>Zero-normalized cross-correlation (ZNCC), <a href="https://en.wikipedia.org/wiki/Cross-correlation">https://en.wikipedia.org/wiki/Cross-correlation</a></li><li>Guided Image Filtering, <a href="http://kaiminghe.com/eccv10/">http://kaiminghe.com/eccv10/</a></li><li>A Space-Sweep Approach to True Multi-Image Matching, <a href="https://www.ri.cmu.edu/pub_files/pub1/collins_robert_1996_1/collins_robert_1996_1.pdf">https://www.ri.cmu.edu/pub_files/pub1/collins_robert_1996_1/collins_robert_1996_1.pdf</a></li><li>Cost Volume Pyramid Based Depth Inference for Multi-View Stereo, <a href="https://arxiv.org/pdf/1912.08329.pdf">https://arxiv.org/pdf/1912.08329.pdf</a></li><li>End-to-End Learning of Geometry and Context for Deep Stereo Regression, <a href="https://arxiv.org/pdf/1703.04309.pdf">https://arxiv.org/pdf/1703.04309.pdf</a>, <a href="https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf">https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf</a></li><li>A Taxonomy and Evaluation of Dense Two-Frame<br>Stereo Correspondence Algorithms, <a href="https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf">https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf</a></li><li>Computational vision and regularization theory, file:///home/subrata/Downloads/317314a0.pdf</li><li>Awesome 3D reconstruction list, <a href="https://github.com/openMVG/awesome_3DReconstruction_list">https://github.com/openMVG/awesome_3DReconstruction_list</a></li><li>Multi-view stereo: A tutorial, <a href="https://carlos-hernandez.org/papers/fnt_mvs_2015.pdf">https://carlos-hernandez.org/papers/fnt_mvs_2015.pdf</a></li><li>Learning Inverse Depth Regression for Multi-View Stereo with Correlation Cost Volume, <a href="https://arxiv.org/pdf/1912.11746.pdf">https://arxiv.org/pdf/1912.11746.pdf</a></li><li>PMBP: PatchMatch Belief Propagation for Correspondence Field Estimation, <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2012/01/PMBP.pdf">https://www.microsoft.com/en-us/research/wp-content/uploads/2012/01/PMBP.pdf</a></li><li>Introduction to Loopy Belief Propagation, <a href="https://cseweb.ucsd.edu/classes/sp06/cse151/lectures/belief-propagation.pdf">https://cseweb.ucsd.edu/classes/sp06/cse151/lectures/belief-propagation.pdf</a></li><li><a href="http://www.cs.cmu.edu/~rsalakhu/10703/Lectures/Lecture_PG.pdf">http://www.cs.cmu.edu/~rsalakhu/10703/Lectures/Lecture_PG.pdf</a>Policy Gradient Theorem Explained — Reinforcement Learning, <a href="https://www.youtube.com/watch?v=cQfOQcpYRzE">https://www.youtube.com/watch?v=cQfOQcpYRzE</a></li><li>10703 Deep Reinforcement Learning and Control, <a href="http://www.cs.cmu.edu/~rsalakhu/10703/Lectures/Lecture_PG.pdf">http://www.cs.cmu.edu/~rsalakhu/10703/Lectures/Lecture_PG.pdf</a></li><li>Policy Gradient Methods for Reinforcement Learning with Function<br>Approximation, <a href="https://homes.cs.washington.edu/~todorov/courses/amath579/reading/PolicyGradient.pdf">https://homes.cs.washington.edu/~todorov/courses/amath579/reading/PolicyGradient.pdf</a></li><li>Reinforcement Learning: An Introduction, by <a href="https://www.google.com/search?client=ubuntu&amp;hs=eMH&amp;sa=X&amp;biw=2545&amp;bih=1296&amp;tbm=bks&amp;sxsrf=AOaemvJuJBYTDifLnJr8y_lCMc5tKCnEcg:1642449681376&amp;tbm=bks&amp;q=inauthor:%22Richard+S.+Sutton%22&amp;ved=2ahUKEwiTgsfuybn1AhVTJkQIHaapAm0Q9Ah6BAgFEAU">Richard S. Sutton</a>, ‎<a href="https://www.google.com/search?client=ubuntu&amp;hs=eMH&amp;sa=X&amp;biw=2545&amp;bih=1296&amp;tbm=bks&amp;sxsrf=AOaemvJuJBYTDifLnJr8y_lCMc5tKCnEcg:1642449681376&amp;tbm=bks&amp;q=inauthor:%22Andrew+G.+Barto%22&amp;ved=2ahUKEwiTgsfuybn1AhVTJkQIHaapAm0Q9Ah6BAgFEAY">Andrew G. Bart</a>o, The MIT Press, 2018.</li><li>Sample Efficient Reinforcement Learning with REINFORCE, <a href="https://web.stanford.edu/~boyd/papers/pdf/conv_reinforce_aaai_preprint_short.pdf">https://web.stanford.edu/~boyd/papers/pdf/conv_reinforce_aaai_preprint_short.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f1e52f30f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>