<?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 Maria Luize Pinheiro on Medium]]></title>
        <description><![CDATA[Stories by Maria Luize Pinheiro on Medium]]></description>
        <link>https://medium.com/@marialuize?source=rss-2c3323f55803------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*E1N57AxWbMcfwMir</url>
            <title>Stories by Maria Luize Pinheiro on Medium</title>
            <link>https://medium.com/@marialuize?source=rss-2c3323f55803------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:21:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marialuize/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[Fusing Sentinel-2 Spectral Indices on Cloud TPU v5e with TorchTPU and Pallas]]></title>
            <link>https://medium.com/@marialuize/fusing-sentinel-2-spectral-indices-on-cloud-tpu-v5e-with-torchtpu-and-pallas-4a9a6a67410c?source=rss-2c3323f55803------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a9a6a67410c</guid>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[torchtpusprint]]></category>
            <category><![CDATA[palla]]></category>
            <category><![CDATA[torchtpu]]></category>
            <dc:creator><![CDATA[Maria Luize Pinheiro]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 02:18:44 GMT</pubDate>
            <atom:updated>2026-11-26T02:18:44.409Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to memory-bound workloads on Cloud TPUs: comparing Eager PyTorch, </em><em>torch.compile(backend=&quot;tpu&quot;), and a custom 2D-tiled Pallas kernel via </em><em>torch.tpu.pallas.jax_op.</em></p><h3>1. The Problem: Why Spectral Indices Are Memory-Bound</h3><p>Considering that a full <strong>Sentinel-2 10m tile</strong> has 10980 × 10980 pixels (~120.5 million pixels). Computing two standard remote-sensing indices—<strong>NDVI</strong> and <strong>NDWI</strong>—from the Red (B04), Green (B03), and Near-Infrared (B08) bands takes very little math:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fj0Qy9r6UH2ID0MBPUWOVQ.png" /></figure><p>That is <strong>8 floating-point operations per pixel</strong>. In an ideal fused pass, we read 3 input bands and write 2 output indices (5 tensor accesses per pixel), giving an arithmetic intensity of:</p><ul><li><strong>float32 (4 bytes):</strong> 8 / (5 × 4) = 0.4 FLOPs/byte</li><li><strong>bfloat16 (2 bytes):</strong> 8/(5 × 2) = 0.8 FLOPs/byte</li></ul><p>On a Cloud TPU v5e (v5litepod-1, <strong>819 GB/s</strong> peak HBM bandwidth), this workload sits far on the left side of the roofline: performance is governed almost entirely by how efficiently we move data between <strong>HBM (High Bandwidth Memory)</strong> and <strong>VMEM (on-chip SRAM)</strong>, not by compute speed.</p><p>In eager PyTorch, each operation (sub, add, div, dtype casts) allocates intermediate tensors and round-trips them through HBM. Fusing both indices into a single pass eliminates those extra transfers.</p><blockquote><strong>Code, tests, benchmarks, and tutorial notebook: </strong><a href="https://github.com/MariaLuize/tpu-pallas-spectral-fusion">https://github.com/MariaLuize/tpu-pallas-spectral-fusion</a></blockquote><h3>2. Environment Setup on Cloud TPU v5e</h3><p>All experiments ran on a single-chip Cloud TPU v5e (v5litepod-1, 16 GB HBM, 16 MB VMEM) with Python 3.11, torch_tpu (torch 2.15.0), and jax 0.10.2:</p><pre>uv venv --python 3.11 .venv<br>source .venv/bin/activate</pre><pre>uv pip install torch_tpu --extra-index-url <a href="https://download.pytorch.org/whl/cpu">https://download.pytorch.org/whl/cpu</a><br>uv pip install &quot;jax[tpu]&quot; -f <a href="https://storage.googleapis.com/jax-releases/libtpu_releases.html">https://storage.googleapis.com/jax-releases/libtpu_releases.html</a><br>uv pip install -r requirements.txt</pre><p>Importing torch_tpu registers the native &quot;tpu&quot; device backend and exposes torch.tpu.pallas:</p><pre>import torch<br>import torch_tpu  # Registers the &#39;tpu&#39; device backend</pre><pre>device = torch.device(&quot;tpu&quot;)</pre><h3>3. Execution Modes: Eager vs. torch.compile(backend=&quot;tpu&quot;)</h3><p>To avoid precision loss or NaN/Inf on nodata (0.0) pixels when inputs are bfloat16, we upcast to float32 during the division and cast back to the original dtype:</p><pre>def compute_indices_eager(<br>    red: torch.Tensor,<br>    green: torch.Tensor,<br>    nir: torch.Tensor,<br>    eps: float = 1e-6,<br>) -&gt; tuple[torch.Tensor, torch.Tensor]:<br>    orig_dtype = red.dtype<br><br>    red_f32 = red.to(torch.float32)<br>    green_f32 = green.to(torch.float32)<br>    nir_f32 = nir.to(torch.float32)<br> <br>    ndvi = (nir_f32 - red_f32) / (nir_f32 + red_f32 + eps)<br>    ndwi = (green_f32 - nir_f32) / (green_f32 + nir_f32 + eps)<br><br>    return ndvi.to(orig_dtype), ndwi.to(orig_dtype)<br><br>compiled_fn = torch.compile(compute_indices_eager, backend=&quot;tpu&quot;)</pre><p>Two important behaviors stand out immediately when comparing these modes on 10980 × 10980:</p><ol><li><strong>In Eager mode, </strong><strong>bfloat16 is actually slower than </strong><strong>float32</strong> (21.71 ms vs. 16.04 ms). Even though bfloat16 tensors are half the size, the explicit .to(torch.float32) and .to(orig_dtype) casts trigger extra HBM reads and writes.</li><li><strong>torch.compile(backend=&quot;tpu&quot;) fuses the entire graph (</strong>casts and arithmetic happen in on-chip registers) dropping bfloat16 latency from <strong>21.71 ms to 2.10 ms</strong> (10.33x speedup, 573.5 GB/s).</li><li><strong>Static shapes and compilation caching matter:</strong> Warming up before timing and keeping shapes static gave a <strong>97.6% compilation cache hit rate</strong> (2013 / 2061 requests, 0 dynamic-shape misses).</li></ol><h3>4. Writing a Custom 2D-Tiled Pallas Kernel with torch.tpu.pallas.jax_op</h3><p>TorchTPU provides @torch.tpu.pallas.jax_op(&quot;namespace::op_name&quot;), which wraps a JAX function (calling pl.pallas_call) and registers it as a native torch.library.custom_op. It inspects the function&#39;s type annotations to generate the PyTorch schema and automatically treat scalar parameters (int, float) as static arguments.</p><p>Here is the 2D-tiled kernel:</p><pre>import functools<br>import jax<br>import jax.numpy as jnp<br>from jax.experimental import pallas as pl<br>from jax.experimental.pallas import tpu as pltpu<br>import torch<br>import torch_tpu<br><br>def _fused_spectral_indices_2d_kernel(<br>    red_ref, green_ref, nir_ref, out_ndvi_ref, out_ndwi_ref, *, eps: float<br>):<br>    &quot;&quot;&quot;Runs on a single (block_h, block_w) tile inside TPU VMEM.&quot;&quot;&quot;<br>    red = red_ref[...]<br>    green = green_ref[...]<br>    nir = nir_ref[...]<br>    orig_dtype = red.dtype   # Upcast inside the VPU (no HBM traffic for float32 intermediates)<br>    <br>    red_f32 = red.astype(jnp.float32)<br>    green_f32 = green.astype(jnp.float32)<br>    nir_f32 = nir.astype(jnp.float32)<br>    ndvi = (nir_f32 - red_f32) / (nir_f32 + red_f32 + eps)<br>    ndwi = (green_f32 - nir_f32) / (green_f32 + nir_f32 + eps)<br>    out_ndvi_ref[...] = ndvi.astype(orig_dtype)<br>    out_ndwi_ref[...] = ndwi.astype(orig_dtype)<br><br>@torch.tpu.pallas.jax_op(&quot;spectral::fused_ndvi_ndwi&quot;)<br>def _fused_spectral_indices_op(<br>    red: jax.Array,<br>    green: jax.Array,<br>    nir: jax.Array,<br>    block_h: int = 512,<br>    block_w: int = 512,<br>    eps: float = 1e-6,<br>) -&gt; tuple[jax.Array, jax.Array]:<br>    h, w = red.shape<br>    grid = (pl.cdiv(h, block_h), pl.cdiv(w, block_w))<br>    out_shape = (<br>        jax.ShapeDtypeStruct((h, w), red.dtype),<br>        jax.ShapeDtypeStruct((h, w), red.dtype),<br>    )<br>    block_spec = pl.BlockSpec(<br>        block_shape=(block_h, block_w),<br>        index_map=lambda i, j: (i, j),<br>    )<br>    kernel_fn = functools.partial(_fused_spectral_indices_2d_kernel, eps=eps)<br>    compiler_params = pltpu.CompilerParams(<br>        dimension_semantics=(&quot;parallel&quot;, &quot;parallel&quot;)<br>    )<br>    return pl.pallas_call(<br>        kernel_fn,<br>        out_shape=out_shape,<br>        in_specs=[block_spec, block_spec, block_spec],<br>        out_specs=(block_spec, block_spec),<br>        grid=grid,<br>        compiler_params=compiler_params,<br>    )(red, green, nir)</pre><p>Before calling _fused_spectral_indices_op, we call .contiguous() on each band so the TPU does not pay for view relayouts.</p><h3>5. Two Practical Lessons That Doubled Performance</h3><h3>Lesson 1: Avoid Eager Padding Outside the Kernel (F.pad vs. pl.cdiv)</h3><p>Because 10980 is not divisible by 128, 256, or 512, the first version (v1) padded all three input bands with torch.nn.functional.pad before calling Pallas and sliced the outputs afterward.</p><p>That looked clean, but it <strong>cut effective bandwidth in half</strong> on 10980 × 10980:</p><ul><li>On 8192 × 8192 (no padding needed): 570.4 GB/s (float32).</li><li>On 10980 × 10980 (with eager F.pad): 288.5 GB/s (8.358 ms).</li></ul><p>The reason is straightforward: eager F.pad ran 3 extra full-tile HBM reads and 3 full-tile HBM writes before the kernel even started. Replacing F.pad with grid = (pl.cdiv(h, block_h), pl.cdiv(w, block_w)) lets Mosaic TPU handle partial boundary tiles directly in hardware DMA, and adding dimension_semantics=(&quot;parallel&quot;, &quot;parallel&quot;) allows the compiler to double-buffer independent tiles. Latency immediately dropped by <strong>more than 2x</strong>.</p><h3>Lesson 2: Size Tiles to VMEM (Including Double-Buffering)</h3><p>Larger tiles reduce per-tile DMA overhead (128 × 128 → 512 × 512 nearly doubled bandwidth), but VMEM on TPU v5e is <strong>16 MB</strong>.</p><p>When I tried 512 × 1024 in float32, it hit RESOURCE_EXHAUSTED. Counting the VMEM footprint explains why:</p><ul><li>5 tiles (3 inputs + 2 outputs) × 512 × 1024 × 4 bytes = <strong>10 MB</strong></li><li>× 2 for async DMA double-buffering = <strong>20 MB &gt; 16 MB VMEM</strong></li></ul><p>Using <strong>256 × 1024</strong> keeps the double-buffered footprint at <strong>10 MB</strong> (fitting comfortably in 16 MB VMEM) while preserving wide, contiguous DMA transfers along the minor dimension.</p><h3>6. Benchmark Results (Cloud TPU v5e, v5litepod-1)</h3><h3>Full Sentinel-2 Tile (10980 × 10980): The Before vs. After</h3><pre><br><br>|                Dtype | Eager | Pallas v1 (`F.pad`, `512×512`) | Pallas v2 (`pl.cdiv`, `256×1024`) | `torch.compile`                |<br>|------------------------------------------------------------------------------------------------------------------------------------|<br>| float32  | 16.037 ms (150.4 GB/s)| 8.358 ms (288.5 GB/s, 1.92x) | **3.931 ms (613.4 GB/s, 4.08x)** | 3.999 ms (602.9 GB/s, 4.01x)  |<br>| bfloat16 | 21.712 ms (55.5 GB/s) | 4.329 ms (278.5 GB/s, 5.02x) | **2.175 ms (554.3 GB/s, 9.98x)** | 2.102 ms (573.5 GB/s, 10.33x) |<br></pre><p>On 10980 × 10980 float32, Pallas (256×1024) reaches <strong>613.4 GB/s (~75% of TPU v5e&#39;s 819 GB/s theoretical peak HBM)</strong> and edges out torch.compile. In bfloat16, both fused approaches deliver <strong>~10x</strong> speedup over Eager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKxlnjn285cLsMVsz1-YDQ.png" /><figcaption>Effective HBM bandwidth (GB/s) across tile shapes and methods compared against TPU v5e’s 819 GB/s HBM ceiling.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gtvCfcmUzBVwCq6JH1osw.png" /><figcaption>Median latency (± std) and speedup vs. Eager on <em>10980 × 10980</em>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjEc5AUkV9SdeGDKNKcuhw.png" /><figcaption>Roofline plot showing NDVI+NDWI firmly in the memory-bound region (<em>0.4–0.8 FLOP/byte</em>), with Pallas <em>256×1024</em> and <em>torch.compile</em> approaching the HBM roof.</figcaption></figure><h3>7. Verifying Fusion with torch.profiler and XProf</h3><p>We profiled each mode separately using torch.profiler (after pre-compiling one warmup step so compilation doesn&#39;t appear in steady-state traces):</p><pre>with profile(<br>    activities=[ProfilerActivity.CPU, ProfilerActivity.TPU],<br>    schedule=schedule(wait=1, warmup=3, active=3, repeat=1),<br>    on_trace_ready=torch.profiler.tensorboard_trace_handler(str(run_dir)),<br>    record_shapes=True,<br>    profile_memory=True,<br>) as prof:<br>    for step in range(7):<br>        with record_function(f&quot;{name}_step_{step}&quot;):<br>            _ = fn(*inputs)<br>            torch.accelerator.synchronize()<br>        prof.step()</pre><p>Opening the exported .pt.trace.json traces in Perfetto UI makes the root cause immediately visible. In Eager mode, one 10980 × 10980 step (21.56 ms) dispatches 13 separate HBM-bound kernels—five of which are just dtype conversions (%to_copy). In Pallas mode, those 13 kernels collapse into a single tpu_custom_call per step, completing <strong>three full steps in 6.40 ms</strong>—less than a third of the time Eager needs for just one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9pU-ykObDuXeKyzMRN1_A.png" /><figcaption><em>Eager </em><em>bfloat16 trace on </em><em>10980 × 10980 (Perfetto UI). A </em><strong><em>single step takes 21.56 ms</em></strong><em> and fragments into </em><strong><em>13 sequential TPU ops</em></strong><em>: 3× </em><em>bf16 → f32 casts (</em><em>%to_copy), 4 ops for NDVI (</em><em>%sub, </em><em>%add, </em><em>%broadcast_add_fusion, </em><em>%div), 4 ops for NDWI, and 2× </em><em>f32 → bf16 casts, each reading from and writing back to HBM.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wsa269s6O1wTf2yzXhi28Q.png" /><figcaption><em>Custom Pallas </em><em>bfloat16 trace on </em><em>10980 × 10980 (Perfetto UI). </em><strong><em>All three active steps together take just 6.40 ms</em></strong><em> (~2.1 ms/step). Each step collapses into a single fused TPU kernel (</em><em>%_fused_spectral_indices_op.1), keeping all </em><em>float32 upcasting and arithmetic inside VMEM/VPU registers.</em></figcaption></figure><blockquote>Eager mode splits each step into multiple sequential element-wise ops and casts; Pallas collapses the entire computation into a single fused kernel operating on VMEM tiles.</blockquote><h3>Summary</h3><ul><li><strong>Start with the roofline:</strong> When arithmetic intensity is &lt; 1 FLOP/byte, every extra HBM round-trip dominates runtime.</li><li><strong>Don’t mix eager casts with </strong><strong>bfloat16:</strong> Always fuse upcasting into torch.compile or your custom kernel so float32 intermediates stay in VPU registers.</li><li><strong>Let Mosaic TPU handle boundaries:</strong> pl.cdiv + dimension_semantics=(&quot;parallel&quot;, &quot;parallel&quot;) avoids costly eager F.pad copies on real-world non-power-of-two shapes like 10980 × 10980.</li><li><strong>Account for double-buffering in VMEM:</strong> Multiply your tile footprint by 2 when sizing blocks for TPU v5e’s 16 MB VMEM.</li></ul><p>#TorchTPUSprint #JAX #Pallas #TorchTPU</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a9a6a67410c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimize the memory usage by converting Tensors from Float to Byte]]></title>
            <link>https://medium.com/@marialuize/how-to-optimize-the-memory-usage-by-converting-tensors-from-float-to-byte-f7aea8b62774?source=rss-2c3323f55803------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7aea8b62774</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Maria Luize Pinheiro]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 16:43:05 GMT</pubDate>
            <atom:updated>2024-10-23T16:53:36.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Lena Forsén used in many image processing experiments" src="https://cdn-images-1.medium.com/max/512/1*gUoANPVUnpV-5hNg2HRX5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*0nQu5zcyLLPEDeZcnfpS5Q.png" /><figcaption>Lena Forsén used in many image processing experiments, and its version on 8 bits.</figcaption></figure><p>Converting TensorFlow tensors from float to byte can offer several advantages. Primarily, it significantly reduces the model size, which is crucial for deploying machine learning models on devices with limited storage or memory, such as mobile phones and embedded systems (and my computer). This reduction in size also leads to faster inference times due to decreased data transfer and memory access. Additionally, byte-sized tensors consume less bandwidth, making them more efficient for transmission and deployment in environments with limited network connectivity. This conversion can be particularly beneficial for applications like image classification, object detection, and speech recognition, where models can be optimized for size and speed without significant loss of accuracy.</p><p>There are a few reasons why TensorFlow defaults to using float (specifically tf.float32) as the data type for tensors:</p><ul><li><strong>Precision:</strong> Floats can represent a wide range of values, including fractional numbers, which is crucial for many machine learning applications. Complex mathematical operations, like those used in neural networks, often require high precision to avoid rounding errors that can accumulate and affect the final result.</li><li><strong>Hardware compatibility:</strong> Most modern GPUs and CPUs are optimized for floating-point operations, which speeds up training and inference of models. Using tf.float32 ensures that TensorFlow can take full advantage of the available hardware.</li><li><strong>Convenience:</strong> In many cases, the input data for machine learning models is already in float format (e.g., images with pixel values normalized between 0 and 1). Using float as the default simplifies the process of loading and preprocessing data.</li></ul><p>However, it’s important to remember that:</p><ul><li>Higher precision isn’t always necessary. In some cases, using lower-precision data types like tf.float16 or even integers can be sufficient and provide benefits in terms of performance and memory usage.</li></ul><p>In my case, by using satellite data converted to 8 bits only (that means from 0 to 255), this huge quantity of spectral information is not necessary.</p><p>Code to convert:</p><pre>def serialize_example_byte(patch_mosaic, patch_supervised):<br>    features = {<br>        &#39;patch_mosaic&#39;: tf.train.Feature(bytes_list=tf.train.BytesList(value= [tf.io.serialize_tensor(patch_mosaic.flatten()).numpy()])),<br>        &#39;patch_supervised&#39;: tf.train.Feature(bytes_list=tf.train.BytesList(value= [tf.io.serialize_tensor(patch_supervised.flatten()).numpy()]))<br>    }<br>    example_proto = tf.train.Example(features=tf.train.Features(feature=features))<br>    return example_proto.SerializeToString()<br><br>def write_tfrecord_byte(patch_mosaic,patch_supervised, filename):<br>    with tf.io.TFRecordWriter(filename, options=tf.io.TFRecordOptions(compression_type=&#39;GZIP&#39;)) as writer:<br>        serialized_example_byte = serialize_example_byte(patch_mosaic, patch_supervised)<br>        writer.write(serialized_example_byte)</pre><pre>def create_tfrecord_dataset_byte(mosaic_list, supervised_list, desired_dims, channels, patch_step, case, version):<br>    if len(mosaic_list) != len(supervised_list):<br>        return<br><br>    label_counter = 0<br>    counter_all = 0<br>    for index in range(len(mosaic_list)):<br>        with rasterio.open(supervised_list[index], &#39;r&#39;) as supervised:    <br>            supervised_arr = supervised.read()<br>        with rasterio.open(mosaic_list[index], &#39;r&#39;) as mosaic:    <br>            mosaic_arr = mosaic.read()<br><br>        mosaic_arr     = np.array(mosaic_arr[[0, 2, 3, 4, 5], :, :])#.astype(np.float32) #ignorar segunda banda, banda BLUE PARA MOSAICO V2<br>        sample_concat  = np.concatenate((mosaic_arr,supervised_arr), axis = 0)<br><br>        if (sample_concat.shape[1]&lt;desired_dims) or (sample_concat.shape[2]&lt;desired_dims):<br>            continue<br>        patches         = patchify(sample_concat, (channels, desired_dims, desired_dims), patch_step)<br>        dim             = patches.shape[1]*patches.shape[2]<br>        patch_reshaped  = patches.reshape((1, dim, channels, desired_dims, desired_dims)) # concat effect, now is a big array of patches.shape[1]*patches.shape[2]<br>        patch_organized = np.transpose(patch_reshaped[0], [0,2,3,1])<br>        patch_mosaic    = patch_organized[..., :5]<br>        patch_supervised = patch_organized[...,5:]<br>    <br>        for idx, patch in enumerate(patch_supervised):<br>            cur = np.transpose(patch, [2,0,1])<br>            counter_all = counter_all+1<br>            if 1 in patch:<br>                label_counter=label_counter+1<br>        creatDirectory(f&#39;train_test/TFRecords_byte/{case}/v{version}&#39;)<br>     <br>        geometry_id = extract_number_from_lzw(mosaic_list[index])<br>        glob_tfrec  = f&#39;train_test/TFRecords_byte/{case}/v{version}/dataset_byte_{case}_{str(geometry_id)}_*&#39;<br>        tfrecords = sorted(tf.io.gfile.glob(glob_tfrec), key=lambda x: int(x.split(&#39;_&#39;)[-1].split(&#39;.&#39;)[0]))<br>        patches_size = patch_organized.shape[0]<br>        <br>        if len(tfrecords) &gt; 0:<br>            files_patch_size = 0<br>            for file_path in tfrecords:<br>                curr_size = extract_number_from_filename(file_path)<br>                files_patch_size = curr_size if curr_size &gt; files_patch_size else files_patch_size<br>            if (files_patch_size == patches_size):<br>                print(f&#39;Total patch generated {files_patch_size}. Unnecessery to generate new TFRecords for index: {index} \n\n&#39;)<br>                continue  <br>        else:<br>            step = 500            <br>            with tf.device(&#39;CPU&#39;):<br>                if (patch_organized.shape[0]&gt;step):<br>                    remain = int(patch_organized.shape[0]%step)<br>                    for i in range(step, patch_organized.shape[0], step):<br>                        print(f&#39;{index} in parts {i}&#39;)<br>       <br>                        name_tfrec = f&#39;~PATH_TFRecords_byte/{case}/v{version}/dataset_byte_{case}_&#39;+str(index)+&#39;_&#39;+str(i)+&#39;.tfrecord.gz&#39;<br>                        write_tfrecord_byte(patch_mosaic[i-step:i], patch_supervised[i-step:i], name_tfrec)<br><br>                    print(f&#39;remain {i+remain}&#39;)<br>                    name_tfrec = f&#39;~PATH_TFRecords_byte/TFRecords_byte/{case}/v{version}/dataset_byte_{case}_&#39;+str(index)+&#39;_&#39;+str(i+remain)+&#39;.tfrecord.gz&#39;<br>                    write_tfrecord_byte(patch_mosaic[i:], patch_supervised[i:], name_tfrec)<br>                else:                             <br>                    name_tfrec = f&#39;~PATH_TFRecords_byte/{case}/v{version}/dataset_byte_{case}_&#39;+str(index)+&#39;_&#39;+str(patch_organized.shape[0])+&#39;.tfrecord.gz&#39;<br>                    write_tfrecord_byte(patch_mosaic, patch_supervised, name_tfrec)<br><br>    return label_counter,counter_all</pre><p>The code focuses on processing pairs of images: one containing multispectral data (like different wavelengths of light captured by the satellite) and the other with corresponding labels or annotations. It starts by reading these images and cleverly extracts relevant information, like specific spectral bands. Then, it merges these data sources and slices them into smaller, manageable chunks called patches. These patches are like individual puzzle pieces that, when combined, represent the bigger picture. The code then meticulously organizes these patches and saves them into a specialized format called TFRecords.</p><p>This format is optimized for TensorFlow, a popular machine learning framework, ensuring efficient data loading and processing during model training. The code even includes checks to prevent redundant processing, ensuring that existing TFRecords are reused, saving time and resources. This snippet provides a glimpse into the intricate world of data preparation for machine learning, highlighting how raw satellite imagery is transformed into a format readily consumed by powerful algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7aea8b62774" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>