<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Technical ramblings</title>
<link>https://blog.rahul.onl/</link>
<atom:link href="https://blog.rahul.onl/index.xml" rel="self" type="application/rss+xml"/>
<description>Notes on systems, Rust, Python and running AI workloads on Intel GPUs.</description>
<generator>quarto-1.10.18</generator>
<lastBuildDate>Sun, 16 Aug 2026 07:00:00 GMT</lastBuildDate>
<item>
  <title>Qwen3.8-27B on Intel Arc Pro: two cards, near four-card speed</title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2026-08-16-qwen38-27b-arc-pro-sglang.html</link>
  <description><![CDATA[ 






<p>Qwen3.8-27B decodes at <strong>37.8 tokens per second on two Intel Arc Pro B65 cards</strong>. The official FP8 checkpoint on <strong>four</strong> cards manages 41.4. Give the same four-bit build all four cards and it reaches <strong>52.1 tok/s</strong>. Halving the hardware is the result I care about most here, and it came out of a decision about quantization.</p>
<p>I wanted <a href="https://huggingface.co/Qwen/Qwen3.8-27B">Qwen3.8-27B</a> as the local backend for coding agents: good at code, useful at long context, small enough to run on a few GPUs. Local agents make latency personal. A slow token is not a number in a benchmark, it is an interruption while you are editing a file, searching a repository, or waiting on a tool call.</p>
<p>Getting there took longer than expected. The model is dense, multimodal, and mostly built from Gated DeltaNet layers. It has a multi-token-prediction head, a vision tower, and enough different execution regimes that a change which looks great in a standalone kernel can vanish, or turn into a regression, once it is inside the server.</p>
<p>None of what worked was dramatic. The largest four-bit step came from a library primitive that already existed. Group size 128 beat group size 32. A cost I had written off as fixed host overhead turned out to be dense device work. And the 48 DeltaNet layers I expected to dominate decode were not where most of the time went.</p>
<p>This is independent work I did in my free time on hardware available to me. It is not an Intel release or an official Intel performance result. Intel XPU support has been arriving quickly in SGLang and the surrounding stack, so the job here was to optimize this particular model and add the model-specific pieces missing from the version I used. Before applying anything described below, check whether current upstream already has it.</p>
<blockquote class="blockquote">
<p><strong>Scope of the numbers:</strong> every measured Qwen3.8 result here is on Intel Arc Pro B65 GPUs. The B70 section is an estimate, clearly marked, not a Qwen3.8 measurement. “Decode tok/s” means <code>1000 / TPOT</code> at the stated context and concurrency; it is not the benchmark’s output-throughput field, which folds time-to-first-token into the same wall-clock interval.</p>
</blockquote>
<section id="running-it" class="level2">
<h2 class="anchored" data-anchor-id="running-it">Running it</h2>
<p>If you only want the model serving, this is the setup I use daily: four Arc Pro B65 cards at tensor parallelism 4, the model’s full 256K context, and enough room configured for several requests in flight at once. A single stream decodes at 52.1 tok/s on an 8K prompt, and token-to-token latency stays flat as the context fills.</p>
<p>The weights are at <a href="https://huggingface.co/ulkaa/Qwen3.8-27B-AWQ-INT4"><code>ulkaa/Qwen3.8-27B-AWQ-INT4</code></a> and the pinned serving image is on Docker Hub as <a href="https://hub.docker.com/r/rahulunair/sglang-xpu"><code>rahulunair/sglang-xpu</code></a>, tag <code>qwen3.8-27b-20260816</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">docker</span> run <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--rm</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--device</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>/dev/dri <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-v</span> /dev/dri:/dev/dri <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--group-add</span> video <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--group-add</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">$(</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getent</span> group render <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-d:</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-f3</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">)</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--cap-add</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SYS_PTRACE <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--security-opt</span> seccomp=unconfined <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--ipc</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>host <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--shm-size</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>64g <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--ulimit</span> memlock=-1 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-p</span> 30000:30000 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-v</span> /path/to/Qwen3.8-27B-AWQ-INT4:/model:ro <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-e</span> ONEAPI_DEVICE_SELECTOR=level_zero:gpu <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-7">  rahulunair/sglang-xpu:qwen3.8-27b-20260816 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-8">  python <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-m</span> sglang.launch_server <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--model-path</span> /model <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--device</span> xpu <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--tp-size</span> 4 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--attention-backend</span> intel_xpu <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--page-size</span> 64 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--context-length</span> 262144 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--chunked-prefill-size</span> 4096 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--mem-fraction-static</span> 0.85 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb1-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--cuda-graph-config</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'{"decode":{"backend":"full","bs":[1,2,4,8]},"prefill":{"backend":"disabled"}}'</span></span></code></pre></div></div>
<p>Use <code>--tp-size 2</code> on a two-card machine, where the same prompt decodes at 37.8 tok/s. Leaving <code>--max-total-tokens</code> unset lets the server size the KV pool from the memory it finds; pin it lower if you are sharing the cards with something else. The <code>SYS_PTRACE</code> and unconfined seccomp flags are there for one optional fast collective I describe later; drop both and the model still runs normally.</p>
<p>Do check current upstream SGLang and Intel images before reaching for a pinned image. A pinned release is useful for reproducing this article; it is not a reason to keep that patch set around forever.</p>
<p>The rest of this post is how I got there.</p>
</section>
<section id="what-are-we-actually-running" class="level2">
<h2 class="anchored" data-anchor-id="what-are-we-actually-running">What are we actually running?</h2>
<p>Qwen3.8-27B has 64 decoder layers. Forty-eight use Gated DeltaNet, a linear attention recurrence, and 16 use full attention. It is dense rather than mixture-of-experts, so almost every large text-model weight participates in every decode step. The checkpoint also carries a 27-layer vision tower and a multi-token-prediction head.</p>
<p>That shape splits the problem into two regimes:</p>
<ul>
<li><strong>Decode at batch one</strong> has very little arithmetic reuse. It is mostly a question of how many bytes must cross memory for every new token, plus small kernels, layer boundaries, and collectives.</li>
<li><strong>Prefill</strong> turns the same projections into larger matrix operations and adds context-growing attention work. Compute throughput and tile efficiency matter much more here.</li>
</ul>
<p>I kept two checkpoints working throughout.</p>
<ol type="1">
<li>The official <a href="https://huggingface.co/Qwen/Qwen3.8-27B-FP8">Qwen3.8-27B-FP8</a> checkpoint, my reference while getting everything working.</li>
<li>My <a href="https://huggingface.co/ulkaa/Qwen3.8-27B-AWQ-INT4">Qwen3.8-27B AWQ W4A16</a> checkpoint: 18.2 GiB, asymmetric group-128 quantization, BF16 vision tower and MTP tensors preserved.</li>
</ol>
<p>“FP8 model” and “AWQ model” describe how a checkpoint stores its weights, not necessarily the instruction that runs every projection. The runtime may dequantize into BF16, keep an extra signed-INT8 copy for decode, or dispatch an actual four-bit primitive. Keeping storage precision, activation precision, and selected kernel separate in my head avoided a lot of confusion.</p>
<p>These are the final runs. Output was coherent, graph replay and the expected fast paths were active, and I used the second run of each shape. Earlier numbers helped me debug the model but are not useful baselines.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 11%">
<col style="width: 14%">
<col style="width: 14%">
<col style="width: 14%">
<col style="width: 14%">
<col style="width: 14%">
<col style="width: 14%">
</colgroup>
<thead>
<tr class="header">
<th>model and setup</th>
<th style="text-align: right;">GPUs / TP</th>
<th style="text-align: right;">input / output</th>
<th style="text-align: right;">TTFT</th>
<th style="text-align: right;">prefill, TTFT-derived</th>
<th style="text-align: right;">TPOT</th>
<th style="text-align: right;">decode</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>official FP8, optimized dense decode setup</td>
<td style="text-align: right;">4x B65 / TP4</td>
<td style="text-align: right;">8K / 1K</td>
<td style="text-align: right;">2,313 ms</td>
<td style="text-align: right;">3,542 tok/s</td>
<td style="text-align: right;">24.17 ms</td>
<td style="text-align: right;"><strong>41.4 tok/s</strong></td>
</tr>
<tr class="even">
<td>AWQ group 128, oneDNN W4A16</td>
<td style="text-align: right;">2x B65 / TP2</td>
<td style="text-align: right;">8K / 1K</td>
<td style="text-align: right;">4,479 ms</td>
<td style="text-align: right;">1,829 tok/s</td>
<td style="text-align: right;">26.44 ms</td>
<td style="text-align: right;"><strong>37.8 tok/s</strong></td>
</tr>
<tr class="odd">
<td>AWQ group 128, oneDNN W4A16</td>
<td style="text-align: right;">4x B65 / TP4</td>
<td style="text-align: right;">8K / 1K</td>
<td style="text-align: right;">2,749 ms</td>
<td style="text-align: right;">2,980 tok/s</td>
<td style="text-align: right;">19.20 ms</td>
<td style="text-align: right;"><strong>52.1 tok/s</strong></td>
</tr>
</tbody>
</table>
<p><em>These are complete setups, not a one-change-at-a-time comparison: graph capture on, concurrency 1, second run, roughly 9K context at the end of decode.</em></p>
<p>The first two rows are the ones I keep coming back to. Two cards running my four-bit build land at 37.8 tok/s against 41.4 for the official checkpoint on four. The two rows use different checkpoint formats and different code paths, so an efficiency percentage between them would mean very little. What it does tell me is what this workload costs in hardware: two cards now give me the interactive feel I was getting from four.</p>
<p>The official FP8 checkpoint stays useful. It is the standard model, it works in the release image, and it helped me separate real model behaviour from bugs in my own quantization pipeline.</p>
</section>
<section id="before-writing-a-kernel-do-the-boring-math" class="level2">
<h2 class="anchored" data-anchor-id="before-writing-a-kernel-do-the-boring-math">Before writing a kernel, do the boring math</h2>
<p>The first question about any operator is whether it is limited by arithmetic or by memory traffic:</p>
<pre class="text"><code>time &gt;= max(useful_FLOPs / achievable_FLOPs_per_second,
            bytes_moved / achievable_bytes_per_second)</code></pre>
<p>For batch-one dense decode, arithmetic intensity is close to one operation per weight byte. The memory term wins quickly, so the first useful model is just counting bytes:</p>
<pre class="text"><code>bytes_per_token = sum(weights and metadata read by one decode step)
seconds_per_token = bytes_per_token / aggregate_achievable_bandwidth
tokens_per_second = 1 / seconds_per_token</code></pre>
<p>Count from the <code>safetensors</code> headers, not from a number in <code>config.json</code>. An embedding table is resident but only one row gets looked up. The vision tower is resident but idle during a text-only turn. The MTP head is only read when speculation is active. On a multimodal model, counting every resident tensor can add several GiB the step never actually reads.</p>
<p>Quantization metadata counts too. A nominal four-bit weight with group scales and zero points is not exactly 0.5 bytes per parameter. In this format it is about 0.52 bytes at group 128 and about 0.59 at group 32, and that metadata is read alongside the payload on every token.</p>
<p>Prefill is a different calculation. A reasonable first approximation for the dense projections is <code>2 × parameters × prompt_tokens</code> floating-point operations, with the attention term added separately. This is why one number called “model throughput” should never be used for both phases.</p>
<p>Intel lists both the B65 and the B70 at 32 GiB and 608 GB/s of memory bandwidth. The B65 has 20 Xe2 cores and 197 peak dense INT8 TOPS; the B70 has 32 cores and 367 TOPS. Same advertised bandwidth, roughly 1.86x the INT8 compute. Decode and prefill should therefore scale differently even before software enters the picture.</p>
<p>A roofline gives you a boundary. Mostly I use it as a warning system: it tells me when a proposed optimization cannot possibly repay its complexity, when a measurement looks suspiciously good, and when writing another kernel is unlikely to be worth the time.</p>
</section>
<section id="check-upstream-first-then-add-the-missing-bits" class="level2">
<h2 class="anchored" data-anchor-id="check-upstream-first-then-add-the-missing-bits">Check upstream first, then add the missing bits</h2>
<p>Pinned containers are good for reproducibility, and they also freeze the stack at one moment. The XPU stack kept moving while I worked, so my loop for every missing path became:</p>
<ol type="1">
<li>Check current SGLang, torch-xpu, oneDNN, Intel’s images, and the XPU kernel packages.</li>
<li>Confirm whether the failure is still present in the pinned release.</li>
<li>Separate a missing platform-specific branch from a missing implementation.</li>
<li>Add the smallest overlay that makes the model correct.</li>
<li>Delete the overlay when upstream covers the same case.</li>
</ol>
<p>Step three is the one that saves weeks, and it came up immediately.</p>
<p>SGLang reads AWQ checkpoints through a component called <code>compressed-tensors</code>, which decides how packed four-bit weights get unpacked and which matrix kernel serves them. In the version I was using, two small things assumed an NVIDIA GPU. A helper that rearranges packed weights into the layout the kernel expects was imported only when CUDA was available, then called later regardless. Separately, the code that picks a quantization scheme asked CUDA for the device’s compute capability before it had chosen a scheme at all, which fails on a machine with no CUDA device.</p>
<p>Neither of those means Intel GPUs lack a four-bit kernel. The kernel was there. The checkpoint just could not reach it, because the road to it ran through NVIDIA-only code. Adding the missing branch was enough.</p>
<p>The MTP path had the same shape. I registered the XPU attention backend in the speculative draft maps, routed the token-tree convolution to a Triton implementation that accepts tree arguments, and relaxed two helpers that rejected non-CUDA tensors even though their implementation was already Triton. Small integration fixes, not a replacement serving stack.</p>
<p>One more lesson: “the model loaded” is only the beginning of correctness. My first text-only quantization build silently omitted the vision tower and the MTP head. The library never instantiated an MTP module, so <code>save_pretrained</code> could not save tensors it did not know existed. I now build with the multimodal class, copy the MTP tensors explicitly, and verify the tensor list before any performance run.</p>
</section>
<section id="the-existing-library-primitive-was-the-fastest-kernel-i-tested" class="level2">
<h2 class="anchored" data-anchor-id="the-existing-library-primitive-was-the-fastest-kernel-i-tested">The existing library primitive was the fastest kernel I tested</h2>
<p>Once the model was correct enough to benchmark, the obvious question was which four-bit matrix path should serve the dense projections.</p>
<p>The answer was not my hand-driven kernel. On the same community AWQ checkpoint, <a href="https://huggingface.co/barrydeen/Qwen3.8-27B-AWQ-4bit"><code>barrydeen/Qwen3.8-27B-AWQ-4bit</code></a>, the same two B65 cards, and the same captured 128-input/512-output shape:</p>
<p><img src="https://blog.rahul.onl/posts/qwen38-27b/awq-path.svg" class="img-fluid" style="width:100.0%" alt="Four measured W4A16 paths on two B65 cards rise from 6.2 tokens per second for separate dequantization and matmul to 35.1 tokens per second for the existing oneDNN primitive."></p>
<p><em>Figure 1. The existing oneDNN primitive, not a new custom kernel, produced the largest measured four-bit step on this shape.</em></p>
<table class="caption-top table">
<colgroup>
<col style="width: 27%">
<col style="width: 36%">
<col style="width: 36%">
</colgroup>
<thead>
<tr class="header">
<th>path</th>
<th style="text-align: right;">TPOT</th>
<th style="text-align: right;">decode</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>awq_dequantize</code> followed by <code>torch.matmul</code></td>
<td style="text-align: right;">161.22 ms</td>
<td style="text-align: right;">6.2 tok/s</td>
</tr>
<tr class="even">
<td><code>moe_grouped_mm_nt_xe20_w4a16</code>, driven as a dense GEMM</td>
<td style="text-align: right;">39.04 ms</td>
<td style="text-align: right;">25.6 tok/s</td>
</tr>
<tr class="odd">
<td>the same kernel with split-K</td>
<td style="text-align: right;">35.44 ms</td>
<td style="text-align: right;">28.2 tok/s</td>
</tr>
<tr class="even">
<td><code>aten::_weight_int4pack_mm_with_scales_and_zeros</code> / oneDNN</td>
<td style="text-align: right;"><strong>28.46 ms</strong></td>
<td style="text-align: right;"><strong>35.1 tok/s</strong></td>
</tr>
</tbody>
</table>
<p>That ATen primitive dispatches to oneDNN weight decompression. It needed no model-specific tuning file and, for this checkpoint layout, no second weight repack. Reading its source also explained a BF16/F16 difference I had measured: the specialized four-bit dequantization path in the oneDNN version I used only accepts F16 and F32 compute types, so BF16 falls through to a more generic tile-conversion branch.</p>
<p>I spent a day pushing the hand-driven path before accepting the stop condition: if the library primitive is already close to the in-situ roofline, keep it as the baseline and move up a level. oneDNN wins this round.</p>
<p>That was a large improvement, and it exposed the next problem. The community AWQ checkpoint left the three large Gated DeltaNet projections in BF16, and those represented nearly half the bytes read during a decode step. The kernel was no longer the only question. The checkpoint itself had become part of the latency path.</p>
</section>
<section id="four-bits-is-not-really-four-bits" class="level2">
<h2 class="anchored" data-anchor-id="four-bits-is-not-really-four-bits">Four bits is not really four bits</h2>
<p>My checkpoint inventory measured the three large projections in every DeltaNet layer (input QKV, input Z, and output) at roughly 10.36 GiB in BF16. That is about 47% of the community checkpoint’s decode traffic. I nearly left them alone. Then I looked at the official FP8 release and found scale tensors for those same projections, with only the small surrounding tensors excluded. Useful prior: the model authors quantize these in their own low-precision release.</p>
<p>My AWQ build quantizes 24.33 billion parameters with asymmetric group-128 W4A16. Per-group scales and zero points bring the stored cost of those weights to 4.16 bits per parameter. Another 3.45 billion parameters stay BF16: embeddings, output head, norms, small DeltaNet gates, vision tower, and MTP head. Across the full checkpoint that averages 5.63 bits per parameter, or 18.2 GiB.</p>
<p>I did not arrive at group 128 immediately. The first all-four-bit build used group 32. It had finer quantization groups and fewer total model bytes than the community checkpoint, and it ran slower. Two measurements explained the sign:</p>
<ul>
<li>Group 32 reads four times as many scale and zero-point groups.</li>
<li>On the same <code>down_proj</code> tensor at <code>M=1</code>, oneDNN moved group-32 data at 383 GB/s and group-128 data at 505 GB/s. The matching BF16 GEMV reached 589 GB/s.</li>
</ul>
<p>Group size turned out to be a serving-layout decision as much as a quality setting, and re-quantizing at 128 was worth more than another day of kernel changes.</p>
<p>Here the comparison is like for like: same cards, same TP2 setup, same 128-input/512-output shape, same server, two four-bit checkpoints of the same model. Quantizing the DeltaNet projections cut measured decode traffic from 21.82 GiB to 14.19 GiB, about 35%, and throughput moved from 35.4 to 38.5 tok/s.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>TP2, 128/512 shape</th>
<th style="text-align: right;">bytes read per step</th>
<th style="text-align: right;">TPOT</th>
<th style="text-align: right;">decode</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><a href="https://huggingface.co/barrydeen/Qwen3.8-27B-AWQ-4bit"><code>barrydeen/Qwen3.8-27B-AWQ-4bit</code></a>, DeltaNet projections BF16</td>
<td style="text-align: right;">21.82 GiB</td>
<td style="text-align: right;">28.24 ms</td>
<td style="text-align: right;">35.4 tok/s</td>
</tr>
<tr class="even">
<td><a href="https://huggingface.co/ulkaa/Qwen3.8-27B-AWQ-INT4"><code>ulkaa/Qwen3.8-27B-AWQ-INT4</code></a>, group 128, DeltaNet projections INT4</td>
<td style="text-align: right;"><strong>14.19 GiB</strong></td>
<td style="text-align: right;"><strong>25.95 ms</strong></td>
<td style="text-align: right;"><strong>38.5 tok/s</strong></td>
</tr>
</tbody>
</table>
<p><em>About 9% faster than the community four-bit checkpoint. Thirty-five percent fewer bytes bought about nine percent more tokens per second, so the byte model found the opportunity, but those newly quantized projection shapes were clearly behaving unlike ordinary dense four-bit GEMMs.</em></p>
<p>I have not closed that gap. The merged DeltaNet projection at TP2 has a shape unlike the dense FFN projections and is my leading suspect, and I come back to it at the end. I would rather publish the result I cannot explain than tidy the story until the arithmetic looks neat.</p>
</section>
<section id="graph-capture-changes-both-performance-and-observability" class="level2">
<h2 class="anchored" data-anchor-id="graph-capture-changes-both-performance-and-observability">Graph capture changes both performance and observability</h2>
<p>Decode is a long chain of small operations. Graph replay removes much of the per-operation submission cost, so graph capture is part of the setup I actually use, not an optional benchmark trick. Earlier work on two other models in this series measured it as a first-order improvement. For Qwen3.8 I do not have a clean graph-on/graph-off comparison, so I attach no new percentage to it.</p>
<p>Capture also changes what instrumentation means. A Python-side counter that gets incremented while the graph is being captured can replay the device work forever without ever incrementing the Python value again. I once had a fast collective serving happily inside the graph while its own log insisted <code>served=0</code>.</p>
<p>The only trustworthy proof was controlled removal:</p>
<ul>
<li>build the same graph with the path enabled;</li>
<li>build it again with exactly that path disabled;</li>
<li>run the same shape after compilation;</li>
<li>require the timing to move by more than the quiet-box noise floor.</li>
</ul>
<p>One of those A/B tests was for a small collective operation. When the model is split across four cards, every layer has to sum partial results from all of them, an operation called an all-reduce. During decode that message is tiny: one token at hidden size 5,120 in BF16 is about 10 KiB. At that size almost none of the time goes into moving bytes. It goes into the fixed cost of setting up the exchange and getting the cards to agree they are ready.</p>
<p>So a leaner path for small messages is worth having. The one I use is built on shared memory that the rank processes map directly, capped at 64 KiB, handing anything larger (prefill, mostly) back to the standard collective. Disabling it in the saved TP4 A/B run cost 4.41 ms per step.</p>
<p>Because it maps shared-memory handles across those processes, it needs <code>SYS_PTRACE</code> and <code>seccomp=unconfined</code> in my container. Those permissions widen what the container can do. They are required for this optional collective, not for running Qwen3.8 in general, so remove them and disable the path if that tradeoff does not suit you.</p>
<p>Hybrid models have another memory pool to watch. The recurrent state pool competes with the KV cache and can bound concurrency before the ordinary request limit does. I once configured it below the number of slots a single request needs and got a server reporting zero runnable requests, with an error that mostly talked about memory. Raising the request limit was never going to help. There was nowhere to put the recurrent state.</p>
</section>
<section id="the-trace-blamed-the-wrong-component" class="level2">
<h2 class="anchored" data-anchor-id="the-trace-blamed-the-wrong-component">The trace blamed the wrong component</h2>
<p>At one point I fit TP2 and TP4 measurements to a simple model with a sharded weight term and a constant term. The fit suggested roughly 12 ms that did not shrink with more cards. Host overhead or graph replay looked guilty.</p>
<p>Rather than apportion a busy trace, I priced components by removal on the real captured graph. Replace one component with shape-matched zeros, keep the rest of the graph and the collectives intact, and measure against an unchanged repeat. This does not produce a perfect additive profile, since collectives overlap some module rows, but it answers the causal question: what disappears if this component is removed?</p>
<p>Starting from a 28.59 ms B65 TP2 run:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 27%">
<col style="width: 36%">
<col style="width: 36%">
</colgroup>
<thead>
<tr class="header">
<th>removed component</th>
<th style="text-align: right;">measured cost</th>
<th style="text-align: right;">share of the step</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>dense MLP bodies across 64 layers</td>
<td style="text-align: right;"><strong>12.37 ms</strong></td>
<td style="text-align: right;"><strong>43% measured</strong></td>
</tr>
<tr class="even">
<td>attention sublayers across 64 layers</td>
<td style="text-align: right;"><strong>10.39 ms</strong></td>
<td style="text-align: right;"><strong>36% measured</strong></td>
</tr>
<tr class="odd">
<td>of which attention and GDN kernels</td>
<td style="text-align: right;">2.24 ms</td>
<td style="text-align: right;">8% measured</td>
</tr>
<tr class="even">
<td>of which projections, gates, RoPE, and collectives</td>
<td style="text-align: right;">8.15 ms</td>
<td style="text-align: right;">28% measured</td>
</tr>
<tr class="odd">
<td>layer-stack all-reduces, overlapping the rows above</td>
<td style="text-align: right;">3.82 ms</td>
<td style="text-align: right;">13% measured</td>
</tr>
<tr class="even">
<td>sampling path</td>
<td style="text-align: right;">0.37 ms</td>
<td style="text-align: right;">1% measured</td>
</tr>
</tbody>
</table>
<p>The supposedly fixed host term was mostly dense MLP device work, whose poor multi-card scaling made a two-point fit look constant. The DeltaNet recurrence itself was small. Had I trusted the fit, I would probably have spent another week optimizing the wrong layer family.</p>
<p>That changed the order of future work: merged four-bit projection shapes first, then dense scaling, then whatever a fresh removal budget turns up. The recurrence is not free, but it is not the first problem.</p>
</section>
<section id="the-final-latency-distribution-is-pleasantly-boring" class="level2">
<h2 class="anchored" data-anchor-id="the-final-latency-distribution-is-pleasantly-boring">The final latency distribution is pleasantly boring</h2>
<p>A mean TPOT can hide an ugly tail, so I measured the inter-token latency distribution for the final AWQ release. Each point below summarizes 1,023 inter-token intervals from the second run of a 1,024-token output, concurrency one, graph capture on.</p>
<p><img src="https://blog.rahul.onl/posts/qwen38-27b/awq-itl-percentiles.svg" class="img-fluid" style="width:100.0%" alt="Median-to-p99 inter-token latency stays narrow on both two and four B65 cards, at short and 8K prompts. TP2 ranges from roughly 26.2 to 27.0 ms, while TP4 ranges from roughly 19.1 to 19.7 ms."></p>
<p><em>Figure 2. Across the short and 8K prompts, p99 stayed within 0.66 ms of the median on TP2 and within 0.57 ms on TP4.</em></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>GPUs / TP</th>
<th style="text-align: right;">prompt</th>
<th style="text-align: right;">median ITL</th>
<th style="text-align: right;">p90</th>
<th style="text-align: right;">p99</th>
<th style="text-align: right;">max</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>2x B65 / TP2</td>
<td style="text-align: right;">256</td>
<td style="text-align: right;">26.16 ms</td>
<td style="text-align: right;">26.51 ms</td>
<td style="text-align: right;">26.82 ms</td>
<td style="text-align: right;">32.32 ms</td>
</tr>
<tr class="even">
<td>2x B65 / TP2</td>
<td style="text-align: right;">8K</td>
<td style="text-align: right;">26.41 ms</td>
<td style="text-align: right;">26.63 ms</td>
<td style="text-align: right;">26.97 ms</td>
<td style="text-align: right;">32.40 ms</td>
</tr>
<tr class="odd">
<td>4x B65 / TP4</td>
<td style="text-align: right;">256</td>
<td style="text-align: right;">19.10 ms</td>
<td style="text-align: right;">19.37 ms</td>
<td style="text-align: right;">19.67 ms</td>
<td style="text-align: right;">22.16 ms</td>
</tr>
<tr class="even">
<td>4x B65 / TP4</td>
<td style="text-align: right;">8K</td>
<td style="text-align: right;">19.17 ms</td>
<td style="text-align: right;">19.37 ms</td>
<td style="text-align: right;">19.60 ms</td>
<td style="text-align: right;">22.14 ms</td>
</tr>
</tbody>
</table>
<p>This is the kind of graph I like: not dramatic, just steady. It supports a more useful statement than “the model does 52 tok/s”. At these two contexts and this concurrency, the ordinary token-to-token experience hides no large tail.</p>
</section>
<section id="what-might-b70-do" class="level2">
<h2 class="anchored" data-anchor-id="what-might-b70-do">What might B70 do?</h2>
<p>I have not measured Qwen3.8-27B on B70, so an exact B70 bar would be fiction. There are two useful boundaries though.</p>
<p>The conservative edge assumes no decode uplift at all, since B65 and B70 share the same advertised 608 GB/s of memory bandwidth. The optimistic edge borrows the largest B70-over-B65 decode ratio I measured on two other models, 1.273x. That is deliberately rough: Qwen3.8 is dense while those models are sparse hybrids, so their scaling does not automatically transfer.</p>
<p><img src="https://blog.rahul.onl/posts/qwen38-27b/b65-b70-scenarios.svg" class="img-fluid" style="width:100.0%" alt="Measured B65 decode is 37.8 tokens per second at TP2 and 52.1 at TP4. Hatched, explicitly unmeasured B70 estimate bands span 37.8 to 48.1 and 52.1 to 66.3 tokens per second."></p>
<p><em>Figure 3. The B70 range is a planning aid, not a benchmark. The lower edge assumes equal bandwidth means equal decode; the upper edge applies the largest uplift seen on two earlier models.</em></p>
<p>Prefill has a better reason to move, since the B70 has more Xe2 cores and roughly 1.86x the advertised dense INT8 compute. Even there I would not simply multiply the measured result by 1.86. Attention, dequantization, collectives, and achieved occupancy do not all scale with peak matrix throughput. The next graph I put here should be a measured one.</p>
</section>
<section id="a-quick-detour-through-the-other-models" class="level2">
<h2 class="anchored" data-anchor-id="a-quick-detour-through-the-other-models">A quick detour through the other models</h2>
<p>Qwen3.8 was the fourth model in this line of work. The earlier three are not apples-to-apples competitors, since they use different architectures, card counts, TP sizes, and workloads. Their value here is showing which methods survived contact with another model.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>model</th>
<th>one useful result</th>
<th>what I brought forward</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><a href="https://huggingface.co/Qwen/Qwen3-Coder-Next">Qwen3-Coder-Next 80B-A3B</a></td>
<td><strong>100.9 tok/s</strong>, B70 TP4, 8K/1K c=1</td>
<td>graph replay, TP-specific tuning, small-collective latency, counting the weights actually used per token</td>
</tr>
<tr class="even">
<td><a href="https://huggingface.co/ornith-ai/Ornith-1.0-35B">Ornith 1.0 35B</a></td>
<td><strong>106.8 tok/s</strong>, B70 TP2, 8K/1K c=1</td>
<td>check packed quantization against real tensors, and never assume a Qwen attention setting helps another hybrid model</td>
</tr>
<tr class="odd">
<td><a href="https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731">DeepSeek-V4-Flash</a></td>
<td><strong>35.1 tok/s</strong> short-context decode and 2,355 tok/s at 8K prefill on 8x B70; a later single-stream test fit 801,024 usable tokens at a 1M setting</td>
<td>start with upstream, measure cold prefill separately, remove components to find where the time really goes</td>
</tr>
</tbody>
</table>
<p>The most useful warning came from Ornith. It looked similar to Qwen: hybrid attention, Gated DeltaNet, packed four-bit experts. Yet its asymmetric zero points changed the correctness contract, its router already used a good XPU top-k path, and the Qwen attention override made it slower. The method transferred; the configuration did not.</p>
<p>Those rows are reference points, not a competition between models. Each one deserves its own post, and I plan to write them. This one is about Qwen3.8 and the method I used to work out what it needed.</p>
<p>That is also why I do not present a bag of “Xe2 optimizations” to enable all at once. Graph capture, rooflines, proof that a fast path actually ran, and controlled A/Bs are methods. A tile size, context cutoff, or packed layout belongs to the exact model, card, and TP combination that earned it.</p>
</section>
<section id="what-were-codex-and-claude-actually-useful-for" class="level2">
<h2 class="anchored" data-anchor-id="what-were-codex-and-claude-actually-useful-for">What were Codex and Claude actually useful for?</h2>
<p>I used coding agents extensively during this work, mainly Codex and Claude. They were useful in a narrower and more practical way than “the agents wrote the optimization”.</p>
<ul>
<li><strong>Reading an unreasonable amount of source.</strong> One investigation followed the SYCL grouped GEMM through its tile policy and reorder atoms, then compared it against oneDNN. That is how I learned the clever four-bit conversion I was about to implement already existed.</li>
<li><strong>Surveying an API surface.</strong> An agent enumerated quantized primitives with real XPU dispatch, their schemas, and their layout contracts, which quickly separated usable operators from names that merely sounded relevant.</li>
<li><strong>Building harnesses from a strict specification.</strong> The speculative-decoding harness refuses failed requests and keeps cache-sensitive natural-text tests separate from random-token kernel isolation.</li>
<li><strong>Running serialized campaigns.</strong> Tuning many shapes is boring but valuable, and it is a good background job when only one process may own the GPUs.</li>
</ul>
<p>They were also entirely capable of producing a confident conclusion from an empty log. Twice a container had stopped and the missing output was treated as a finding. A <code>pkill -f</code> pattern matched the replacement command itself four times. One benchmark reported a rejected over-context request as zeros, which looked like an amazing performance result for a few seconds.</p>
<p>The fix belonged in the harness rather than the prompting: fail loudly, record the exact setup and run number, keep retractions beside the results, and refuse to print metrics for a rejected request. My own job stayed the same: one benchmark on the GPUs at a time, one changed variable, and no number without a saved log.</p>
</section>
<section id="fast-gibberish-is-still-gibberish" class="level2">
<h2 class="anchored" data-anchor-id="fast-gibberish-is-still-gibberish">Fast gibberish is still gibberish</h2>
<p>Two quantization mistakes produced clean server starts and output consisting almost entirely of exclamation marks.</p>
<p>First, the text-only model class changed module prefixes. Weight loading had a name-translation layer, but the quantization ignore list did not, so exclusions silently missed their targets.</p>
<p>Then the quantizer added the container module <code>layers.N.linear_attn</code> to the ignore list, because the container itself was not a <code>Linear</code>. The runtime matched ignore entries by substring, so that one entry hid every projection beneath it. Packed tensors existed in the checkpoint and were never loaded into those linears.</p>
<p>Both cases now fail at build time, and I also compare packed dequantization against an independent float64 reference on real tensors. Shape checks alone are not enough. A wrong packed orientation can be shape-valid and still produce fluent-looking, numerically wrong output.</p>
<p>The final group-128 AWQ checkpoint passed health, determinism, and coherence checks on code, reasoning, factual, and summarization prompts. Against the BF16 reference:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>quality check</th>
<th style="text-align: right;">result</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>mean rank of the BF16 reference token on aligned steps</td>
<td style="text-align: right;"><strong>1.0000</strong></td>
</tr>
<tr class="even">
<td>BF16 reference token outside AWQ top 8</td>
<td style="text-align: right;"><strong>0</strong></td>
</tr>
<tr class="odd">
<td>mean KL on aligned steps</td>
<td style="text-align: right;">0.0201</td>
</tr>
<tr class="even">
<td>prefill perplexity</td>
<td style="text-align: right;">8.87 → <strong>9.33</strong>, +5.2%</td>
</tr>
<tr class="odd">
<td>prompts whose greedy text diverged</td>
<td style="text-align: right;">8 of 8</td>
</tr>
<tr class="even">
<td>aligned steps after divergence</td>
<td style="text-align: right;">71 of 957</td>
</tr>
</tbody>
</table>
<p>Exact argmax agreement applies only where the sequences are still aligned. Every greedy sequence eventually diverged, leaving 7.4% of steps directly comparable. So the claim stays modest: the quantized model tracks BF16 closely before divergence, at a measured +0.46 prefill-perplexity cost. It is still a four-bit model, not an exact BF16 drop-in.</p>
<p>I also have an absolute IFEval result, but no current BF16 run through the same harness and scored subset, and I will not compare it against an older result that skipped a different set of instruction types.</p>
<p>Multimodal inference works. The checkpoint keeps the vision tower in BF16, images load, and the model answers questions about them. What I have not done is score it against a broad image benchmark suite, so I can say the capability is present and working without yet quantifying what the four-bit text weights cost it. The MTP path is enabled as well, though acceptance rates and end-to-end benefit on natural coding prompts still need a proper campaign. Random token IDs are useful for defeating the prefix cache, but they pin speculative yield near its minimum and cannot answer whether MTP helps a real session.</p>
</section>
<section id="what-still-does-not-make-sense" class="level2">
<h2 class="anchored" data-anchor-id="what-still-does-not-make-sense">What still does not make sense?</h2>
<p>I cut 35% of the bytes read per decode step and got 9% more throughput back. Three independent views agree that the shortfall is real: checkpoint-aware projection, same-shape kernel rates, and component removal. None of them explains why the merged DeltaNet projection behaves so differently from the dense FFN path.</p>
<p>Somewhere in there is performance I have already paid for and am not collecting, and until I know why, every other number in my AWQ build rests on something I cannot account for. So it goes first.</p>
<p>Some of the things I want to do next:</p>
<ol type="1">
<li>Work out where the rest of that saving went. Profile the merged DeltaNet four-bit shapes inside the running server, not as standalone GEMMs, and find out what makes that shape different from the dense FFN projections.</li>
<li>Redo the component-removal measurements once that changes, because the rankings expire the moment the algorithm does.</li>
<li>Measure Qwen3.8 on B70 and put real numbers where the estimated range is now.</li>
<li>See how often MTP’s speculated tokens actually get accepted in real coding-agent sessions instead of synthetic prompts.</li>
<li>Run a full multimodal suite so the vision path has numbers too.</li>
</ol>
<p>What I would carry to the next model is the method rather than this configuration: check upstream first, count bytes from the checkpoint, keep the vendor library as the baseline, verify instruction and layout legality before designing a tile, prove every fast path actually served, and measure with graph capture on, the way the model will be used day to day.</p>
<p>That process is slower than collecting one exciting number, but it made the next model much faster to understand. And Qwen3.8 is now a local coding-agent backend I can use without thinking about every token it generates, which is what I wanted from it.</p>


</section>

 ]]></description>
  <category>intel</category>
  <category>arc</category>
  <category>arc-pro</category>
  <category>xe2</category>
  <category>xpu</category>
  <category>sglang</category>
  <category>llm-inference</category>
  <category>quantization</category>
  <category>agentic-coding</category>
  <guid>https://blog.rahul.onl/posts/2026-08-16-qwen38-27b-arc-pro-sglang.html</guid>
  <pubDate>Sun, 16 Aug 2026 07:00:00 GMT</pubDate>
  <media:content url="https://blog.rahul.onl/posts/qwen38-27b/card.png" medium="image" type="image/png" height="95" width="144"/>
</item>
<item>
  <title>Exposing Local Applications: Cloudflare and Gradio Tunnels</title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2024-12-11-expose-tunneling.html</link>
  <description><![CDATA[ 






<p>When developing or testing applications locally, you may need to share them quickly over the internet. Whether it’s for demos, hackathons, or collaborative projects, tunneling tools like <strong>Cloudflare’s TryCloudflare</strong> and <strong>Gradio’s Share Feature</strong> provide effective solutions to expose local services to the public.</p>
<p>This guide focuses on setting up tunnels for various workloads (e.g., web services, web apps, TGI servers, VLLM services) and provides detailed steps for using these tools. The examples assume your service is running locally on a specific port (e.g., <code>http://localhost:8080</code>).</p>
<hr>
<section id="cloudflares-trycloudflare" class="level2">
<h2 class="anchored" data-anchor-id="cloudflares-trycloudflare">Cloudflare’s TryCloudflare</h2>
<p><strong>Cloudflare’s TryCloudflare</strong> lets you quickly expose local services to the internet with no Cloudflare account required. While it’s intended for testing or temporary use, Cloudflare also offers premium tunnels for production-grade needs.</p>
<section id="why-use-cloudflare" class="level3">
<h3 class="anchored" data-anchor-id="why-use-cloudflare">Why Use Cloudflare?</h3>
<ul>
<li><strong>Quick Setup:</strong> A single command is enough to expose your service.</li>
<li><strong>Secure:</strong> It uses Cloudflare’s global network, protecting your IP address.</li>
<li><strong>Temporary Usage:</strong> Ideal for demos or quick sharing during development.</li>
</ul>
</section>
<section id="setting-up-trycloudflare" class="level3">
<h3 class="anchored" data-anchor-id="setting-up-trycloudflare">Setting Up TryCloudflare</h3>
<ol type="1">
<li><p><strong>Install <code>cloudflared</code>:</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> apt update</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> apt install <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-y</span> wget</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wget</span> https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb</span>
<span id="cb1-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sudo</span> dpkg <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> cloudflared-linux-amd64.deb</span></code></pre></div></div></li>
<li><p><strong>Expose a Local Service</strong> (replace <code>8080</code> with your service’s port):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">cloudflared</span> tunnel <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--url</span> http://localhost:8080</span></code></pre></div></div></li>
<li><p><strong>Share the Public URL</strong>:</p>
<p>After running the command, you’ll receive a public URL like:</p>
<pre><code>https://&lt;random-subdomain&gt;.trycloudflare.com</code></pre>
<p>This link is temporary and only works while the <code>cloudflared</code> process is running.</p></li>
</ol>
</section>
<section id="example-workloads" class="level3">
<h3 class="anchored" data-anchor-id="example-workloads">Example Workloads:</h3>
<ul>
<li><p><strong>Web Service</strong>: Start your web service (e.g., Flask, FastAPI, Node.js) locally on port <code>8080</code> and use <code>cloudflared</code> to expose it.</p></li>
<li><p><strong>TGI or VLLM Server</strong>: Run your inference server locally, bound to a port, and use <code>cloudflared</code> to expose it for collaborators or clients to test.</p></li>
</ul>
</section>
<section id="for-production-use" class="level3">
<h3 class="anchored" data-anchor-id="for-production-use">For Production Use:</h3>
<p>For permanent, production-grade tunnels with custom domains, better reliability, and SLAs, consider upgrading to <a href="https://www.cloudflare.com/products/tunnels/">Cloudflare’s premium tunnel services</a>.</p>
<hr>
</section>
</section>
<section id="gradios-share-feature" class="level2">
<h2 class="anchored" data-anchor-id="gradios-share-feature">Gradio’s Share Feature</h2>
<p><strong>Gradio</strong> is widely used for creating interfaces for machine learning models, but its <code>share=True</code> option can also be repurposed to expose general-purpose applications.</p>
<section id="why-use-gradio" class="level3">
<h3 class="anchored" data-anchor-id="why-use-gradio">Why Use Gradio?</h3>
<ul>
<li><strong>Ease of Use:</strong> Designed for developers, with minimal configuration required.</li>
<li><strong>Temporary Links:</strong> Ideal for demos, with links valid for up to 72 hours.</li>
<li><strong>Integrated with Python:</strong> Perfect for exposing Python-based services.</li>
</ul>
</section>
<section id="setting-up-gradio-tunnels" class="level3">
<h3 class="anchored" data-anchor-id="setting-up-gradio-tunnels">Setting Up Gradio Tunnels</h3>
<ol type="1">
<li><p><strong>Install Gradio</strong>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install gradio</span></code></pre></div></div></li>
<li><p><strong>Expose a Local Service</strong>:</p>
<p>Create a minimal Gradio app to expose your service (replace <code>8080</code> with your service’s port):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> gradio <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> gr</span>
<span id="cb5-2"></span>
<span id="cb5-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> expose_app():</span>
<span id="cb5-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Service running on http://localhost:8080"</span></span>
<span id="cb5-5"></span>
<span id="cb5-6">demo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gr.Interface(fn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>expose_app, inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[], outputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>)</span>
<span id="cb5-7">demo.launch(share<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div></li>
<li><p><strong>Share the Public URL</strong>:</p>
<p>Running the script provides a public URL like:</p>
<pre><code>https://&lt;random-subdomain&gt;.gradio.live</code></pre>
<p>This link is active for 72 hours.</p></li>
</ol>
</section>
<section id="example-workloads-1" class="level3">
<h3 class="anchored" data-anchor-id="example-workloads-1">Example Workloads:</h3>
<ul>
<li><p><strong>Web Service</strong>: Use Gradio to describe and share your web service running on <code>localhost:8080</code>.</p></li>
<li><p><strong>Web App</strong>: Expose your local React, Vue, or other frontend applications by sharing the port they’re hosted on.</p></li>
<li><p><strong>Inference Servers</strong>: Provide lightweight interaction interfaces for machine learning models.</p></li>
</ul>
</section>
<section id="for-production-use-1" class="level3">
<h3 class="anchored" data-anchor-id="for-production-use-1">For Production Use:</h3>
<p>Gradio’s share links are temporary and not intended for production. For permanent hosting, consider deploying on platforms like <a href="https://huggingface.co/spaces">Hugging Face Spaces</a>.</p>
<hr>
</section>
</section>
<section id="recommendations-and-when-to-use" class="level2">
<h2 class="anchored" data-anchor-id="recommendations-and-when-to-use">Recommendations and When to Use</h2>
<ul>
<li><p><strong>Cloudflare TryCloudflare</strong>: Best for quick exposure of services without additional Python dependencies. Use it for secure sharing during hackathons or short-lived projects. For production or long-term use, consider Cloudflare’s premium tunnels.</p></li>
<li><p><strong>Gradio Share Feature</strong>: Ideal for Python developers or when you need a simple interface to accompany your service. Use it to share ML demos, Python apps, or lightweight experiments.</p></li>
</ul>
<p>Both tools are great for development and testing but remember their limitations for production-grade usage. Choose based on your workflow and requirements.</p>
<hr>
<p>This guide equips you with two powerful tools to expose local applications to the world, simplifying collaboration and testing. Happy sharing!</p>


</section>

 ]]></description>
  <guid>https://blog.rahul.onl/posts/2024-12-11-expose-tunneling.html</guid>
  <pubDate>Mon, 18 Nov 2024 08:00:00 GMT</pubDate>
</item>
<item>
  <title>Text-to-SQL Generation Using LLMs Fine-Tuned with QLoRA on Intel GPUs</title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2023-12-05-qlora-finetuning-intel-gpu.html</link>
  <description><![CDATA[ 






<p>The landscape of AI and natural language processing has dramatically shifted with the advent of Large Language models (LLMs). This shift is characterized by advancements like Low-Rank Adaptation (LoRA) and its more advanced iteration, Quantized LoRA (QLoRA), which have transformed the fine-tuning process from a compute-intensive task into an efficient, scalable procedure.</p>
<figure align="center" class="figure">
<img src="https://blog.rahul.onl/posts/images/launghing_llama.jpg" width="800" alt="laughing llama" class="figure-img">
<figcaption style="font-size: 0.8em; color: #666; margin-top: 5px; max-width: 800px; text-align: center;">
Generated with Stable Diffusion XL using the prompt: “A cute laughing llama with big eye lashes, sitting on a beach with sunglasses reading in gibili style.”
</figcaption>
</figure>
<section id="the-advent-of-lora-a-paradigm-shift-in-llm-fine-tuning" class="level2">
<h2 class="anchored" data-anchor-id="the-advent-of-lora-a-paradigm-shift-in-llm-fine-tuning">The Advent of LoRA: A Paradigm Shift in LLM Fine-Tuning</h2>
<p>LoRA represents a significant advancement in the fine-tuning of LLMs. By introducing trainable adapter modules between the layers of a large pre-trained model, LoRA focuses on refining a smaller subset of model parameters. These adapters are low-rank matrices, significantly reducing the computational burden and preserving the valuable pre-trained knowledge embedded within LLMs. The key aspects of LoRA include:</p>
<ul>
<li><strong>Low-Rank matrix structure:</strong> Shaped as (r x d), where ‘r’ is a small rank hyperparameter and ‘d’ is the hidden dimension size. This structure ensures fewer trainable parameters.</li>
<li><strong>Factorization:</strong> The adapter matrix is factorized into two smaller matrices, enhancing the model’s function adaptability with fewer parameters.</li>
<li><strong>Scalability and adaptability:</strong> LoRA balances the model’s learning capacity and generalizability by scaling adapters with a parameter α and incorporating dropout for regularization.</li>
</ul>
<figure align="center" class="figure">
<img src="https://blog.rahul.onl/posts/images/lora_library.png" width="800" alt="lora adapter library" class="figure-img">
<figcaption style="font-size: 0.8em; color: #666; margin-top: 5px; max-width: 800px; text-align: center;">
Left: Integration of LoRA adapters into the model. Right: Deployment of LoRA adapters with a foundation model as a task-specific model library
</figcaption>
</figure>
</section>
<section id="quantized-lora-qlora-efficient-fine-tuning-on-intel-hardware" class="level2">
<h2 class="anchored" data-anchor-id="quantized-lora-qlora-efficient-fine-tuning-on-intel-hardware">Quantized LoRA (QLoRA): Efficient Fine-Tuning on Intel Hardware</h2>
<p>QLoRA advances LoRA by introducing weight quantization, further reducing memory usage. This approach enables the fine-tuning of large models, such as the 70B-parameter Llama 2, on a single GPU , like Intel® Data Center GPU Max Series 1100 with 48 GB VRAM, which was considered impossible previously. QLoRA’s main features include:</p>
<ul>
<li>Memory efficiency: Through weight quantization, QLoRA substantially reduces the model’s memory footprint, crucial for handling large LLMs.</li>
<li>On-the-fly dequantization: It temporarily dequantizes the quantized weights for computations, focusing only on adapter gradients during training.</li>
</ul>
<section id="fine-tuning-with-qlora-on-intel-hardware" class="level3">
<h3 class="anchored" data-anchor-id="fine-tuning-with-qlora-on-intel-hardware">Fine-Tuning with QLoRA on Intel Hardware</h3>
<p>The fine-tuning process starts with setting up the environment and installing the necessary packages, including <a href="https://bigdl.readthedocs.io/en/latest/#bigdl-llm-low-bit-llm-library">bigdl-llm</a> for model loading, parameter-efficient fine-tuning (PEFT) for LoRA adapters, <a href="https://intel.github.io/intel-extension-for-pytorch/xpu/latest/">Intel® Extension for PyTorch*</a> for training using Intel discrete GPUs, Hugging face Transformers for fine-tuning, and datasets for loading the dataset. We will walk through the high-level process of fine-tuning an LLM to improve its capabilities. As an example, we will generate SQL queries from natural language input, focusing on general QLoRA fine-tuning. For detailed explanations, check out the full notebook that takes you from setting up the required Python* packages, loading the model, fine-tuning, and inferencing the fine-tuned LLM to generate SQL from text, on Intel® Developer Cloud and also <a href="https://github.com/rahulunair/genAI/blob/main/LLM_finetuning.ipynb">here</a>.</p>
</section>
<section id="model-loading-and-configuration-for-fine-tuning" class="level3">
<h3 class="anchored" data-anchor-id="model-loading-and-configuration-for-fine-tuning">Model Loading and Configuration for Fine-Tuning</h3>
<p>The foundation model is loaded in a 4-bit format using bigdl-llm, significantly reducing memory usage. This step enables fine-tuning large models like Llama 2 70 for example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> bigdl.llm.transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> AutoModelForCausalLM </span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Loading the model in a 4-bit format for efficient memory usage </span></span>
<span id="cb1-4">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> AutoModelForCausalLM.from_pretrained( </span>
<span id="cb1-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"model_id"</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Replace with your model ID </span></span>
<span id="cb1-6">    load_in_low_bit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nf4"</span>, </span>
<span id="cb1-7">    optimize_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, </span>
<span id="cb1-8">    torch_dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.float16, </span>
<span id="cb1-9">    modules_to_not_convert<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm_head"</span>], </span>
<span id="cb1-10">) </span></code></pre></div></div>
</section>
<section id="learning-rate-and-stability-in-training" class="level3">
<h3 class="anchored" data-anchor-id="learning-rate-and-stability-in-training">Learning Rate and Stability in Training</h3>
<p>Selecting an optimal learning rate is critical in QLoRA fine-tuning to balance training stability and convergence speed. This decision is vital for effective fine-tuning outcomes as a higher learning rate can lead to instabilities with the training loss abnormally drop zero after few steps.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TrainingArguments </span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Configuration for training </span></span>
<span id="cb2-4">training_args <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TrainingArguments( </span>
<span id="cb2-5">    learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2e-5</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Optimal starting point; adjust as needed </span></span>
<span id="cb2-6">    per_device_train_batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, </span>
<span id="cb2-7">    max_steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>, </span>
<span id="cb2-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Additional parameters... </span></span>
<span id="cb2-9">) </span></code></pre></div></div>
<p>During the fine-tuning process, there is a notable rapid decrease in the loss after just a few steps, which then gradually levels off, reaching a value near 0.6 at approximately 300 steps as seen in the graph below:</p>
<figure align="center" class="figure">
<img src="https://blog.rahul.onl/posts/images/loss_chart.jpg" width="800" alt="loss chart" class="figure-img">
<figcaption style="font-size: 0.8em; color: #666; margin-top: 5px; max-width: 800px; text-align: center;">
Training and Validation loss during fine-tuning a CodeLlama-7b model on the b-mc2/sql-create-context dataset.
</figcaption>
</figure>
</section>
</section>
<section id="text-to-sql-conversion-prompt-engineering" class="level2">
<h2 class="anchored" data-anchor-id="text-to-sql-conversion-prompt-engineering">Text-to-SQL Conversion: Prompt Engineering</h2>
<p>With the fine-tuned model, we can convert natural language queries into SQL commands, a vital capability in data analytics and business intelligence. To fine-tune the model, we must carefully convert the data into a structured prompt like below to form an instruction dataset with Input, Context and Response fields:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Function to generate structured prompts for Text-to-SQL tasks </span></span>
<span id="cb3-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_prompt_sql(input_question, context, output<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>):</span>
<span id="cb3-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"""You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables. </span></span>
<span id="cb3-4"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">You must output the SQL query that answers the question.</span></span>
<span id="cb3-5"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">### Input:</span></span>
<span id="cb3-6"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>input_question<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-7"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">### Context:</span></span>
<span id="cb3-8"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>context<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-9"><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">### Response:</span></span>
<span id="cb3-10"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>output<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span></code></pre></div></div>
</section>
<section id="diverse-model-options" class="level2">
<h2 class="anchored" data-anchor-id="diverse-model-options">Diverse Model Options</h2>
<p>The notebook supports an array of models, each offering unique capabilities for different fine-tuning objectives:</p>
<ul>
<li><a href="https://huggingface.co/NousResearch/Nous-Hermes-llama-2-7b">NousResearch/Nous-Hermes-Llama-2–7b</a></li>
<li><a href="https://huggingface.co/NousResearch/Llama-2-7b-chat-hf">NousResearch/Llama-2–7b-chat-hf</a></li>
<li><a href="https://huggingface.co/NousResearch/Llama-2-13b-hf">NousResearch/Llama-2–13b-hf</a></li>
<li><a href="https://huggingface.co/NousResearch/CodeLlama-7b-hf">NousResearch/CodeLlama-7b-hf</a></li>
<li><a href="https://huggingface.co/Phind/Phind-CodeLlama-34B-v2">Phind/Phind-CodeLlama-34B-v2</a></li>
<li><a href="https://huggingface.co/openlm-research/open_llama_3b_v2">openlm-research/open_llama_3b_v2</a></li>
<li><a href="https://huggingface.co/openlm-research/open_llama_13b">openlm-research/open_llama_13b</a></li>
<li><a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta">HuggingFaceH4/zephyr-7b-beta</a></li>
</ul>
</section>
<section id="model-inference-with-qlora-a-comparative-approach" class="level2">
<h2 class="anchored" data-anchor-id="model-inference-with-qlora-a-comparative-approach">Model Inference with QLoRA: A Comparative Approach</h2>
<p>The true test of any fine-tuning process lies in its inference capabilities. In the case of the implementation, the inference stage not only demonstrates the model’s proficiency in task-specific applications but also allows for a comparative analysis between the base and the fine-tuned models. This comparison sheds light on the effectiveness of the LoRA adapters in enhancing the model’s performance for specific tasks.</p>
<section id="model-loading-for-inference" class="level3">
<h3 class="anchored" data-anchor-id="model-loading-for-inference">Model Loading for Inference</h3>
<p>For inference, the model is loaded in a low-bit format, typically 4-bit, using the bigdl-llm library. This approach drastically reduces the memory footprint, making it suitable to run multiple LLMs with high parameter count on a single resource-optimized device such as the Intel® Data Center Max GPU 1100. The following code snippet illustrates the model loading process for inference:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> bigdl.llm.transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> AutoModelForCausalLM </span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Loading the model for inference </span></span>
<span id="cb4-4">model_for_inference <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> AutoModelForCausalLM.from_pretrained( </span>
<span id="cb4-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"finetuned_model_path"</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Path to the fine-tuned model</span></span>
<span id="cb4-6">    load_in_4bit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 4 bit loading</span></span>
<span id="cb4-7">    optimize_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb4-8">    use_cache<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb4-9">    torch_dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.float16, </span>
<span id="cb4-10">    modules_to_not_convert<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm_head"</span>], </span>
<span id="cb4-11">)</span></code></pre></div></div>
</section>
<section id="running-inference-comparing-base-vs-fine-tuned-model" class="level3">
<h3 class="anchored" data-anchor-id="running-inference-comparing-base-vs-fine-tuned-model">Running Inference: Comparing Base vs Fine-Tuned Model</h3>
<p>Once the model is loaded, we can perform inference to generate SQL queries from natural language inputs. This process can be conducted on both the base model and the fine-tuned model, allowing you to directly compare the outcomes and assess the improvements brought about by fine-tuning with QLoRA:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generating a SQL query from a text prompt </span></span>
<span id="cb5-2">text_prompt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> generate_sql_prompt(…)</span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Base Model Inference </span></span>
<span id="cb5-4">base_model_sql <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> base_model.generate(text_prompt) </span>
<span id="cb5-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base Model SQL:"</span>, base_model_sql) </span>
<span id="cb5-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Fine-Tuned Model Inference </span></span>
<span id="cb5-7">finetuned_model_sql <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> finetuned_model.generate(text_prompt) </span>
<span id="cb5-8"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fine-Tuned Model SQL:"</span>, finetuned_model_sql)</span></code></pre></div></div>
<p>Following a 15-minute session training itself, the fine-tuned model demonstrates enhanced proficiency in generating SQL queries that reflect the given questions more accurately than the base model. With additional training steps, we can anticipate further improvements in the model’s response accuracy:</p>
<p>Finetuned Model:</p>
<figure align="center" class="figure">
<img src="https://blog.rahul.onl/posts/images/finetuned.png" width="800" alt="finetuned llm" class="figure-img">
<figcaption style="font-size: 0.8em; color: #666; margin-top: 5px; max-width: 800px; text-align: center;">
Fine-tuned model SQL generation for a given question and context.
</figcaption>
</figure>
<p>Base Model:</p>
<figure align="center" class="figure">
<img src="https://blog.rahul.onl/posts/images/base_model.png" width="800" alt="base llm" class="figure-img">
<figcaption style="font-size: 0.8em; color: #666; margin-top: 5px; max-width: 800px; text-align: center;">
Base model SQL generation for a given question and context.
</figcaption>
</figure>
</section>
<section id="lora-adapters-a-library-of-task-specific-enhancements" class="level3">
<h3 class="anchored" data-anchor-id="lora-adapters-a-library-of-task-specific-enhancements">LoRA Adapters: A Library of Task-Specific Enhancements</h3>
<p>One of the most compelling aspects of LoRA is its ability to act as a library of task-specific enhancements. These adapters can be fine-tuned for distinct tasks and then saved. Depending on the requirement, a specific adapter can be loaded and used with the base model, effectively switching the model’s capabilities to suit different tasks. This adaptability makes LoRA a highly versatile tool in the realm of LLM fine-tuning.</p>
</section>
<section id="check-out-the-notebook-on-intel-developer-cloud" class="level3">
<h3 class="anchored" data-anchor-id="check-out-the-notebook-on-intel-developer-cloud">Check out the notebook on Intel Developer Cloud</h3>
<p>I invite AI practitioners and developers to explore the full notebook on the Intel Developer Cloud, where you can experiment with and explore the capabilities of fine-tuning LLMs using QLoRA on Intel hardware with Intel AI software optimizations. Once you log into Intel Developer Cloud, go to the “Training Catalog”. Under “Gen AI Essentials” in the catalog, you can find the LLM fine-tuning notebook and other notebooks.</p>
<figure align="center" class="figure">
<img src="https://blog.rahul.onl/posts/images/idc_page.webp" width="800" alt="idc genai" class="figure-img">
<figcaption style="font-size: 0.8em; color: #666; margin-top: 5px; max-width: 800px; text-align: center;">
LLM Fine-tuning and other notebooks in Gen AI Essentials under the Training Catalog on IDC.
</figcaption>
</figure>
</section>
</section>
<section id="repo" class="level2">
<h2 class="anchored" data-anchor-id="repo">Repo</h2>
<p>You can find the full code and other related notebooks <a href="https://github.com/rahulunair/genAI">here</a>.</p>


</section>

 ]]></description>
  <category>intel</category>
  <category>dgpu</category>
  <category>PVC1100</category>
  <category>arc</category>
  <category>PyTorch</category>
  <category>bigdl-llm</category>
  <guid>https://blog.rahul.onl/posts/2023-12-05-qlora-finetuning-intel-gpu.html</guid>
  <pubDate>Tue, 05 Dec 2023 08:00:00 GMT</pubDate>
</item>
<item>
  <title>Stable Diffusion inference on Intel Arc GPUs</title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2022-09-06-arc-dgpu-stable-diffusion.html</link>
  <description><![CDATA[ 






<p><a href="https://blog.rahul.onl/posts/2022-08-12-arc-dgpu-linux.html">Now</a> that we have our Arc discrete GPU setup on Linux, let’s try to run Stable Diffusion model using it.</p>
<section id="a-quick-recap-updated-steps-to-set-up-arc-on-linux" class="level2">
<h2 class="anchored" data-anchor-id="a-quick-recap-updated-steps-to-set-up-arc-on-linux">A quick recap / updated steps to set up Arc on Linux</h2>
<p>Intel has now published <a href="https://dgpu-docs.intel.com/installation-guides/ubuntu/ubuntu-jammy-arc.html">documentation</a> on how to set up Arc on Linux. I tried it today, it worked beautifully.</p>
<section id="steps-to-configure-arc" class="level3">
<h3 class="anchored" data-anchor-id="steps-to-configure-arc">Steps to configure Arc</h3>
<ul>
<li>Install the 5.7 OEM kernel</li>
<li>Install kernel mode drivers, gpu firmware</li>
<li>Install usermod drivers for compute, 3d graphics and media</li>
<li>Add user to <code>render</code> group</li>
<li>Install oneAPI 2022.3 (latest as of this writeup)</li>
</ul>
</section>
</section>
<section id="stable-diffusion" class="level2">
<h2 class="anchored" data-anchor-id="stable-diffusion">Stable Diffusion</h2>
<p>Stable Diffusion is a fully open-source (thank you Stability.ai) deep learning text to image and image to image model. For more information on the model, checkout the wikipedia <a href="https://en.wikipedia.org/wiki/Stable_Diffusion">entry</a> for the same.</p>
<section id="pytorch" class="level3">
<h3 class="anchored" data-anchor-id="pytorch">PyTorch</h3>
<p>To use PyTorch on Intel GPUs, we need to install, the Intel extensions for PyTorch or <a href="https://github.com/intel/intel-extension-for-pytorch">ipex</a>. Let’s get the latest release for <a href="https://github.com/intel/intel-extension-for-pytorch/releases/download/v1.10.200%2Bgpu/torch-1.10.0a0+git3d5f2d4-cp39-cp39-linux_x86_64.whl">pyTorch</a> and <a href="https://github.com/intel/intel-extension-for-pytorch/releases/download/v1.10.200%2Bgpu/intel_extension_for_pytorch-1.10.200+gpu-cp39-cp39-linux_x86_64.whl">ipex</a>.</p>
<ol type="1">
<li>Create a conda environment with Python 3.9 and install both of the wheels.</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">~</span> → conda create <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-n</span> ipex python=3.9 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-y</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">~</span> → conda activate ipex</span>
<span id="cb2-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">~</span> → pip install ~/Downloads/<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">*</span>.whl</span></code></pre></div></div>
<p>Let’s see how to run the model using PyTorch first,</p>
<ol start="2" type="1">
<li>Install diffusers library and dependencies</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">~</span> → pip install diffusers ftfy transformers Pillow</span></code></pre></div></div>
<ol start="3" type="1">
<li>Run stable diffusion</li>
</ol>
<p>We will use a model from 🤗 maintained by runwayml, <code>runwayml/stable-diffusion-v1-5</code>. To use the model, you will have to <a href="https://huggingface.co/docs/hub/security-tokens">generate</a> a User access token for the 🤗 model hub. Once generated we can easily download the model using diffusers API. Now that we have installed all the required packages and have the user token, lets try it out:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> intel_extension_for_pytorch</span>
<span id="cb4-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb4-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> diffusers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StableDiffusionPipeline</span>
<span id="cb4-4"></span>
<span id="cb4-5">model_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"runwayml/stable-diffusion-v1-5"</span></span>
<span id="cb4-6">prompt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vivid red hot air ballons over paris in the evening"</span></span>
<span id="cb4-7">pipe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> StableDiffusionPipeline.from_pretrained(</span>
<span id="cb4-8">    model_id,</span>
<span id="cb4-9">    torch_dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.float16,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># this can be torch.float32 as well</span></span>
<span id="cb4-10">    revision<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fp16"</span>,</span>
<span id="cb4-11">    use_auth_token<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"&lt;the token you generated&gt;"</span>)</span>
<span id="cb4-12">pipe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pipe.to(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"xpu"</span>)</span>
<span id="cb4-13">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pipe(prompt).images[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb4-14">image.save(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>prompt[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">.png"</span>)</span></code></pre></div></div>
<p>Executing this, we get the result:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>]: image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pipe(prompt).images[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb5-2">   ...: </span>
<span id="cb5-3"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%|</span>██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">51</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">51</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">35</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>,  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.43</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">it</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>s]</span>
<span id="cb5-4">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>]: image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pipe(prompt).images[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb5-5"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%|</span>██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">51</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">51</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>,  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.20</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">it</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>s]</span></code></pre></div></div>
<p><img src="https://blog.rahul.onl/posts/images/sd_pyt_fp16.png" class="img-fluid"></p>
<p>As you can see the first time you run the model, it takes about 35 seconds, subsequent runs take about 10 seconds, you can expect this number to double when using fp32.</p>
</section>
<section id="tensorflow" class="level3">
<h3 class="anchored" data-anchor-id="tensorflow">TensorFlow</h3>
<p>Moving on to TensorFlow, we have this awesome repo from <a href="https://github.com/divamgupta/stable-diffusion-tensorflow">divamgupta</a></p>
<ol start="2" type="1">
<li>Install stable_diffusion_tensorflow package and dependencies</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">~</span> → pip install git+https://github.com/divamgupta/stable-diffusion-tensorflow ftfy pillow tqdm regex tensorflow-addons</span></code></pre></div></div>
<ol start="3" type="1">
<li>Run stable diffusion</li>
</ol>
<p>Running the TensorFlow model is straightforward as there are no user tokens or anything like that required.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> intel_extension_for_tensorflow</span>
<span id="cb7-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tensorflow</span>
<span id="cb7-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> stable_diffusion_tf.stable_diffusion <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StableDiffusion</span>
<span id="cb7-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> PIL <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image</span>
<span id="cb7-5"></span>
<span id="cb7-6">prompt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vivid red hot air ballons over paris in the evening"</span></span>
<span id="cb7-7">generator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> StableDiffusion(</span>
<span id="cb7-8">    img_height<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>,</span>
<span id="cb7-9">    img_width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>,</span>
<span id="cb7-10">    jit_compile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb7-11">)</span>
<span id="cb7-12"></span>
<span id="cb7-13">img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> generator.generate(</span>
<span id="cb7-14">    prompt,</span>
<span id="cb7-15">    num_steps<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>,</span>
<span id="cb7-16">    unconditional_guidance_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">7.5</span>,</span>
<span id="cb7-17">    temperature<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb7-18">    batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb7-19">)</span>
<span id="cb7-20">Image.fromarray(img[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]).save(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sd_tf_fp32.png"</span>)</span></code></pre></div></div>
<p>Executing this, we get the result:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2022</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">23</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">51.948547</span>: I tensorflow<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>core<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>grappler<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>optimizers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>custom_graph_optimizer_registry.cc:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">114</span>] Plugin optimizer <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> device_type XPU <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> enabled.</span>
<span id="cb8-2">  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>   <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%|</span>█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>,  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.21</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">s</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>it]</span>
<span id="cb8-3"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2022</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">23</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">55.103111</span>: I tensorflow<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>core<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>grappler<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>optimizers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>custom_graph_optimizer_registry.cc:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">114</span>] Plugin optimizer <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> device_type XPU <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> enabled.</span>
<span id="cb8-4">  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>   <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%|</span>█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">00</span>,  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.67</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">it</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>s]</span></code></pre></div></div>
<p><img src="https://blog.rahul.onl/posts/images/sd_tf_fp32.png" class="img-fluid"></p>
<p>As you can see the first time you run the model, it takes about 60 seconds, subsequent runs take about 30 seconds. One thing to note here is that, for the TensorFlow version we used FP32 and not FP16 as in the case of pyTorch.</p>
</section>
</section>
<section id="repo" class="level2">
<h2 class="anchored" data-anchor-id="repo">Repo</h2>
<p>You can find the full code and other related materials <a href="https://github.com/rahulunair/stable_diffusion_arc">here</a>.</p>


</section>

 ]]></description>
  <category>intel</category>
  <category>dgpu</category>
  <category>graphics</category>
  <category>arc</category>
  <category>pytorch</category>
  <category>tensorflow</category>
  <guid>https://blog.rahul.onl/posts/2022-09-06-arc-dgpu-stable-diffusion.html</guid>
  <pubDate>Sun, 06 Nov 2022 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Configure Intel Arc A370M Xe-HPG discrete GPU on Linux</title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2022-08-12-arc-dgpu-linux.html</link>
  <description><![CDATA[ 






<p>These instructions are for Ubuntu 22.04 LTS-based Oses. I am using Pop!_OS 22.04 LTS derivative of Ubuntu 22.04.</p>
<section id="configure-linux-kernel" class="level2">
<h2 class="anchored" data-anchor-id="configure-linux-kernel">Configure Linux kernel</h2>
<ol type="1">
<li>Install the latest available Linux kernel. For example, I have installed <strong>kernel 6.0</strong></li>
</ol>
<p>Install a recent version of the kernel. The easiest way to install a different kernel is by using <a href="https://github.com/bkw777/mainline">Mainline</a>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → add-apt-repository ppa:cappelikan/ppa</span>
<span id="cb1-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → apt update</span>
<span id="cb1-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → apt install mainline</span></code></pre></div></div>
<p>As seen in the screenshot below, I am using Kernel 6.0.0:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://user-images.githubusercontent.com/45503355/195398959-c28fe9f3-47c9-46cd-b1a0-5e26d8e6228a.png" class="img-fluid figure-img"></p>
<figcaption>Mainline kernel installer</figcaption>
</figure>
</div>
<p>After installing the kernel, please restart the machine.</p>
<ol start="2" type="1">
<li>As Arc dGPUs support are still <code>experimental</code> in the kernel, you will have to force the dGPU to be detected. This can be done using the kernel force_probe parameter <code>i915.force_probe=&lt;device_id&gt;</code> for the Intel i915 HD graphics driver. This will force probe the driver for new Intel graphics devices that are recognized by the kernel but not adequately supported. Hopefully, you wouldn’t have to do that with a newer version of the kernel. I am using a <a href="https://www.lenovo.com/us/en/p/laptops/yoga/yoga-2-in-1-series/yoga-7i-gen-7-(16-inch-intel)">Yoga 7i (16” Intel) with Intel Arc Graphics</a> which has the Intel® Arc™ A370M discrete Graphics card (dgpu) along with an integrated Intel® UHD Graphics. The device id for this dgpu is <code>5693</code>, and you can find the device id of the card either by looking at i915 logs using <code>sudo dmesg | grep -i i915</code> or from Intel’s gpu <a href="https://dgpu-docs.intel.com/devices/hardware-table.html">hardware table</a>.</li>
</ol>
<p>Pop!_OS 22.04 LTS uses systemd to manage kernel boot params, to force i915 driver to enable the dgpu use <code>kernelstub</code> tool:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → kernelstub <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-a</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"i915.force_probe=5693"</span></span></code></pre></div></div>
<p>After this restart the machine and check i915 logs using <code>dmesg</code> to see if the graphics card has been detected:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → dmesg <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> i915</span></code></pre></div></div>
<p>You should see an output like this:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> →  dmesg <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> i915</span>
<span id="cb4-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    0.000000] Command line: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">initrd=\EFI\Pop_OS-97fe6a26-7d8a-4120-89db-8f2130b644b7\initrd.img</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">root</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>UUID=97fe6a26-7d8a-4120-89db-8f2130b644b7 <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ro</span> quiet loglevel=0 systemd.show_status=false splash i915.force_probe=5693</span>
<span id="cb4-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    0.047217] Kernel command <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">line:</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">initrd</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\E</span>FI<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\P</span>op_OS-97fe6a26-7d8a-4120-89db-8f2130b644b7<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\i</span>nitrd.img <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">root</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>UUID=97fe6a26-7d8a-4120-89db-8f2130b644b7 <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ro</span> quiet loglevel=0 systemd.show_status=false splash i915.force_probe=5693</span>
<span id="cb4-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.775328] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> VT-d active for gfx access</span>
<span id="cb4-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.775383] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">vgaarb:</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">deactivate</span> vga console</span>
<span id="cb4-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.775416] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Using Transparent Hugepages</span>
<span id="cb4-7"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.775979] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">vgaarb:</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">changed</span> VGA decodes: olddecodes=io+mem,decodes=none:owns=io+mem</span>
<span id="cb4-8"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.777234] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Finished loading DMC firmware i915/adlp_dmc_ver2_16.bin <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">v2.16</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb4-9"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.912397] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC firmware i915/adlp_guc_70.1.1.bin version 70.1</span>
<span id="cb4-10"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.912399] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> HuC firmware i915/tgl_huc_7.9.3.bin version 7.9</span>
<span id="cb4-11"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.926153] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> HuC authenticated</span>
<span id="cb4-12"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.926448] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC submission enabled</span>
<span id="cb4-13"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.926449] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC SLPC enabled</span>
<span id="cb4-14"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.927353] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC RC: enabled</span>
<span id="cb4-15"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    1.930736] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Protected Xe Path <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">PXP</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">protected</span> content support initialized</span>
<span id="cb4-16"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.769893] <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">drm</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span> Initialized <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">i915</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">1.6.0</span> 20201103 for 0000:00:02.0 on minor 0</span>
<span id="cb4-17"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.775461] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">enabling</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">device</span> <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">0000</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> 0002<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb4-18"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.775491] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Incompatible option enable_guc=3 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-</span> HuC is not supported!</span>
<span id="cb4-19"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.776346] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> VT-d active for gfx access</span>
<span id="cb4-20"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.776472] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Local memory IO size: 0x00000003fa000000</span>
<span id="cb4-21"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.776476] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Local memory available: 0x00000003fa000000</span>
<span id="cb4-22"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.787361] fbcon: i915drmfb <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(fb0)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">is</span> primary device</span>
<span id="cb4-23"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.787366] i915 0000:00:02.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> fb0: i915drmfb frame buffer device</span>
<span id="cb4-24"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    3.796583] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> Finished loading DMC firmware i915/dg2_dmc_ver2_06.bin <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">v2.6</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb4-25"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    5.326692] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> failed to retrieve link info, disabling eDP</span>
<span id="cb4-26"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    5.428126] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC firmware i915/dg2_guc_70.1.2.bin version 70.1</span>
<span id="cb4-27"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    5.442889] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC submission enabled</span>
<span id="cb4-28"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    5.442892] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC SLPC enabled</span>
<span id="cb4-29"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">[</span>    5.443378] i915 0000:03:00.0: <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">[drm</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">]</span> GuC RC: enabled</span></code></pre></div></div>
<p>The dg2_guc is loaded as seen in the above line: <strong>[ 5.428126] i915 0000:03:00.0: [drm] GuC firmware i915/dg2_guc_70.1.2.bin version 70.1</strong>. Both the igpu and dgpu is detected and also the firmware is loaded. If drm verification fails and <a href="https://01.org/linuxgraphics/downloads/firmware">GuC</a> is not loaded, install the latest linux firmware from this <a href="https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/">link</a>:</p>
<p>You can install the latest firmware files by cloning the repo and moving it to <code>/lib/firmware</code> (<strong>warning</strong>: this is a brute-force approach):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb5-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> →  git clone https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/</span>
<span id="cb5-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> →  cd linux-firmware <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">&amp;&amp;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">yes</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cp</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-r</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">*</span> /lib/firmware</span></code></pre></div></div>
<p>For me, the firmware that came with Pop!_OS 22.04 LTS worked, i didn’t have to install the latest ones.</p>
</section>
<section id="setup-open-source-mesa-3d-graphics-libraries-for-opengl-and-vulkan" class="level2">
<h2 class="anchored" data-anchor-id="setup-open-source-mesa-3d-graphics-libraries-for-opengl-and-vulkan">Setup Open source Mesa 3d Graphics libraries for OpenGL and Vulkan</h2>
<ol type="1">
<li>Install drivers</li>
</ol>
<p>Now, if you want media and graphics support beyond compute, install bleeding edge Mesa libraries from <a href="https://launchpad.net/~oibaf/+archive/ubuntu/graphics-drivers">oiabf ppa</a> that provides open graphics drivers; you can do it by:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → add-apt-repository ppa:oibaf/graphics-drivers</span>
<span id="cb6-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → apt-update</span>
<span id="cb6-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → apt-upgrade</span>
<span id="cb6-4"></span>
<span id="cb6-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → dpkg <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-l</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> mesa</span>
<span id="cb6-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  libegl-mesa0:amd64                                                      22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        free implementation of the EGL API <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> Mesa vendor library</span>
<span id="cb6-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  libgl1-mesa-dri:amd64                                                   22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        free implementation of the OpenGL API <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> DRI modules</span>
<span id="cb6-8"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  libglapi-mesa:amd64                                                     22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        free implementation of the GL API <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> shared library</span>
<span id="cb6-9"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  libglu1-mesa:amd64                                                      9.0.2-1                                                           amd64        Mesa OpenGL utility library <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">GLU</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb6-10"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  lib</span>
<span id="cb6-11"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">-mesa0:amd64</span>                                                      22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        free implementation of the OpenGL API <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> GLX vendor library</span>
<span id="cb6-12"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  mesa-utils                                                              8.4.0-1ubuntu1                                                    amd64        Miscellaneous Mesa utilities <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> symlinks</span>
<span id="cb6-13"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  mesa-utils-bin:amd64                                                    8.4.0-1ubuntu1                                                    amd64        Miscellaneous Mesa utilities <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> native applications</span>
<span id="cb6-14"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  mesa-va-drivers:amd64                                                   22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        Mesa VA-API video acceleration drivers</span>
<span id="cb6-15"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  mesa-vdpau-drivers:amd64                                                22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        Mesa VDPAU video acceleration drivers</span>
<span id="cb6-16"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ii</span>  mesa-vulkan-drivers:amd64                                               22.3~git2210120600.ddc5c3~oibaf~j                                 amd64        Mesa Vulkan graphics drivers</span></code></pre></div></div>
<p>Fair warning, be careful as these drivers are bleeding edge and, by design, may not be stable. After installing the Mesa drivers, you should be able to run glx and Vulkan benchmarks.</p>
<ol start="2" type="1">
<li>Check if opengl detects the dgpu using glxinfo</li>
</ol>
<p>Install glxinfo from apt repo mesa-utils</p>
<p>To use the dGPU, set the env variable <code>DRI_PRIME=1</code>, <a href="https://wiki.archlinux.org/title/PRIME">PRIME</a> is a technology in Linux that uses open source graphics drivers to use <code>switchable graphics</code> and install glxinfo from apt repo mesa-utils.</p>
<p>Here is the output of glxinfo without setting <code>DRI_PRIME</code> environment variable:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb7-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → glxinfo <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-B</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> device</span>
<span id="cb7-2">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device:</span> Mesa Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">ADL</span> GT2<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">0x46a6</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>After setting the environment variable for PRIME:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb8-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → export DRI_PRIME=1</span>
<span id="cb8-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → glxinfo <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-B</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> device</span>
<span id="cb8-3">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device:</span> Mesa Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Arc</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">tm</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">A370M</span> Graphics <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">DG2</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">0x5693</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>As you can the dgpu is recognized by Mesa OpenGL. yay!</p>
<ol start="3" type="1">
<li>Let’s try to run a benchmark on the Arc gpu to see how it performs. I am using glmark2, which can be installed on Ubuntu-based OSes easily using:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb9-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → apt-get install glmark2</span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb10-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → export DRI_PRIME=1</span>
<span id="cb10-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → glxinfo <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-B</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> device</span>
<span id="cb10-3">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device:</span> Mesa Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Arc</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">tm</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">A370M</span> Graphics <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">DG2</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">0x5693</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb10-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → glmark2</span></code></pre></div></div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://blog.rahul.onl/posts/assets/arc370m_bench.gif" class="img-fluid figure-img"></p>
<figcaption>glmark2 running on Arc 370m dGPU</figcaption>
</figure>
</div>
<ol start="4" type="1">
<li>Now, let’s install the intel compute drivers. <a href="https://github.com/intel/compute-runtime/releases">Goto</a>. Get the latest release and install using the deb packages for OpenCL, level zero, igc etc.</li>
</ol>
<p>As of this writing, the latest compute driver release version is <a href="https://github.com/intel/compute-runtime/releases/tag/22.39.24347">22.39.24347</a>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb11-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → cd /tmp <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">&amp;&amp;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mkdir</span> compute_drivers</span>
<span id="cb11-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → cd compute_drivers</span>
<span id="cb11-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-1.0.12149.1/intel-igc-core_1.0.12149.1_amd64.deb</span>
<span id="cb11-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-1.0.12149.1/intel-igc-opencl_1.0.12149.1_amd64.deb</span>
<span id="cb11-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → wget https://github.com/intel/compute-runtime/releases/download/22.39.24347/intel-level-zero-gpu_1.3.24347_amd64.deb</span>
<span id="cb11-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → wget https://github.com/intel/compute-runtime/releases/download/22.39.24347/intel-opencl-icd_22.39.24347_amd64.deb</span>
<span id="cb11-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → wget https://github.com/intel/compute-runtime/releases/download/22.39.24347/libigdgmm12_22.2.0_amd64.deb</span>
<span id="cb11-8"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → dpkg <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">*</span>.deb</span></code></pre></div></div>
<p>Now that the compute drivers are installed let’s see if OpenCL can detect the dgpu. Install <code>clinfo</code> from apt and check using:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb12-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → clinfo <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0x5690"</span></span>
<span id="cb12-2">  <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device</span> Name                                     Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb12-3">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device</span> Name                                   Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb12-4">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device</span> Name                                   Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb12-5">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Device</span> Name                                   Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span></code></pre></div></div>
<p>We can see that the dgpu has been detected.</p>
</section>
<section id="install-oneapi-basekit-and-device-discovery-using-sycl" class="level2">
<h2 class="anchored" data-anchor-id="install-oneapi-basekit-and-device-discovery-using-sycl">Install oneAPI basekit and device discovery using sycl</h2>
<ol type="1">
<li>Finally, install the oneapi basekit to use the dpcpp runtime. I used 2022.2.0 version of oneapi basekit.</li>
</ol>
<p>Please refer to <a href="https://www.intel.com/content/www/us/en/develop/documentation/installation-guide-for-intel-oneapi-toolkits-linux/top/installation/install-using-package-managers/apt.html#apt">oneAPI installation guide</a> to install using the <code>apt</code> package manager.</p>
<p>Source the oneAPI environment using:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb13-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">→</span> source /opt/intel/oneapi/setvars.sh</span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb14-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">~</span> → dpcpp <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-v</span></span>
<span id="cb14-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Intel</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">oneAPI</span> DPC++/C++ Compiler 2022.2.0 <span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">2022.2.0.20220730</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb14-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Target:</span> x86_64-unknown-linux-gnu</span>
<span id="cb14-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Thread</span> model: posix</span>
<span id="cb14-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">InstalledDir:</span> /opt/intel/oneapi/compiler/2022.2.0/linux/bin-llvm</span>
<span id="cb14-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Found</span> candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11</span>
<span id="cb14-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Selected</span> GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11</span>
<span id="cb14-8"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Candidate</span> multilib: .<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">;</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">@m64</span></span>
<span id="cb14-9"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Selected</span> multilib: .<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">;</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">@m64</span></span></code></pre></div></div>
<ol start="2" type="1">
<li>Device discovery using sycl-ls see if sycl can detect the dgpu:</li>
</ol>
<p>Intel dgpus like the A370m are represented as SYCL devices. <code>sycl-ls</code> is a tool that is part of the oneAPI basekit that can show all the detected devices and all the SYCL backends support by the runtime. Once the oneapi basekit has been installed, source the environment using:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb15-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → source /opt/intel/oneapi/setvars.sh </span></code></pre></div></div>
<p>Device discovery using syclto see if sycl can detect the dgpu:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb16-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → sycl-ls</span>
<span id="cb16-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">[opencl:acc:0]</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">FPGA</span> Emulation Platform for OpenCL<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">TM</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">,</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">FPGA</span> Emulation Device 1.2 <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">2022.14.7.0.30_160000</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb16-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">[opencl:cpu:1]</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">OpenCL,</span> 12th Gen Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Core</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">TM</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">i7-12700H</span> 3.0 <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">2022.14.7.0.30_160000</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb16-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">[opencl:gpu:2]</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">OpenCL</span> HD Graphics, Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span> 3.0 <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">22.40.024349</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb16-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">[opencl:gpu:3]</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">OpenCL</span> HD Graphics, Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x46a6</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span> 3.0 <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">22.40.024349</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb16-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">[ext_oneapi_level_zero:gpu:0]</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Level-Zero,</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span> 1.3 <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">1.3.24349</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb16-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">[ext_oneapi_level_zero:gpu:1]</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Level-Zero,</span> Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x46a6</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span> 1.3 <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">1.3.24349</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span></code></pre></div></div>
<p>To get a more verbose output, use, <code>sycl-ls --verbose</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb17-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → sycl-ls <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--verbose</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-i</span> name</span>
<span id="cb17-2">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>     : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">FPGA</span> Emulation Platform for OpenCL<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">TM</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span></span>
<span id="cb17-3">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">FPGA</span> Emulation Device</span>
<span id="cb17-4">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>     : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">OpenCL</span></span>
<span id="cb17-5">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : 12th Gen Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Core</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">TM</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">i7-12700H</span></span>
<span id="cb17-6">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>     : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">OpenCL</span> HD Graphics</span>
<span id="cb17-7">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb17-8">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>     : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">OpenCL</span> HD Graphics</span>
<span id="cb17-9">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x46a6</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb17-10">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>     : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Level-Zero</span></span>
<span id="cb17-11">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x5693</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb17-12">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : Intel<span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">(</span><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">R</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Graphics</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0x46a6</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb17-13">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>     : SYCL host platform</span>
<span id="cb17-14">        <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Name</span>       : SYCL host device</span></code></pre></div></div>
<p>As seen above 2 GPU devices are detected by the SYCL runtime and are supported using both OpenCL and Level-Zero drivers.</p>
<p>We now have configured the machine with all the required software stack to fully utilize the discrete gpu available on the laptop. These instructions can be used to enable any Arc discrete GPUs like the A370m, A770m, A770, A750 etc on Linux.</p>
</section>
<section id="intels-system-monitoring-utility-to-monitor-the-dgpu" class="level2">
<h2 class="anchored" data-anchor-id="intels-system-monitoring-utility-to-monitor-the-dgpu">Intel’s System Monitoring Utility to monitor the dgpu</h2>
<ol type="1">
<li>Install sysmon</li>
</ol>
<p><code>sysmon</code> is a tool similar to <code>top</code> for cpu, that is part of Intel’s <a href="https://github.com/intel/pti-gpu/tree/master/tools/sysmon">Platform Tools Interfaces for GPU</a>. <code>sysmon</code> helps in monitoring the Intel gpu parameters like frequency, memory, etc. The tool can be installed using:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb18-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → git clone https://github.com/intel/pti-gpu/</span>
<span id="cb18-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → cd pti-gpu/tools/sysmon</span>
<span id="cb18-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → mkdir build <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">&amp;&amp;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">cd</span> build</span>
<span id="cb18-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">Coding</span> → cmake <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-DCMAKE_BUILD_TYPE</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Release .. <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">&amp;&amp;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">make</span></span></code></pre></div></div>
<ol start="2" type="1">
<li>After successfully building <code>sysmon</code> let’s check the dgpu frequency:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb19-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">./sysmon</span></span></code></pre></div></div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://user-images.githubusercontent.com/45503355/195416715-923dc33a-acbd-411e-a774-7a38c13e72f3.png" class="img-fluid figure-img"></p>
<figcaption>system monitor output on my laptop</figcaption>
</figure>
</div>
<p>As seen above both the igpu and dgpu performance can be monitored using the tool.</p>
</section>
<section id="acknowledgements" class="level2">
<h2 class="anchored" data-anchor-id="acknowledgements">Acknowledgements</h2>
<p>I wouldn’t have been able to do this without the help of <a href="https://github.com/sanchitintel"><span class="citation" data-cites="sanchitintel">@sanchitintel</span></a> and <a href="https://github.com/gujinghui"><span class="citation" data-cites="gujingui">@gujingui</span></a>. Also, <a href="https://www.phoronix.com/review/intel-arc-graphics-linux">Phoronix</a> has been publishing updates on the best way to enable Intel Arc dGPU, detailing the version of the kernel, mesa drivers, etc. That was my start in setting up the software stack.</p>
</section>
<section id="something-not-working" class="level2">
<h2 class="anchored" data-anchor-id="something-not-working">Something not working?</h2>
<p>Please create an <a href="https://github.com/rahulunair/intel_arc_dgpu_linux/issues">issue</a> here to track any issues with these steps.</p>
</section>
<section id="citation" class="level2">
<h2 class="anchored" data-anchor-id="citation">Citation</h2>
<p>If you are using this information, please cite using the below link:</p>
<p>Unnikrishnan Nair, R. (2022). dgpu_setup_pytorch (Version 1.0.0) [Computer software]. https://github.com/rahulunair/intel_arc_dgpu_linux</p>


</section>

 ]]></description>
  <category>intel</category>
  <category>dgpu</category>
  <category>graphics</category>
  <guid>https://blog.rahul.onl/posts/2022-08-12-arc-dgpu-linux.html</guid>
  <pubDate>Wed, 12 Oct 2022 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2021-03-22-rust-type.html</link>
  <description><![CDATA[ 






<section id="flashcard-rust-what-type-is-this-variable-again" class="level1">
<h1>Flashcard Rust: What type is this variable again?!</h1>
<p>This is going to be a very short post on a tiny function that can help us in figuring out what is the type of a variable.</p>
<p>This is helpful to me personally when learning rust and after some hours of coding, I want to know what is the type of a variable quickly, which is not easy always.I need to thank <a href="https://twitter.com/timClicks"><span class="citation" data-cites="timClicks">@timClicks</span></a> for showing this in one of his streams on youtube. If you are learning Rust and is looking for a book, let me please recommend <a href="https://www.manning.com/books/rust-in-action">Rust in Action</a> by Tim, it is an excellent in-depth introduction to Rust.</p>
<section id="what-is-it" class="level2">
<h2 class="anchored" data-anchor-id="what-is-it">What is it ?</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">std::any::</span>type_name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// what is the type of the passed argument</span></span>
<span id="cb1-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> what_type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>T) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-5">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"type is: {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">type_name::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p><code>type_name</code> function from the <code>std</code> crate returns the name of a type as a string slice.</p>
<p>Before knowing about this function available from the std crate(reminder to self, to read the standard library docs!), i tended to use the ide introspection features to confirm what the type of a variable was at times or use a <code>()</code> as type and the compiler complains to me that the type is something else, which is what i wanted to known in the first place, but know I have a shiny new function that I can use, lets see how it works.</p>
</section>
<section id="how-is-it-used" class="level2">
<h2 class="anchored" data-anchor-id="how-is-it-used">How is it used ?</h2>
<p>Let’s take a simple example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> number <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3232</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Rahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>to_string()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> list_of_nums <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">vec!</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> ]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-5">    what_type(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>number)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-6">    what_type(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-7">    what_type(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>list_of_nums)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>That is it, and it will print the type of the variable passed into the what_type function as below:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span>: i32</span>
<span id="cb3-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span>: alloc::string::String</span>
<span id="cb3-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span>: alloc::vec::Vec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>i32<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p><a href="https://doc.rust-lang.org/std/any/fn.type_name.html">type_name</a></p>
</section>
<section id="end" class="level2">
<h2 class="anchored" data-anchor-id="end">End</h2>
<p>Like I said a short post about a really useful(hopefully) function in Rust.</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <category>rust</category>
  <guid>https://blog.rahul.onl/posts/2021-03-22-rust-type.html</guid>
  <pubDate>Mon, 22 Mar 2021 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2021-01-17-rust-turbofish.html</link>
  <description><![CDATA[ 






<section id="flashcard-rust-colon-colon-angle-bracket-or-turbofish" class="level1">
<h1>Flashcard Rust: Colon colon angle bracket or turbofish!</h1>
<p>This confused me a lot when i started learning rust and the heading <code>colon colon angle braket</code> is what I searched for first when I saw this syntax, but the official name of this syntax within the Rust community is <strong>turbofish</strong>.</p>
<section id="what-is-it" class="level2">
<h2 class="anchored" data-anchor-id="what-is-it">What is it ?</h2>
<p>It is to specify a concrete type, for a function, a struct, a method or an enum. The syntax of <strong>turbofish</strong> looks like:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>
<p>It looks kinda like a fish I guess, the name <strong>turbofish</strong>, check <a href="https://twitter.com/steveklabnik/status/659034597062262784">steve klabnik’s</a> official explanation <a href="https://github.com/steveklabnik/rust/commit/4f22b4d1dbaa14da92be77434d9c94035f24ca5d#commitcomment-14014176">here</a> for more details.</p>
</section>
<section id="how-is-it-used" class="level2">
<h2 class="anchored" data-anchor-id="how-is-it-used">How is it used ?</h2>
<p>Let’s take a simple example, to parse a string into float,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pi_string <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.1415"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pi_float <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi_string<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>parse()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>unwrap()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-4">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> pi_float)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>This program will not compile as <code>parse</code> function is too generic, and the rust compiler being helpful as always tell us to give a time annotation to the variable <code>pi_float</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"> Compiling turbofish v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.0</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>Users<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>unrahul<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>Coding<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>rust<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>learn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>turbofish)</span>
<span id="cb3-2">error[E0282]: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span> annotations needed</span>
<span id="cb3-3"> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--&gt;</span> src<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>main.rs:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span></span>
<span id="cb3-4">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb3-5"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>     let pi_float <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi_string.parse().unwrap()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-6">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>         <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^^^^^^^^</span> consider giving `pi_float` a <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span></span></code></pre></div></div>
<p>This can be solved in two ways, either we use a <code>turbofish</code> notation for <code>parse</code> function or use type annotation, let’s see how we can use <code>turbofish</code> to solve this.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pi_string <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.1415"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pi_float <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi_string<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">parse::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">f32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>unwrap()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-4">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> pi_float)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>We tell the compile, which <strong>concrete</strong> type is being parsed using <code>parse</code>, and the code compiles:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">Compiling turbofish v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.0</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>Users<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>unrahul<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>Coding<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>rust<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>learn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>turbofish)</span>
<span id="cb5-2">Finished dev [unoptimized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> debuginfo] target(s) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.21</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">s</span></span>
<span id="cb5-3">Running `target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>debug<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>turbofish`</span>
<span id="cb5-4"><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.1415</span></span></code></pre></div></div>
<p>Lastly, let’s try the compiler suggested fix, that is to use type annotation:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb6-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pi_string <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.1415"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pi_float <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">f32</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi_string<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>parse()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>unwrap()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-4">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> pi_float)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Yup, that works too!, as shown below:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">Compiling turbofish v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.0</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>Users<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>unrahul<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>Coding<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>rust<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>learn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>turbofish)</span>
<span id="cb7-2">Finished dev [unoptimized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> debuginfo] target(s) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.21</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">s</span></span>
<span id="cb7-3">Running `target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>debug<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>turbofish`</span>
<span id="cb7-4"><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.1415</span></span></code></pre></div></div>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p><a href="https://matematikaadit.github.io/posts/rust-turbofish.html">Where to put turbofish</a><br> <a href="https://techblog.tonsser.com/posts/what-is-rusts-turbofish">What is Rust’s turbofish</a></p>
</section>
<section id="end" class="level2">
<h2 class="anchored" data-anchor-id="end">End</h2>
<p>This was a quick introduction to the <strong>turbofish</strong> notation and how it is used.</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <category>rust</category>
  <guid>https://blog.rahul.onl/posts/2021-01-17-rust-turbofish.html</guid>
  <pubDate>Sun, 17 Jan 2021 08:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2021-01-14-rust-result.html</link>
  <description><![CDATA[ 






<section id="flashcard-rust-result-type-in-rust-and-how-to-handle-it" class="level1">
<h1>Flashcard Rust: Result Type in Rust and how to handle it</h1>
<p>Rust <code>Result</code> is a type used to return / propogate errors from a function to the caller. It is an <code>Enum</code> with two variants - an <code>Ok(T)</code> and an <code>Err(E)</code>. An <code>Ok(T)</code> represents success and error represents failure.</p>
<figure align="center" class="figure">
<img src="https://i.imgur.com/lxPnX5U.jpg" alt="Result type holds two variants" class="figure-img">
<figcaption>
Rust Result Type
</figcaption>
</figure>
<p>In code it looks like:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">enum</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Result</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> E<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-2">  <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(T)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb1-3">  <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Err</span>(E)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb1-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Let’s use a simple program to see how Result type can be used and handled. The program below has two functions, an <code>is_even</code> and the <code>main</code> function:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// a simple program that shows how to use Result Type in Rust</span></span>
<span id="cb2-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">std::io::</span>stdin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// check if a number is even or odd</span></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// return a Result type (Ok(String) if even, Err(String) if odd)</span></span>
<span id="cb2-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> is_even(n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Result</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> even <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">match</span> even <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-9">        <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">format!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{} is even!"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> n))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-10">        _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Err</span>(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">format!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{} is not even!"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> n))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-11">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-12"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-13"></span>
<span id="cb2-14"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-15">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// read input from stdin</span></span>
<span id="cb2-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> input <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>new()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-17">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enter an integer: "</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-18">    stdin()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>read_line(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> input)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enter an integer!"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-19"></span>
<span id="cb2-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// parse String as u32, returns a Result type</span></span>
<span id="cb2-21">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> input <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>trim()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">parse::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>unwrap()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-22"></span>
<span id="cb2-23">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// is_even function returns a custom Result type</span></span>
<span id="cb2-24">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> is_even(input)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>unwrap()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-25">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{:?}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> res)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-26"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>As the name suggests, <code>is_even</code> is used to check if a digit is even or odd, it returns a Result Type, both <code>Ok</code> and <code>Err</code> variants of the type returns a String in case the digit is even or failure (Error) if its odd.</p>
<p>Let’s see how the program works, building and running the program using <code>cargo</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">➜  results git:(master) ✗ cargo build <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> cargo run</span>
<span id="cb3-2">enter an integer:</span>
<span id="cb3-3"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"2 is even!"</span></span>
<span id="cb3-5">➜  results git:(master) ✗</span></code></pre></div></div>
<p>That worked as expected, we gave <code>2</code> and it printed on the screen <code>2 is even</code>.</p>
<p>Now if we give an odd number, let’s see what happens:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">➜  results git:(master) ✗ cargo build <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> cargo run</span>
<span id="cb4-2">enter an integer:</span>
<span id="cb4-3"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb4-4">thread <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'main'</span> panicked at <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'called `Result::unwrap()` on an `Err` value: "1 is not even!"'</span>, src<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>main.rs:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">24</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb4-5">note: run <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> `RUST_BACKTRACE<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>` environment variable to display a backtrace</span></code></pre></div></div>
<p>The program panicked with an Error value, <code>"1 is not even!"</code>. That is not great, error handling to say the least.</p>
<p>The <code>main</code> function has a few other things going on as well, the line:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb5-1">stdin()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>read_line(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> input)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enter an integer"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>tries to read a line of input from standard input as a String owned by the variable <code>input</code>, if it fails, the program panics and outputs, “enter an integer”.</p>
<p>The line:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> input <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>trim()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">parse::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"error in parsing input"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>trims the input string and tries to parse the value as an unsigned integer, it uses the same variable <code>input</code> to assign its result, this is called <code>shadowing</code> in Rust, if you are not familar with it, please <a href="https://rahul.onl/coding/2020/03/16/vars.html">see</a></p>
<p>Now that you understand the program, let’s talk about the ways to handle a Result type. There are three ways in general to handle a Result type:</p>
<ol type="1">
<li><p><code>unwrap</code> - This is the simplest case, here it essentially means, we don’t care about the error, and tells the program to try to get the success (<code>Ok</code>) value and if the call results in a failure (<code>Err</code>), panic. This is okay in the case we are writing simple scripts, or knows for sure that there should be an <code>Ok</code> value, or if we, you know are lazy.</p></li>
<li><p><code>?</code> - It is a short hand notation in Rust, which basically tries to unwrap a value if it’s a success (<code>Ok</code>) or if it’s a failure returns an <code>Err</code>. As it can have two possible variants, and <code>errors</code> have to be handled some way, <code>?</code> can only be used inside functions that returns a Result Type.</p></li>
</ol>
<p>We could use it in our program, but we will have to change the signature of our <code>main</code> to:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Result</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> std<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>io<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Error</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-2"></span>
<span id="cb7-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//same code till `let res = ` as original program</span></span>
<span id="cb7-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> is_even(input)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// change unwrap to ?</span></span>
<span id="cb7-5">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(())</span>
<span id="cb7-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>This can be read as if failure, main will exit with an error code, if not main returns nothing a <code>()</code>.</p>
<ol start="3" type="1">
<li>Finally, we come to the most exhaustive way to handle Result type, here, we use a <code>match</code> express for both success (<code>Ok</code>) and failure (<code>Err</code>), to capture and handle all possible scenarios gracefully.</li>
</ol>
<p>To use it in our original program, remove <code>is_even(input).unwrap();</code> line and add:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-2"></span>
<span id="cb8-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//same code till `let res = ` as original program</span></span>
<span id="cb8-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">match</span> is_even(input) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-5">        <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(val) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{:?}, val),</span></span>
<span id="cb8-6"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    Err(err) =&gt; println!("</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{:?},</span> err)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-7">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Doing this, we can avoid our program from panicking and now when we run the program, it doesn’t panic:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">➜  results git:(master) ✗ cargo build <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> cargo run</span>
<span id="cb9-2">enter an integer:</span>
<span id="cb9-3"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"1 is not even!"</span></span>
<span id="cb9-5">➜  results git:(master) ✗ cargo build <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> cargo run</span>
<span id="cb9-6">enter an integer:</span>
<span id="cb9-7"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb9-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"2 is even!"</span></span>
<span id="cb9-9">➜  results git:(master) ✗</span></code></pre></div></div>
<p>yay!, now isn’t this much better than before :) .</p>
<p>So to wrap up, Result type in Rust is an Enum used to handle success and failure scenarios in functions. It can be handled in three ways, using <code>unwrap</code>, using a <code>?</code> or using a <code>match</code> expression.</p>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p>For more details, please read:</p>
<p><a href="https://doc.rust-lang.org/std/result/index.html">Rust docs on Result type</a><br> <a href="https://jakedawkins.com/2020-04-16-unwrap-expect-rust/">Unwrap and Expect in Rust</a><br> <a href="https://learning-rust.github.io/docs/e4.unwrap_and_expect.html">Unrwap and Expect</a></p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>In this post, we got a basic idea of what Results are and how to handle them. Next time, we can see how to handle errors in a bit more detail.</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <category>rust</category>
  <guid>https://blog.rahul.onl/posts/2021-01-14-rust-result.html</guid>
  <pubDate>Thu, 14 Jan 2021 08:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-07-15-ml-forget.html</link>
  <description><![CDATA[ 






<p>In relation to learning new tasks, the phenomenon of a model forgetting how to perform a previously learned task when trained on a new task is called catastrophic forgetting (CF). Catastrophic forgetting can be at fault in online training of similar tasks as well. Ideally for a deep enough network to learn all tasks it has to be presented with all the training data at once. This is often not quite possible because of reasons like memory constraints, security, non-sustainable solution and serious limitations in the online learning environment. This is especially important in reinforcement learning because catastrophic inference is most visible in sequential online tasks. RL methods we use by definition is a sequential online learning algorithm. Here online means the agent has to adapt to the environment in real time.</p>
<section id="simple-methods-to-try-first" class="level2">
<h2 class="anchored" data-anchor-id="simple-methods-to-try-first">Simple methods to try first:</h2>
<ul>
<li>Regularize with dropout and maxout</li>
<li>Store weights for each environment</li>
<li>Take average of these weights and initialize when learning a new environment</li>
<li>Add adaptive learning rate for weights, slow learning rate for weights for common skills for each environment and fast learning rate for new environments</li>
</ul>
</section>
<section id="ideas-to-further-investigate" class="level2">
<h2 class="anchored" data-anchor-id="ideas-to-further-investigate">Ideas to further investigate:</h2>
<ul>
<li>PathNet - For learning similar tasks</li>
<li>Elastic Weight Consolidation - Good for dissimilar tasks</li>
<li>H-DRLN - Hierarchal Deep Life Long RL – - A framework based that combines DQN and lifelong learning techniques</li>
</ul>
<p>Before we dive in, lets see why does a neural network ever have ‘Catastrphic Forgetting’ problem?</p>
<p>Catastrophic Forgetting is not only limited to neural nets; if that was the case, we could have easily replaced it some other learning algorithm. Researchers who studied this problem were of the opinion that the underlying cause is the generalization that a neural net does. The ability of a neural net to distribute and share representation of the relationship between input and an output label helps it to generalize, which is one of the most important properties of a neural net. Thus, each time a new data point (x, y) comes up to be trained, the neural net tries to distribute and share the representation by adjusting the weights of the neural net. This leads to the neural net forgetting earlier representations.</p>
<p>What are some of the possible solutions?</p>
<p>Many methods that detailed below can be explained off as a particular type of regularization. The techniques given below can be considered as a bag of tricks that could be used to limit catastrophic forgetting. As mentioned above, most of these solutions can be explained as a type of regularization and freezing of learned structures. To remember everything is to not change any of the weights or the activation traces of a task. Some methods directly tackle this by freezing weights, others by freezing activation traces of the entire network from input to output.</p>
</section>
<section id="regularization-dropout-and-activation-functions" class="level2">
<h2 class="anchored" data-anchor-id="regularization-dropout-and-activation-functions">Regularization, dropout and activation functions</h2>
<ul>
<li>Regularization</li>
<li>Joint Many-Task model - Successive regularization at each epoch</li>
<li>Dropout with Maxout</li>
</ul>
<p><strong>Regularization</strong> is traditionally used to prevent overfitting; this can be done in many ways. A standard way to do this is to add a norm component to the loss function that is proportional to the square of the weights of a neural network (L2 norm). L2 regularization has the effect of the network preferring to learn smaller weights; as more significant the weight, larger would be the loss value. How this prevents forgetting can be attributed to the fact that, when the weights are small (regularized), small input values will not affect the loss function drastically. This, in turn means, the gradient of the loss would be a smaller value, thus when the weights which are adjusted based on this gradient value will not change much.</p>
<p><strong>Dropout</strong> is used as a regularizing technique. Here how it regularizes can be explained by considering dropout as training a set of neural networks (each time dropping out a set of hidden units), then averaging the result of an ensemble of nets at the end [dropout]. This makes the model robust to losses by not assuming that a set of neurons (thus information) will always be present. Thus, when a new task is learned, the combined effect of a robust and regularized network can to some degree minimize forgetting.</p>
<p>Dropout has been empirically proven to help in adapting to new task while remembering old tasks. It has been suggested to use <strong>maxout</strong> as the activation function when using dropout as a technique to minimize forgetting.</p>
</section>
<section id="weight-freezingslow-updating" class="level2">
<h2 class="anchored" data-anchor-id="weight-freezingslow-updating">Weight freezing/slow updating</h2>
<ul>
<li>Using fast weights to de-blur old memories - Hinton</li>
<li>Elastic Weight Consolidation - Deepmind</li>
</ul>
<p>Here the idea is to not frequently update parameters of a Neural Net when learning new tasks. The larger the activation weights between two nodes for a task, the less chance that these weights should be affected. Hinton worked on this problem in the 80s and designed a network with weights of different rate of plasticity [Fast weights]. A similar approach was chosen by Kirkpatrick and the Deepmind team with the Elastic Weight Consolidation (EWC) technique. Here a constraint is added to the loss function that controls which weights can be updated and which cannot. When a new task is being learned, strong activation paths are not updated, and weights that didn’t contribute much to a previous task is updated first.</p>
<p>The insight that led to EWC is that, in a deep neural network, there can be many different configurations of weights that will give us a similar rate of error for a task. The goal with EWC is to find a set of weights from the parameter space that has low error rate for both the new task and the old one. In this approach the authors consider gradient descent in a Bayesian perspective. Whereas stochastic gradient descent tries to estimate a single parameter (weight), they tried to estimate a parameter for the entire distribution of data (Bayesian estimate), now this is not tractable, so what they do is that they use a trick called Laplace approximation and they call their approach EWC. By learning a distribution of parameters for each task, they were able to sample a set of parameters (weights) that worked for both tasks. [EWC].</p>
</section>
<section id="ensemble-methods" class="level2">
<h2 class="anchored" data-anchor-id="ensemble-methods">Ensemble methods</h2>
<p>Progressive Neural Networks - Perfect memory PathNet - Deepmind</p>
<p>Ensemble methods attempt to train multiple networks and combine them to get the result, essentially training separate classifiers for each new task.</p>
<p>Progressive neural networks progressively extend its structure in proportion to new tasks. It starts with an initial neural net and to learn a new task; new lateral connections are formed in parallel to the initial one. This helps in few ways, first when a new task has to be learned the previous network weights are frozen thus eliminating catastrophic forgetting and as lateral connections between each layer are formed the new network shares knowledge from the previous network. The only disadvantage with a progressive network is with the growth of new tasks, the network weights also grow.</p>
<p>PathNet is a network of networks. It has a fixed set of networks in which each layer has a collection of parallel mini neural network modules. Optimal paths are discovered using a genetic algorithm or reinforcement learning from the fixed size neural network for each task. After training and identification of a path, they are frozen. Thus the network does not forget. The cool thing about PathNet is that the base network is fixed and it does not grow further than the initial architecture. It is possible for the learned representations to be reused as well. PathNet is considered the best model for this type of learning.</p>
</section>
<section id="memory-methods-rehearsal" class="level2">
<h2 class="anchored" data-anchor-id="memory-methods-rehearsal">Memory Methods – Rehearsal</h2>
<ul>
<li>Episodic Memory Approach</li>
<li>Episodic Generative Approach</li>
<li>Dual memory models</li>
<li>Gradient Episodic Memory</li>
</ul>
<p>These involve both static memory and generative memory methods. Static memory methods involve using a big experience replay type of memory to store previous session data, and during training of each new task, data from memory is randomly sampled and mixed with the new training data. The generative model can be a type of auto-encoder or a generative adversarial network (GAN), where the statistics of the data is stored and replayed while training for new tasks.</p>
<p>Dual memory models use a system of short-term memory (STM) modules and a long-term memory (LTM) module. Both of the memories have a combination of a generator and a learner. The STM which is a collection of task-specific networks, also, has a hash-table that keeps a tab on how many tasks the agent has learned and indexes each of the task-specific networks. The LTM uses a collection of the raw data sample from all the previous tasks to train its generative memory. The STM is used for fast training, and LTM is used to reinforce the STM.</p>
<p>In Gradient Episodic Memory, when learning in a new environment, weight update depends on a meeting a metric. Here for each task, a sample of the states (X-y) are stored in memory. For each update, the gradient is compared with the gradient of all the previous tasks, if the gradient of the current update does not contribute to the overall gradients of all the previous tasks, then an approximation that does contribute is chosen as the update. This reduces drastic changes to weights when learning new tasks, hence prevents catastrophic forgetting.</p>
<p>Now let me give some details on approaches specific to reinforcement learning.</p>
</section>
<section id="life-long-reinforcement-learning" class="level2">
<h2 class="anchored" data-anchor-id="life-long-reinforcement-learning">Life Long Reinforcement Learning</h2>
<p>A lifelong reinforcement learning agent should have 2 main abilities: Efficiently retain knowledge base of learned policy in an environment (highly regularized sparse data structure). Efficient transfer - Should have the ability to transfer knowledge from the previous environment to the new one.</p>
<p>In life-long reinforcement learning, instead of learning each task, the objective is for the agent to distill learning from different environments, use shared knowledge and learn environment specific information as well. In the following section task and environment mean the same thing.</p>
</section>
<section id="life-long-rl-through-multiple-environments" class="level2">
<h2 class="anchored" data-anchor-id="life-long-rl-through-multiple-environments">Life Long RL through multiple environments</h2>
<p>These learning methods are based on introducing bias into learning. Here, bias refers to knowledge about the environment. So a lifelong learning agent is initialized with something called the initial bias which is the weights of the previous environment and then updated with learning bias for the new environment. Now, this is in some ways similar to what our DQN agent is doing where we initialize the net with the weights trained from the initial simulator and then use this to bootstrap for the real environment. This can be extended, and initial bias could be the average of weights for all the previous environments. Also, adaptive learning rates are used for weights. The weights are updated in proportion to the amount by which they varied for the previous environments. If they did not vary by a threshold value, the learning rate for those weights are set to be very low, and if the weights beyond a threshold, then that means that these weights are environment dependent, thus the learning rate for these weights for the new environment is set to a higher one.</p>
<p>Most of the recent lifelong learning schemes used in RL is based on an algorithm known as ELLA (Efficient Lifelong Learning Algorithm). The principle behind ELLA is that we assume each task is sequentially submitted to the agent, and each learnable parameter is considered as a linear combination of a latent basis component (a component common to all tasks) and a task-specific component. Thus, the objective would be to minimize predictive loss over all tasks while encouraging significance of the latent shared component. This is done by introducing a sort of inductive bias (inductive of shared task information) to the loss function.</p>
</section>
<section id="policy-gradient---ella" class="level2">
<h2 class="anchored" data-anchor-id="policy-gradient---ella">Policy Gradient - ELLA</h2>
<p>The goal of policy gradient using efficient lifelong learning algorithm is to find optimum policies parameterized by a set of weights for each environment. We use the same approach as in general ELLA where the parameters (weights) for each task is considered to be a linear combination of parameters of the common latent model between the tasks and task-specific weights. Here the latent structure is stored in memory for future learning, and the PG algorithm in each of its iteration uses this knowledge base to update both latent weights and task-specific weights.</p>
</section>
<section id="hierarchical-deep-reinforcement-lifelong-learning-network-h-drln" class="level2">
<h2 class="anchored" data-anchor-id="hierarchical-deep-reinforcement-lifelong-learning-network-h-drln">Hierarchical Deep Reinforcement Lifelong Learning Network (H-DRLN)</h2>
<p>To solve complex tasks, rather than just knowing what action to take in a state, an agent has to learn skills; these would include things like picking up an object, moving from a point to another point, etc. Reinforcement learning was extended using the options framework to do exactly this. [options framework]. To use reusable skills in a lifelong manner, an algorithm should be able to learn a skill (Eg: how to move left or right); enable an agent to determine which of these skills should be used/reused and cache reusable skills.</p>
<p>H-DRLN has something called a Deep Skill Network which stores independent DQNs that have special skills stored, for example, there could be 2 DQNs as in our case one for passive control and another for active control. Along with the Deep Skill Network, the agent has a generic output layer that outputs either simple actions or skills from the Deep Skill Network depending upon the state sampled. This agent can be considered as a DQN with actions being temporally extended to solve tasks. For training the agent, a modification is made to the experience reply, and a new memory called Skill Experience Reply (S-ER) is used.</p>
<p>With this, we come to the end of the survey on Catastrophic Forgetting and lifelong learning approaches. A few other methods like explicit sparse coding, policy distillation, and curriculum learning have not been mentioned here as many of the techniques discussed could be considered as variations of these algorithms.</p>
</section>
<section id="terms" class="level2">
<h2 class="anchored" data-anchor-id="terms">Terms</h2>
<p>Plasticity - The propensity of a weight to be affected by a change. A weight with high plasticity can be modified easily than a weight with lower plasticity. Auto-encoder - A type of neural networks used to learn representation of data, mainly for dimensionality reduction GAN - GAN or Generative Adversarial Networks uses a competing pair of networks to learn the representation of data and can be used to generate data points from the learned distribution.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p>[Dropout] : https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf [Empirical study] : https://arxiv.org/pdf/1312.6211.pdf [Fast weights]: https://www.cs.bham.ac.uk/~jxb/PUBS/COGSCI05.pdf [EWC]: https://arxiv.org/pdf/1612.00796.pdf [Lifelong ML]: https://www.cs.uic.edu/~liub/lifelong-machine-learning-draft.pdf [Options framework]: http://www-anw.cs.umass.edu/~barto/courses/cs687/Sutton-Precup-Singh-AIJ99.pdf [Multi task learning PG]: http://proceedings.mlr.press/v32/ammar14.pdf [Gradient Episodic Memory]: https://arxiv.org/pdf/1706.08840.pdf [PathNet]: https://arxiv.org/pdf/1701.08734.pdf [Deep Generative Memory]: https://arxiv.org/pdf/1710.10368.pdf [Progressive Neural Net]: 1606.04671 Progressive Neural Networks</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>Thats all for now folks on Catastrophic Forgetting in Learning systems using connectionist methods.</p>
<figure align="center" class="figure">
<img src="https://www.oldbookillustrations.com/wp-content/uploads/2020/02/de-groof-falling.jpg" alt="Fall of the Flying Man, London." height="300" width="400" class="figure-img">
<figcaption>
Fall of the Flying Man, London.
</figcaption>
</figure>


</section>

 ]]></description>
  <category>ml</category>
  <guid>https://blog.rahul.onl/posts/2020-07-15-ml-forget.html</guid>
  <pubDate>Wed, 15 Jul 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-07-14-learning-methods.html</link>
  <description><![CDATA[ 






<p>Model free learning can be done using variations of temporal difference learning or Monte Carlo methods.</p>
<section id="temporal-difference-or-td-learning" class="level2">
<h2 class="anchored" data-anchor-id="temporal-difference-or-td-learning">Temporal Difference or TD Learning</h2>
<p>From each step learn something that would make enable us to improve the estimated value for the next step. Consider this, three scenarios, in which the third scenario depends on the second and or the first. If that is the case, then knowing the states in the scenario can help us in better predicting the states in scenario three. We can improve the prediction in the third scenario if there is any change in states for either of the other scenarios, rather than waiting for the third one to finish and then realizing our prediction was close or way off. Consider, you are going somewhere and you expect to go through 2 cities. You estimate that you would reach the destination in 3 hours, as you know or estimate that you will need 1 hour each to cover the 2 other cities. Now, if it’s your lucky day and traffic is low in the first city, thus you could pass through it in 30 minutes instead of 60. Thus, you can estimate that you will reach the final destination 30 minutes early. While passing through the second city, you have car trouble and it takes an hour to fix it and start again. Thus, you now predict you would reach 30 minutes past the estimated time at your destination (Provided, you don’t face any further uncertainties). This continuous improvement of estimate is the main principle behind temporal difference or TD learning. We can say, TD learning is an on-line learning (as we don’t need to wait for the entire episode to finish before updating our estimates). It bootstraps on the estimated value of other states to estimate value of the state in concern.</p>
<p><strong>Types</strong> : TD(0) and TD(lambda)</p>
</section>
<section id="q-learning" class="level2">
<h2 class="anchored" data-anchor-id="q-learning">Q learning</h2>
<p>It is a variation of TD(0) learning, where we incrementally estimate the Q value for a state based on immediate rewards and the Q value for the next state. The variation is that, to estimate the Q value for the next state, we add the immediate reward with the Q value for the next state that maximizes the value (Q value for the state for the action that gives the maximum value). Also, unlike TD(0) learning, Q learning is an off-policy learning algorithm. Thus the estimated Q value at instance k is, the Q value at k for the state and action at time t plus the difference between estimated Q value using the immediate reward and discounted Q value for the next state for the action that gives the maximum value and the Q value of the current state. This delta between estimated Q value for the next state and Q value for the current state is weighted by a factor called the learning rate, which is between [0, 1]. The weighting factor or learning rate alpha can be decreased based on each iteration or as in many scenarios, use a small fixed value. The rate basically determines by how much we update the Q value. Now, if that sounds complex, trust me, it’s not, I am just not that good at explaining I guess. Just search for the algorithm on line and you will get it instantly.</p>
<p>How is it done?</p>
<p>Well, basically, the agent at time, t, in state, s, does an action, a, and moves to the next state and thus receives a reward, r. Now at time, t+1, the agent knows that it is in state, s, and knows the reward it obtained from the previous state. It uses this information along with the Q value for the optimum action for this state to get a better estimate of the Q value of the state, s. For this update to work, we need to have some starting point of Q values, in practice this is assumed to be zero or set randomly and at each iteration, k, the Q value is updated a little bit based on the learning rate to be a little closer to reality. In time, after many iterations of learning, the Q values for each states will reflect the real values that can be obtained. It has been proved (don’t ask me how, I haven’t checked out the proof) that if we do this iterative update an infinite time, we will eventually get the right Q values, irrespective on the initial Q values, the actions we took in each state etc.</p>
</section>
<section id="sarsa-learning" class="level2">
<h2 class="anchored" data-anchor-id="sarsa-learning">SARSA learning</h2>
<p>First of all, what a creative naming, it must have taken them a long time to come up with this name. So, why is it called SARSA?, It’s because, the learning algorithm uses the present state, S, the action taken, A, the reward obtained, R, the next state, S<code>, and the action taken, A</code>, in this next state, while following a policy. SARSA stands for State-Action-Reward-State-Action!. While in traditional Q value function, the objective was to estimate the optimum policy doing exploration of a random policy, in SARSA, we start with a policy and tries to estimate the Q value of starting at a state, doing an action in state and following a policy, that is not changed in the course of learning. Thus it is an on-policy learning algorithm, as we don’t change the policy that has been chosen for a particular iteration. The idea is that if we are able to try all the states and all the possible actions infinitely many times, then this will eventually converge to the optimum policy itself. For a particular iteration, it computationally less demanding that Q learning, but overall, it may need more time to converge. This learning is used when the state transition probabilities might not be fixed, there can be changes in the probabilities of switching from one state to the other. The only change in the algorithm compared to Q learning is, it doesn’t take the action that maximizes the utility when calculating the <code>next state</code> value, but obeys by the policy and takes the stipulated action. Here, too if you don’t understand it, please check the algorithm once on line and it will be clear.</p>
</section>
<section id="actor-critic-algorithms" class="level2">
<h2 class="anchored" data-anchor-id="actor-critic-algorithms">Actor Critic Algorithms</h2>
<p>This class of learning algorithms has two parts, the Actor, which is a policy function and the Critic, which is a value function that is used to obtain the value for a state transition following an action. After an action has been selected, the Critic estimates the value for the state and calculates value for the state (immediate reward plus value for the next state). This is used to evaluate the action taken, which is the difference between the calculated value (using Bellman equation) and the estimated value. This difference or delta is used to improve the probability for the action in that state. The improvement factor delta is weighted by a learning rate, beta. A variation of this algorithm called the A3C algorithm is one of the fastest RL algorithms out there.</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>Awesome, thus in a two step process, we are able to identify <code>an optimum</code> policy based on nothing but a Q value table for each state action pairs. Kind of cool right!</p>
<figure align="center" class="figure">
<img src="https://www.oldbookillustrations.com/wp-content/uploads/2020/02/de-groof-falling.jpg" alt="Fall of the Flying Man, London." height="300" width="400" class="figure-img">
<figcaption>
Fall of the Flying Man, London.
</figcaption>
</figure>


</section>

 ]]></description>
  <category>prose</category>
  <category>ml</category>
  <guid>https://blog.rahul.onl/posts/2020-07-14-learning-methods.html</guid>
  <pubDate>Tue, 14 Jul 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-07-09-learning-methods.html</link>
  <description><![CDATA[ 






<p>Model free learning can be done using variations of temporal difference learning or Monte Carlo methods.</p>
<section id="temporal-difference-or-td-learning" class="level2">
<h2 class="anchored" data-anchor-id="temporal-difference-or-td-learning">Temporal Difference or TD Learning</h2>
<p>From each step learn something that would enable us to improve the estimated value for the next step. Consider this, three scenarios, in which the third scenario depends on the second and or the first. If that is the case, then knowing the states in the scenario can help us in better predicting the states in scenario three. We can improve the prediction in the third scenario if there is any change in states for either of the other scenarios, rather than waiting for the third one to finish and then realizing our prediction was close or way off.</p>
<p>Consider, you are going somewhere and you expect to go through 2 cities. You estimate that you would reach the destination in 3 hours, as you know or estimate that you will need 1 hour each to cover the 2 other cities. Now, if it’s your lucky day and traffic is low in the first city, you could pass through it in 30 minutes instead of 60. Thus, you can estimate that you will reach the final destination 30 minutes early. While passing through the second city, you have car trouble and it takes an hour to fix it and start again. Thus, you now predict you would reach 30 minutes past the estimated time at your destination (Provided, you don’t face any further uncertainties). This continuous improvement of estimate is the main principle behind temporal difference or TD learning.</p>
<p>We can say, TD learning is an on-line learning (as we don’t need to wait for the entire episode to finish before updating our estimates). It bootstraps on the estimated value of other states to estimate value of the state in concern.</p>
<p><strong>Types</strong> : TD(0) and TD(lambda)</p>
</section>
<section id="q-learning" class="level2">
<h2 class="anchored" data-anchor-id="q-learning">Q learning</h2>
<p>It is a variation of TD(0) learning, where we incrementally estimate the Q value for a state based on immediate rewards and the Q value for the next state. The variation is that, to estimate the Q value for the next state, we add the immediate reward with the Q value for the next state that maximizes the value (Q value for the state for the action that gives the maximum value). Also, unlike TD(0) learning, Q learning is an off-policy learning algorithm. Thus the estimated Q value at instance k is, the Q value at k for the state and action at time t plus the difference between estimated Q value using the immediate reward and discounted Q value for the next state for the action that gives the maximum value and the Q value of the current state. This delta between estimated Q value for the next state and Q value for the current state is weighted by a factor called the learning rate, which is between [0, 1]. The weighting factor or learning rate alpha can be decreased based on each iteration or as in many scenarios, use a small fixed value. The rate basically determines by how much we update the Q value. Now, if that sounds complex, trust me, it’s not, I am just not that good at explaining I guess. Just search for the algorithm online and you will get it instantly.</p>
<p>How is it done?</p>
<p>Well, basically, the agent at time, t, in state, s, does an action, a, and moves to the next state and thus receives a reward, r. Now at time, t+1, the agent knows that it is in state, s, and knows the reward it obtained from the previous state. It uses this information along with the Q value for the optimum action for this state to get a better estimate of the Q value of the state, s. For this update to work, we need to have some starting point of Q values, in practice this is assumed to be zero or set randomly and at each iteration, k, the Q value is updated a little bit based on the learning rate to be a little closer to reality. In time, after many iterations of learning, the Q values for each states will reflect the real values that can be obtained. It has been proved (don’t ask me how, I haven’t checked out the proof) that if we do this iterative update an infinite time, we will eventually get the right Q values, irrespective on the initial Q values, the actions we took in each state etc.</p>
</section>
<section id="sarsa-learning" class="level2">
<h2 class="anchored" data-anchor-id="sarsa-learning">SARSA learning</h2>
<p>First of all, what a creative naming, it must have taken them a long time to come up with this name. So, why is it called SARSA?, It’s because, the learning algorithm uses the present state, S, the action taken, A, the reward obtained, R, the next state, S<code>, and the action taken, A</code>, in this next state, while following a policy. SARSA stands for State-Action-Reward-State-Action!. While in traditional Q value function, the objective was to estimate the optimum policy doing exploration of a random policy, in SARSA, we start with a policy and tries to estimate the Q value of starting at a state, doing an action in state and following a policy, that is not changed in the course of learning. Thus it is an on-policy learning algorithm, as we don’t change the policy that has been chosen for a particular iteration. The idea is that if we are able to try all the states and all the possible actions infinitely many times, then this will eventually converge to the optimum policy itself. For a particular iteration, it is computationally less demanding that Q learning, but overall, it may need more time to converge. This learning is used when the state transition probabilities might not be fixed, there can be changes in the probabilities of switching from one state to the other. The only change in the algorithm compared to Q learning is, it doesn’t take the action that maximizes the utility when calculating the <code>next state</code> value, but obeys by the policy and takes the stipulated action. Here, too if you don’t understand it, please check the algorithm once on line and it will be clear.</p>
</section>
<section id="actor-critic-algorithms" class="level2">
<h2 class="anchored" data-anchor-id="actor-critic-algorithms">Actor Critic Algorithms</h2>
<p>This class of learning algorithms has two parts, the Actor, which is a policy function and the Critic, which is a value function that is used to obtain the value for a state transition following an action. After an action has been selected, the Critic estimates the value for the state and calculates value for the state (immediate reward plus value for the next state). This is used to evaluate the action taken, which is the difference between the calculated value (using Bellman equation) and the estimated value. This difference or delta is used to improve the probability for the action in that state. The improvement factor delta is weighted by a learning rate, beta. A variation of this algorithm called the A3C algorithm is one of the fastest RL algorithms out there.</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>Awesome, thus in a two step process, we are able to identify <code>an optimum</code> policy based on nothing but a Q value table for each state action pairs. Kind of cool right!</p>
<figure align="center" class="figure">
<img src="https://www.oldbookillustrations.com/wp-content/high-res/n-d-after-1915/fun-study-768.jpg" alt="Fun and study well combined." height="300" width="400" class="figure-img">
<figcaption>
Fun and study well combined.
</figcaption>
</figure>


</section>

 ]]></description>
  <category>prose</category>
  <category>ml</category>
  <guid>https://blog.rahul.onl/posts/2020-07-09-learning-methods.html</guid>
  <pubDate>Thu, 09 Jul 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-07-09-rl-intro.html</link>
  <description><![CDATA[ 






<section id="reinforcement-learning-rl" class="level2">
<h2 class="anchored" data-anchor-id="reinforcement-learning-rl">Reinforcement Learning (RL)</h2>
<section id="what-is-it" class="level3">
<h3 class="anchored" data-anchor-id="what-is-it">What is it?</h3>
<p>Learning by doing, where the quality of learning is determined by how much reward one can get at the end of an episode.</p>
</section>
</section>
<section id="some-terms-that-people-drop-when-talking-about-rl" class="level2">
<h2 class="anchored" data-anchor-id="some-terms-that-people-drop-when-talking-about-rl">Some terms that people drop when talking about RL</h2>
<section id="mdp-models-and-the-rest" class="level3">
<h3 class="anchored" data-anchor-id="mdp-models-and-the-rest">MDP, Models and the rest:</h3>
<section id="markov-decision-process-or-mdp" class="level4">
<h4 class="anchored" data-anchor-id="markov-decision-process-or-mdp">Markov Decision Process or MDP</h4>
<p>MDP - A function that is a tuple of (S, A, R, T) , where S - State, A - Action, R - Reward for that A in S, T - Transition probability to go to a next state when action A is taken in state S.</p>
</section>
<section id="policy-pis-x-a---0-1" class="level4">
<h4 class="anchored" data-anchor-id="policy-pis-x-a---0-1">Policy pi:S x A -&gt; [0, 1]</h4>
<p>That is, for every state there is a mapping from state to action which has a probability. Sum of all possible action probabilities in a state is 1.</p>
</section>
<section id="types" class="level4">
<h4 class="anchored" data-anchor-id="types">Types</h4>
<p><em>Model free</em> - We don’t know the transition probabilities or rewards before hand. <em>Model based</em> - Transition and rewards are know, thus just follow the path using value iteration to get the optimum policy.</p>
</section>
<section id="goal" class="level4">
<h4 class="anchored" data-anchor-id="goal">Goal</h4>
<p>To gather rewards.</p>
</section>
<section id="optimality" class="level4">
<h4 class="anchored" data-anchor-id="optimality">Optimality</h4>
<p>What is the goal?</p>
<p>Simple, maximize the reward.</p>
<p>Three models of optimality (criteria).</p>
<ul>
<li>Finite horizon - Expectation of reward from time = 0 to horizon.</li>
<li>Discounted, infinite horizon - Expectation of discounted rewards from time = 0 to infinity.</li>
<li>Average reward - Expectation of rewards from time t to horizon when limit of horizon tends to infinity.</li>
</ul>
<blockquote class="blockquote">
<p>Note: Expectation is the average of results when some operation/task is repeated many times, while average is the average of something that is done once.</p>
</blockquote>
</section>
<section id="how-the-goal-is-achieved" class="level4">
<h4 class="anchored" data-anchor-id="how-the-goal-is-achieved">How the goal is achieved?</h4>
<p>This depends on what the optimality condition is, is it convergence, speed of convergence etc.</p>
</section>
<section id="value-functions" class="level4">
<h4 class="anchored" data-anchor-id="value-functions">Value functions</h4>
<p>Links optimal criteria to policies.</p>
</section>
<section id="two-types-of-functions" class="level4">
<h4 class="anchored" data-anchor-id="two-types-of-functions">Two types of functions</h4>
<p><strong>State value function</strong> : The value of a state <code>s</code> under policy <code>pi</code>.</p>
<p>This function helps us to know that is the value of being in a state <code>s</code> and then from there following the policy <code>pi</code>.</p>
<p><strong>State, Action function</strong> : The value of state <code>s</code> in which we take the action <code>a</code>.</p>
<p>This is similar to the state value function, and this one is called the Q value function, it the value of a state <code>s</code> in which we take a specific action <code>a</code> and then afterwards follow a policy <code>pi</code>. The cool thing about these functions are recursive in nature, that is, the solution or value of a state <code>s</code> can be known if we know that is the solution or value of the state <code>s+1</code> is. This is called the Bellman Equation. Bellman Equation - The Expected return value of a state can be defined in terms of immediate reward for that state and value of possible next states, weighted by their transition probabilities.</p>
</section>
<section id="achieving-the-best-policy." class="level4">
<h4 class="anchored" data-anchor-id="achieving-the-best-policy.">Achieving the best policy.</h4>
<section id="optimal-value-functions" class="level5">
<h5 class="anchored" data-anchor-id="optimal-value-functions">Optimal Value functions</h5>
<p>The value of taking the best or the optimal policy for a state is equal to the return we get by taking the best action for that state. Once we know the optimal value for a state, we can just greedily take the best action for the state and follow through the optimal value function, taking the best action in each state. This thus becomes our optimal policy. This is called the greedy policy, as we are inclined to take the best action available thus far to maximize the expected returns. This is all cool, only problem here is that we need to know the Transition probabilities of going from one state to another. This can be a problem in a model free environment, as we don’t have a clue what is the probability of going from one state to another before exhausting all possible transitions. Thus comes the optimal state, value functions to the rescue.</p>
</section>
<section id="optimal-state-value-functions" class="level5">
<h5 class="anchored" data-anchor-id="optimal-state-value-functions">Optimal (State, Value) functions</h5>
<p>These functions, known as Q functions, makes weighted summation over different alternatives. Let’s think about it, for finding the optimal value for an MDP, we need to know which action is the best and how often the best action is chosen. What if we don’t know that, instead we just weigh different actions taken from the state and assigns a number value to each state for all possible actions. If we have a table like this, we could take the actions for each state that gives us the best <code>value</code> for that state and move on to the next state, following this same process again. In the end, we would get the optimum value for the state from where we started. If we had kept a tab on the actions we took from the starting state, then we have the list of actions that enabled us to get the best possible value, which is the optimal action.</p>
<p>Relationships between the Q value, Value and Policy is a follows:</p>
<ul>
<li>Optimum Value is equal to Q values for each state when the action that gives maximum value for a state is taken.</li>
<li>Optimum policy is nothing but the action that resulted in getting the optimum values in the first place.</li>
</ul>
</section>
</section>
</section>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>Awesome, thus in a two step process, we are able to identify <code>an optimum</code> policy based on nothing but a Q value table for each state action pairs. Kind of cool right!</p>
<figure align="center" class="figure">
<img src="https://www.oldbookillustrations.com/wp-content/uploads/2020/02/de-groof-falling.jpg" alt="Fall of the Flying Man, London." height="300" width="400" class="figure-img">
<figcaption>
Fall of the Flying Man, London.
</figcaption>
</figure>


</section>

 ]]></description>
  <category>prose</category>
  <category>ml</category>
  <guid>https://blog.rahul.onl/posts/2020-07-09-rl-intro.html</guid>
  <pubDate>Thu, 09 Jul 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-05-23-ray.html</link>
  <description><![CDATA[ 






<p>The <a href="https://ray.io/">ray</a> library for distributed computing has been around for a while. It was a few years back when I first noticed it. This was when I had started doing some Deep Reinforcement Learning at work and needed to do distributed policy explorations. Since then, the library has expanded it’s role in many ways and is a true distributed framework to scale compute intensive workloads. Today I want to try and use it for a non machine learning workload and see how different it would be from using thee <code>multiprocessing</code> library that comes part of the Python standard library.</p>
<p>I was doing some webscraping and parsing and needed to parallelize some part of my code, specifically I wanted to run 2 functions parallely.</p>
<section id="python-multiprocessing" class="level1">
<h1>Python multiprocessing</h1>
<p>The usual approach I would choose to do this is using the <code>multiprocessing</code> library, although <code>threads</code> or <code>asyncio</code> can be used as well, as this were heavy IO based functions.</p>
<p>Consider these two functions as an example:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>():</span>
<span id="cb1-2">  a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb1-3">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000000</span>):</span>
<span id="cb1-4">    a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> i</span>
<span id="cb1-5">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> a</span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> product():</span>
<span id="cb1-8">  a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb1-9">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100000</span>):</span>
<span id="cb1-10">    a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> n</span>
<span id="cb1-11">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> a</span></code></pre></div></div>
<p>One way to multiprocess <code>sum()</code> and <code>product()</code> would be:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> multiprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Process</span>
<span id="cb2-2"></span>
<span id="cb2-3">p1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Process(target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>)</span>
<span id="cb2-4">p2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Process(target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>product) </span>
<span id="cb2-5">p1.start()</span>
<span id="cb2-6">p2.start()</span>
<span id="cb2-7">n_sum, n_prod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> p1.join(), p2.join()</span></code></pre></div></div>
<p>That was fairly simple wasn’t it? Although real world functions will have parameters and might have need to share memory etc.. I am avoiding all those here for simplicity.</p>
</section>
<section id="using-ray-to-do-the-same-thing" class="level1">
<h1>Using Ray to do the same thing</h1>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ray</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># initialize ray</span></span>
<span id="cb3-4">ray.init()</span>
<span id="cb3-5"></span>
<span id="cb3-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># decorate function that need to be parallized</span></span>
<span id="cb3-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@ray.remote</span>()</span>
<span id="cb3-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>():</span>
<span id="cb3-9">  a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb3-10">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000000</span>):</span>
<span id="cb3-11">    a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> i</span>
<span id="cb3-12">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> a</span>
<span id="cb3-13"></span>
<span id="cb3-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># decorate function that need to be parallized</span></span>
<span id="cb3-15"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@ray.remote</span>()</span>
<span id="cb3-16"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> product():</span>
<span id="cb3-17">  a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb3-18">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100000</span>):</span>
<span id="cb3-19">    a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> n</span>
<span id="cb3-20">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> a</span>
<span id="cb3-21"></span>
<span id="cb3-22"></span>
<span id="cb3-23">sum_id, prod_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sources.remote(), binaries.remote()</span>
<span id="cb3-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># block until finished</span></span>
<span id="cb3-25">n_sum, n_prod <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ray.get([sum_id, prod_id])</span></code></pre></div></div>
<p>That’s it, that was as simple as using the <code>multiprocessing</code> library. The interesting thing about <code>ray</code> is that the same code can be used to distribute the workload across a cluster as well without changing the code in any way- this I think is a game changer especially when I don’t have to deal with MPI configs or spark clusters to get that ability.</p>
<p>Running this code, I get a INFO message:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2020</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">23</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">848</span> INFO resource_spec.py:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">204</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span> Starting Ray <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">7.28</span> GiB memory available <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> workers <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> up to <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.66</span> GiB <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> objects. You can adjust these settings <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> ray.init(memory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&lt;</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bytes</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>, object_store_memory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&lt;</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bytes</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>).</span>
<span id="cb4-2"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2020</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">23</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">19</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">246</span> INFO services.py:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1168</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span> View the Ray dashboard at localhost:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8265</span></span></code></pre></div></div>
<p>The dashboard running on <code>localhost:8265</code> gives me a overview of resource consumption *(cpu, memory), amount of data seent and recieved etc, this is especially useful in a distributed cluster environment, very neat!</p>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>For distributed Machine Learning training I used Horovod exlusively, the one thing with Horovod is that it needs MPI and at times, it’s a pain to debug MPI, I would like to tryout Ray and see if it is easier to use in place of Horovod. My initial thoughts are all positive and it looks really great.</p>
<figure align="center" class="figure">
<img src="https://www.oldbookillustrations.com/wp-content/high-res/1880/dickinson-lorenz-machines-768.jpg" alt="Jup used to spend some of his time in the kitchen." height="300" width="400" class="figure-img">
<figcaption>
Dickinson-Lorenz Typesetting and Distributing Machines
</figcaption>
</figure>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <guid>https://blog.rahul.onl/posts/2020-05-23-ray.html</guid>
  <pubDate>Sat, 23 May 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-03-23-tiemy.html</link>
  <description><![CDATA[ 






<section id="timing-python-functions" class="level1">
<h1>Timing python functions</h1>
<p>I have been writing some performant code in Python (oxymoron?), and I wanted a simple decorator to time funtions essentially to measure running time.</p>
<p>There a plenty of modules in Python that can help with this, but most were complicated for me to understand what exactly they were doing and had way more functionaltiy than I required.</p>
<p>So I wrote a tiny package that can help with this. The package is named <code>tiemy</code> and is available in pypi, it only has one single decorator, <code>timer</code> and I would like to keep it to a minimum.</p>
<p>You just have to use the decorator <code>@timer</code> on any Python callable and tiemy runs the function for 3 times and displays the mean and standard deviation of the run time.</p>
<p>At the core tiemy uses <code>perf_counter</code> from <a href="https://docs.python.org/3/library/time.html#time.perf_counter">time module</a> to measure running time.</p>
<section id="installing-tiemy" class="level2">
<h2 class="anchored" data-anchor-id="installing-tiemy">Installing tiemy</h2>
<p>The module is fairly easy to install, you just need python and pip:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">pip install tiemy</span></code></pre></div></div>
<p>That’s it!</p>
</section>
<section id="how-to-use-tiemy" class="level2">
<h2 class="anchored" data-anchor-id="how-to-use-tiemy">How to use tiemy</h2>
<p>Consider a prime number sieve as below is saved in a file <code>prime.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> tiemy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> timer</span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@timer</span></span>
<span id="cb2-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> sundaram(N):</span>
<span id="cb2-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""sundaram's sieve to find non primes."""</span></span>
<span id="cb2-6">    primes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, N, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb2-7">    half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> N <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-8">    init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span></span>
<span id="cb2-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> step <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, N, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>):</span>
<span id="cb2-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(init, half, step):</span>
<span id="cb2-11">            primes[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb2-12">        init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (step <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> half:</span>
<span id="cb2-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, numbers))</span>
<span id="cb2-15"></span>
<span id="cb2-16"></span>
<span id="cb2-17"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__name__</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"__main__"</span>:</span>
<span id="cb2-18">    sundaram(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100000</span>)</span></code></pre></div></div>
<p>The output would be something like:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">python prime.py</span>
<span id="cb3-2">timing func:: sundaram</span>
<span id="cb3-3">mean:     <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0090</span>, std:     <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0003</span> sec.</span></code></pre></div></div>
<p>The above method to find prime numbers is called sundaram sieve <sup>1</sup>, we will look at it more in detail in a later post :).</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<a href="https://pypi.org/project/tiemy/">Tiemy</a>, pronunced as <code>tie-mee</code>, is a simple timing decorator that just does one thing, measure running time.
<figure align="center" class="figure">
<img src="https://www.oldbookillustrations.com/wp-content/high-res/n-d/jup-kitchen-768.jpg" alt="Jup used to spend some of his time in the kitchen." height="266" width="200" class="figure-img">
<figcaption>
Jup used to spend time
</figcaption>
</figure>


</section>
</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p><a href="https://en.wikipedia.org/wiki/Sieve_of_Sundaram">sieve of sundaram</a>↩︎</p></li>
</ol>
</section></div> ]]></description>
  <category>coding</category>
  <guid>https://blog.rahul.onl/posts/2020-03-23-tiemy.html</guid>
  <pubDate>Mon, 23 Mar 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-03-22-pyjuggle.html</link>
  <description><![CDATA[ 






<section id="python-concurrency-lessons" class="level1">
<h1>Python concurrency lessons</h1>
<p>Now that everyone is talking about and using <code>async/await</code> and event loops everywhere, I thought I would go to the basics (well not to the fundamentals, but practical basics) and write a small program to download a bunch of text files and process them.</p>
<section id="the-program" class="level2">
<h2 class="anchored" data-anchor-id="the-program">The program</h2>
<p>Fetch <code>n</code> ebooks from project gutenberg site and do some elemental processing on the content.</p>
<p>Some of the code snippets:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"></span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> download(url: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb1-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""download and decode content from a url."""</span></span>
<span id="cb1-4">    page <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> requests.get(url)</span>
<span id="cb1-5">    name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> url.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/"</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> page.content.decode(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"utf-8"</span>), <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"texts/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> save(content: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, fname: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb1-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""save content to file with name."""</span></span>
<span id="cb1-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(fname, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"w"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> fh:</span>
<span id="cb1-11">        fh.write(content)</span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process(string: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>:</span>
<span id="cb1-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""cpu bound tasks"""</span></span>
<span id="cb1-15">    ...</span>
<span id="cb1-16">    ...</span>
<span id="cb1-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> string</span>
<span id="cb1-18"></span>
<span id="cb1-19"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb1-20">    urls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb1-21">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://www.gutenberg.org/cache/epub/376/pg376.txt"</span>,</span>
<span id="cb1-22">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://www.gutenberg.org/files/84/84-0.txt"</span>,</span>
<span id="cb1-23">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://www.gutenberg.org/cache/epub/844/pg844.txt"</span>,</span>
<span id="cb1-24">    ]</span>
<span id="cb1-25"></span>
<span id="cb1-26">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># call download</span></span>
<span id="cb1-27"></span>
<span id="cb1-28">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># call save</span></span>
<span id="cb1-29"></span>
<span id="cb1-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#call string process</span></span></code></pre></div></div>
<p>The full source code is on github at <a href="https://github.com/rahulunair/pyjuggle">pyjuggle</a>.</p>
</section>
<section id="python-and-concurrency" class="level2">
<h2 class="anchored" data-anchor-id="python-and-concurrency">Python and concurrency</h2>
<p>Let’s get this straight, concurrency and parallelism are not the same. Concurrency means, running multiple programs as though they are running at the same time, where as parallelism is running the programs truly in parallel in multiple cores of your machine.</p>
<p>The interesting aspect of Python (Ruby and few others) is that there is something called the global interpreter lock or GIL. This is part of the cpython implementation, where only one Python object can have access to the interpreter at one time. This means that, we cannot run two threads of execution parallely in Python but that all threads of execution are time sliced. You can read more on GIL <a href="https://wiki.python.org/moin/GlobalInterpreterLock">here</a>.</p>
<p>Threads come handy though when there is a lot of IO involved or when there are subprocess calls, where the interpreter is handing-off to work to another subsystem, and a new thread of execution can start, while the previous thread waits for a response.</p>
<p>When we need to real multi-core parallel tasks in Python, mulitprocessing library comes to our favour. It essentially spins up multiple Python interpreters and works on orthogal exlusive chunks of data, this method is good for CPU bound tasks.</p>
</section>
<section id="when-to-use-what" class="level2">
<h2 class="anchored" data-anchor-id="when-to-use-what">When to use what?</h2>
<p>Although, there are exceptions, I would say when IO or subprocess calls are involved or when the interpreter is giving of control to another sub-system use threads.</p>
<p>The module of choice for me for concurrency in python is <code>concurrent.futures</code>.</p>
<p>To use a thread pool, we can do this:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> concurrent.futures <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ThreadPoolExecutor <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tpe</span>
<span id="cb2-2"></span>
<span id="cb2-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># call download method concurrently</span></span>
<span id="cb2-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> tpe(max_workers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> exe:</span>
<span id="cb2-5">        results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> exe.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(download, urls)</span></code></pre></div></div>
<p>Here, maximum of 4 threads will be spun up, each time sliced, and will start downloading the <code>urls</code>. One thing to note here is that, depending upon the amount of data, here the <code>urls</code> threaded code may not show significant performance improvement when compared to one without threading, so it is always good to time sequential and threaded code before you decide.</p>
<p>{% include info.html text=“use threads when the task is IO bound” %}</p>
<p>The same approach can be used to save the files, create a threadpool and save the downloaded content:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> concurrent.futures <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ThreadPoolExecutor <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tpe</span>
<span id="cb3-2">    ...</span>
<span id="cb3-3">    ...</span>
<span id="cb3-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># call save method concurrently</span></span>
<span id="cb3-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> tpe(max_workers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> exe:</span>
<span id="cb3-6">        exe.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(save, results)</span>
<span id="cb3-7">    ...</span>
<span id="cb3-8">    ...</span></code></pre></div></div>
<p>Finally we come across, a CPU bound task, which has to tokenize the saved files, here if we use threading, although there could be some speedup than serial execution, it is advicable to use multiprocessing, in some cases, threading could actually slow down the program if the program is mostly CPU bound.</p>
<p>An example of using a multiprocess executor is:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> concurrent.futures <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ProcessPoolExecutor <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> ppe</span>
<span id="cb4-2"></span>
<span id="cb4-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># call process method parallely</span></span>
<span id="cb4-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> ppe(max_workers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> exe:</span>
<span id="cb4-5">        exe.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(process, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"./all.txt"</span>).readlines())</span></code></pre></div></div>
<p>{% include info.html text=“use processes when the task is CPU bound” %}</p>
<p>Here we are mapping 4 <code>process</code> methods with chunks of data from the file, one thing to note here is that the amount of work distributed to the 4 processes is not controlled by the programmer and may not be equal.</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>This was an interesting experience, I wanted to write about this for few years now, finally got to it. I am pretty sure I have got some things wrong, if you find any such techincal inacurracies ping me on twitter or on github.</p>
<p>May be next time I will write, when to use <code>async-await</code>.</p>
<p align="center">
<img src="https://rahul.onl/images/juggle.png" alt="python_juggle" width="200" height="300">
</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <guid>https://blog.rahul.onl/posts/2020-03-22-pyjuggle.html</guid>
  <pubDate>Sun, 22 Mar 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-03-16-vars.html</link>
  <description><![CDATA[ 






<section id="flashcard-rust-variables" class="level1">
<h1>Flashcard Rust: Variables</h1>
<p>In this post, let’s look at how variables are considered in Rust.</p>
<section id="immutable-by-default" class="level2">
<h2 class="anchored" data-anchor-id="immutable-by-default">Immutable by default</h2>
<p>By default all variables in Rust are <code>immutable</code>, what that means is, once we assign a value to a variable, we cannot reassign another value. The keyword <code>let</code> is used to create variables and bind values to them in Rust.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-2">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unrahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-3">  <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Output of the above program is:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> unrahul</span></code></pre></div></div>
<p>There you go, what we have done is; we have created a string literal <code>name</code> in Rust of type <code>&amp;str</code>. Now, if we try to reassign the same variable <code>name</code> in the same scope as <code>main</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unrahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// created a variable `name` and assigned a value to it</span></span>
<span id="cb3-3">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-4">    name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// trying to assign a new value to the variable `name`  </span></span>
<span id="cb3-5">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"new name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>The compiler will throw an error:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">error[E0384]: cannot assign twice to immutable variable `name`</span>
<span id="cb4-2"> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--&gt;</span> src<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>main.rs:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb4-3">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb4-4"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>     let name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unrahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-5">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>         <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">----</span></span>
<span id="cb4-6">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>         <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb4-7">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>         first assignment to `name`</span>
<span id="cb4-8">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>         <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">help</span>: make this binding mutable: `mut name`</span>
<span id="cb4-9"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>     println<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name is </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-10"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>     name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-11">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>     <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^^^^^^^^^^^^^^</span> cannot assign twice to immutable variable</span>
<span id="cb4-12"></span>
<span id="cb4-13">error: aborting due to previous error</span>
<span id="cb4-14">For more information about this error, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span> `rustc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>explain E0384`.</span>
<span id="cb4-15">error: could <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">compile</span> `playground`.</span></code></pre></div></div>
<p>{% include info.html text=“try rustc –explain E0384 to see what the error is all about” %}</p>
<p>This is freakin’ cool, now that variables cannot be reassigned, in a program, we do not have to worry if the types are going to change or if the state of a variable will change unintentionally.</p>
</section>
<section id="can-a-variable-ever-be-a-mutable" class="level2">
<h2 class="anchored" data-anchor-id="can-a-variable-ever-be-a-mutable">Can a variable ever be a mutable?</h2>
<p>In some situtations, we want variables to be reassigned like in a loop, or ehmm if we want to change our name to a new one.., for those situations, in Rust we can do:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb5-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unrahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// just change the varible to a `mutable` variable</span></span>
<span id="cb5-3">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-4">    name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-5">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"new name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>An the output is:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> unrahul</span>
<span id="cb6-2">new name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> rahul</span></code></pre></div></div>
</section>
<section id="shadowing" class="level2">
<h2 class="anchored" data-anchor-id="shadowing">Shadowing</h2>
<p>Shadowing in simple terms mean, a variable already declared can be redeclared with in a inner block with the same name.</p>
<p>For example, we can do this in Rust:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unrahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-3">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-4">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-5">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// here the variable is in inner scope (see the braces?), and this is shadowing the external declartion of `name`</span></span>
<span id="cb7-6">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"new name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-7">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb7-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Compiling and running this, we get:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> unrahul</span>
<span id="cb8-2">new name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> rahul</span></code></pre></div></div>
<p>Okay, I lied a bit, <strong>shadows</strong> need not be in inner or seperate block, this below is perfectly valid:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb9-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unrahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-3">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rahul"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// This is also considered as shadowing</span></span>
<span id="cb9-5">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"new name is {}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>And the output of this is:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> unrahul</span>
<span id="cb10-2">new name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> rahul</span></code></pre></div></div>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>Now that we have seen <code>immutable</code> and <code>mutable</code> variables, and also <code>shadowing</code>, may be primitive types next?..</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <category>rust</category>
  <guid>https://blog.rahul.onl/posts/2020-03-16-vars.html</guid>
  <pubDate>Mon, 16 Mar 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-03-09-cargo.html</link>
  <description><![CDATA[ 






<section id="flashcard-rust-cargo" class="level1">
<h1>Flashcard Rust: Cargo</h1>
<p>Cargo is the one ring to rule them all, the one build tool that:</p>
<ul>
<li>builds our rust project</li>
<li>downloads dependencies</li>
<li>build dependencies</li>
<li>help release optimized code</li>
</ul>
<p>Let’s see how cargo helps us in packaging and releasing our code, get it? cargo.. packaging… ah ohkay, not the right time for terrible jokes I guess..</p>
<section id="using-cargo-to-create-rust-projects" class="level2">
<h2 class="anchored" data-anchor-id="using-cargo-to-create-rust-projects">Using cargo to create Rust projects</h2>
<p>Cargo should be installed as part of rust installation, to ensure cargo is installed run</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> cargo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>version</span>
<span id="cb1-2">cargo <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.41.0</span></span></code></pre></div></div>
<p>you should be able to see something like above… to create a wireframe for a new project <code>hworld</code> run:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> cargo new hworld</span></code></pre></div></div>
<p>This creates a directory <code>hworld</code>, with few files and one directory:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb3-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|--</span> Cargo.toml</span>
<span id="cb3-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|--</span> src</span>
<span id="cb3-4">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|--</span> main.rs</span></code></pre></div></div>
<p>Cargo goes one step ahead and adds versioning to the project, <code>git</code> is used by default, so if you do a <code>ls -la</code> you can see few more files, but for now let’s ignore that and focus on the main files.</p>
<ul>
<li>Cargo.toml - This is called the <strong>manifest</strong> file of our Rust project and is the file where we configure stuff like <code>name</code>, <code>version</code> of the project, Rust <code>edition</code>, the, <code>author's</code>, email address, and also there is a section to include the <code>dependencies</code> required by the project.</li>
</ul>
<p>A sample <code>Cargo.toml</code> looks like:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">package</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">]</span></span>
<span id="cb4-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name = "hworld"</span></span>
<span id="cb4-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">version = "0.1.0"</span></span>
<span id="cb4-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">authors = ["rahulunair &lt;rahulunair@gmail.com&gt;"]</span></span>
<span id="cb4-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">edition = "2018"</span></span>
<span id="cb4-6"></span>
<span id="cb4-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dependencies</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">]</span></span>
<span id="cb4-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">time = "0.1.12"</span></span></code></pre></div></div>
<p>There are a lot more options that can be included in the manifest file, for an extensive list, <a href="https://doc.rust-lang.org/cargo/reference/manifest.html">see</a>. Here I have specified one dependency <code>time</code> with version 0.1.12, we wont use it for anything now, but just for kicks eh?</p>
<ul>
<li>./src/main.rs - It is a placeholder to add our code, <code>cargo</code> has populated it with:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb5-2">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello, world!"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
</section>
<section id="building-the-project-with-cargo" class="level2">
<h2 class="anchored" data-anchor-id="building-the-project-with-cargo">Building the project with Cargo</h2>
<p>It’s just as simple as running the below command from inside <code>hworld</code> directory:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> cargo build</span></code></pre></div></div>
<p>If you are running it for the first time, you would see something like:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">Updating crates.io index</span>
<span id="cb7-2">  Downloaded time v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.42</span></span>
<span id="cb7-3">  Downloaded libc v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2.67</span></span>
<span id="cb7-4">   Compiling libc v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2.67</span></span>
<span id="cb7-5">   Compiling time v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.42</span></span>
<span id="cb7-6">   Compiling hworld v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.0</span> (hworld)</span>
<span id="cb7-7">    Finished dev [unoptimized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> debuginfo] target(s) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">49.31</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">s</span></span></code></pre></div></div>
<p>That’s it, we have built our first program using <code>cargo</code>.</p>
</section>
<section id="running-the-program" class="level2">
<h2 class="anchored" data-anchor-id="running-the-program">Running the program</h2>
<p>After <code>cargo</code> has built the project successfully, it creates a directory <code>./target/debug/</code> to save the binary, we can just cd to <code>./target/debug</code> and run:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> .<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>hworld</span>
<span id="cb8-2">Hello, world<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span></span></code></pre></div></div>
<p>Yay! we have run our first Rust program, that was created using Cargo.</p>
</section>
<section id="releasing-our-code" class="level2">
<h2 class="anchored" data-anchor-id="releasing-our-code">Releasing our code</h2>
<p>Release version ideally should be an optimized binary, to obtain such a binary, it is as simple as running:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> cargo build <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--</span>release</span></code></pre></div></div>
<p>Running the above command on my system from <code>hworld</code> directory, Cargo prints:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">   Compiling libc v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2.67</span></span>
<span id="cb10-2">   Compiling time v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.42</span></span>
<span id="cb10-3">   Compiling hworld v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.0</span> (hworld)</span>
<span id="cb10-4">    Finished release [optimized] target(s) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">8.42</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">s</span></span></code></pre></div></div>
<p>And, lo and behold there is an optimized binary <code>hworld</code> in <code>hworld/target/release/</code>, in later posts, we can see the difference between debug and release versions of binaries generated by Cargo.</p>
<p>The eligance of Cargo is that, everything is named as we would expect, no gotcha’s .. I really like that about Cargo.</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>As a closing note, let’s recap Cargo mainly does two things for us,</p>
<ul>
<li>builds our project using - cargo build or cargo build –release</li>
<li>builds and runs our project using - cargo run</li>
</ul>
<p>Now, there is a third and final command I use, to check for compilation issues fast, without really building the binary, which can be slow at times.</p>
<p>The command to check if everything is alright is:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> cargo check</span></code></pre></div></div>
<p>On my system it gives me this:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">    Checking libc v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2.67</span></span>
<span id="cb12-2">    Checking time v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.42</span></span>
<span id="cb12-3">    Checking hworld v0<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1.0</span> (hworld)</span>
<span id="cb12-4">    Finished dev [unoptimized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> debuginfo] target(s) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.61</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">s</span></span></code></pre></div></div>
<p>That’s it, so we saw what <code>cargo</code> can do, it is a tool that can be used when we are building a Rust project, but if it is a simple file, with no dependencies we can still use <code>rustc</code> as we saw earlier in <a href="https://rahul.onl/coding/rust/all/2020/03/07/ahoy-rust.html#ahoy">Flashcard Rust</a>.</p>
<p align="center">
<a href="https://imgur.com/EboHRWB.png"> <img src="https://imgur.com/EboHRWB.png"> </a>
</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <category>rust</category>
  <guid>https://blog.rahul.onl/posts/2020-03-09-cargo.html</guid>
  <pubDate>Mon, 09 Mar 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2020-03-07-ahoy-rust.html</link>
  <description><![CDATA[ 






<section id="flashcard-rust-first-steps" class="level1">
<h1>Flashcard Rust: First steps</h1>
<p>Rust is one of the coolest systems programming lanugage on the block, let’s dip our feet in it.</p>
<section id="setup" class="level2">
<h2 class="anchored" data-anchor-id="setup">Setup</h2>
<p>Hopefully, you are using Linux. To install Rust, use:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> curl https:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span>sh.rustup.rs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>sSf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> sh</span></code></pre></div></div>
<p>Rustup is a tool that is used to install Rust, the above script downloads and installs <code>rustup</code> first and then installs Rust.</p>
</section>
<section id="ahoy" class="level2">
<h2 class="anchored" data-anchor-id="ahoy">Ahoy!</h2>
<p>Let’s create a directory to keep our source files:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> mkdir <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~/</span>rust_sources</span>
<span id="cb2-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> cd <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~/</span>rust_sources</span></code></pre></div></div>
<p>Our first program, to say <code>ahoy!</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> mkdir ahoy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> cd ahoy</span>
<span id="cb3-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> touch main.rs</span></code></pre></div></div>
<p>Open <code>main.rs</code> and add the following line:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-2">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ahoy ahoy!"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>  </span>
<span id="cb4-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Save the file and run <code>rustc main.rs</code>, thats it! We have compiled our first rust program.</p>
<p>There should be a file named <code>main</code> in the same directory main.rs is in, execute it using:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">.<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>main</span>
<span id="cb5-2">ahoy ahoy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span></span></code></pre></div></div>
<p>Now that you have written 2 lines of rust, do <a href="https://doc.rust-lang.org/stable/book/ch01-02-hello-world.html">read</a></p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="https://imgur.com/LZ6VxZR.png"><img src="https://imgur.com/LZ6VxZR.png" class="img-fluid figure-img"></a></p>
<figcaption>https://imgur.com/LZ6VxZR.png</figcaption>
</figure>
</div>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <category>rust</category>
  <guid>https://blog.rahul.onl/posts/2020-03-07-ahoy-rust.html</guid>
  <pubDate>Sat, 07 Mar 2020 08:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2017-03-31-juggling.html</link>
  <description><![CDATA[ 






<section id="monkeys-juggling-and-some-golang" class="level1">
<h1>Monkeys, Juggling and some Golang</h1>
<p>Today let’s do some basic monkey work, rather lets do some juggling. I am always fascinated by people being able to juggle multiple balls. It’s something amazing, at least to me. They even have a World Juggling day, can you believe it?! So, why are we talking about monkeys, juggling and what not… Well, to me golang goroutines is sort of juggling. Where the juggler is able to do one thing at one time and, is able to keep track of multiple balls or whatever is being juggled. Well, you might have a different opinion and you are right, if the opinion is something like we can truely do tasks parallely if there are multiple CPUs, akin to two monkeys handling 2 seperate balls. hmm… yeah, so this might be the most over simplified and in some ways incorrect expalnation of concurrency and parallelism. For people who are curious to know the difference, there are awesome videos out there, particularly one comes to mind, the one Rob Pike gave. Check it out, you might like it.</p>
<p>I initially thought of writing about different ways in which we can do concurrent jobs in both golang and python. Well, now that I am thinking let me give an example of how to use go routines.</p>
<p>Go routines are basically light threads handled by the go scheduler to do concurrent jobs. There are primitives such as mutexes, synchonozation etc. to prevent conditions like data lock, unwanted write, multiple threads trying to read and write a resource at the sametime etc. more on that later.</p>
<section id="magical-number-e" class="level2">
<h2 class="anchored" data-anchor-id="magical-number-e">Magical number <strong>e</strong></h2>
<p>So let’s see how to find the value of e in three different ways. I think if you ask me what is your favorite number, I might say it is <strong>e</strong>, never ending, rather transcendental constant with value <strong>2.7182818…</strong> . Funny thing is that this number comes up in many places across the universe, it was made famous by Bernoulli when he came across it, while studying compound interest..go figure out..&gt;&gt;</p>
</section>
<section id="an-example-program-to-find-value-of-e" class="level2">
<h2 class="anchored" data-anchor-id="an-example-program-to-find-value-of-e">An example program to find value of e</h2>
<p>There are lot of ways to find e, we can use the Binomial expansion, Newton’s method, Brother’s method (formualated in 2004 I think) etc.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">package</span> main</span>
<span id="cb1-2"></span>
<span id="cb1-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">import</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span></span>
<span id="cb1-4">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fmt"</span></span>
<span id="cb1-5">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"math"</span></span>
<span id="cb1-6">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sync"</span></span>
<span id="cb1-7">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-8"></span>
<span id="cb1-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// dumbFact is a recursive function to print factorial</span></span>
<span id="cb1-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> dumbFact<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>num <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> num <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-12">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb1-13">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> num <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dumbFact<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>num<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-15">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-16"></span>
<span id="cb1-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Brother method to find e using approximation</span></span>
<span id="cb1-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// for n=0 to limit</span></span>
<span id="cb1-19">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//    (2n+2)/(2n+1)!</span></span>
<span id="cb1-20">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> Brother<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>limit <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> wg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sync<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>WaitGroup<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-21">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> n <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span></span>
<span id="cb1-22">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> e <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span></span>
<span id="cb1-23">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// `defer` keyword will run the expression after the</span></span>
<span id="cb1-24">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//function returns</span></span>
<span id="cb1-25">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">defer</span> wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Done<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">()</span></span>
<span id="cb1-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> limit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-27">            e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)/</span>dumbFact<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-28">            n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb1-29">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-30">        fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Printf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Brother's method for `e` yields: %20.15f</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> e<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-31">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-32"></span>
<span id="cb1-33">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Binomial method to find `e`</span></span>
<span id="cb1-34">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> Binomial<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>limit <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> wg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sync<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>WaitGroup<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">defer</span> wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Done<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">()</span></span>
<span id="cb1-36">        e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> math<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Pow<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">((</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>limit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">),</span> limit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-37">        fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Printf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Binomial solution to `e` is : %20.15f</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> e<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-38">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-39"></span>
<span id="cb1-40">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Newton method - approximation when n is big</span></span>
<span id="cb1-41">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> Newton<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>limit <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> wg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sync<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>WaitGroup<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-42">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">defer</span> wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Done<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">()</span></span>
<span id="cb1-43">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> n <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span></span>
<span id="cb1-44">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> e <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">float64</span></span>
<span id="cb1-45">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> limit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-46">            e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>dumbFact<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-47">            n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb1-48">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-49">        fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Printf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Newton's method gives the value as: %20.15f</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> e<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-50">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-51"></span>
<span id="cb1-52">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> main<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">()</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-53">        fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Println<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A simple go routine example"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-54">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// A waitgroup is just used to wait until the</span></span>
<span id="cb1-55">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//routine completes</span></span>
<span id="cb1-56">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> wg sync<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>WaitGroup</span>
<span id="cb1-57">        wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Add<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-58">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">go</span> Brother<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-59">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">go</span> Binomial<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-60">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">go</span> Newton<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-61">        wg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Wait<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">()</span></span>
<span id="cb1-62">        fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Println<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Done!"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-63">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>You can see the program in action <a href="https://play.golang.org/p/-jJA-RPNbS">here</a>.</p>
</section>
<section id="whats-happening-here" class="level2">
<h2 class="anchored" data-anchor-id="whats-happening-here">What’s happening here?</h2>
<p>The <strong>juggling</strong> happens in lines 58, 59 and 60 of the program. Where, the scheduler will concurrently work on the three routines, there is nothing complicated in the program, it uses the basic factorial function, uses something called the <code>WaitGroup</code> and runs three go routines.</p>
<p>So why am I using a <code>WaitGroup</code>, you ask. Well, <code>WaitGroup</code> is just to prevent go from falling through and terminating the programming before the routines are done. It tells go to <em>wait</em> till all the routines have finished running. We could waited for a simple input from the user at the end after line 61 and made the program explicitly wait, which would have given the routines time to run as well. I arbitrarily chose this WaitGroup option.</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>Essentially, go routines are simple at first, and that is important. As in any concurrent programming paradigms, there are complications and real world pains, but the entry level bar is low, which is in my opinion <strong>neat</strong>. This helps one learn the concepts of concurrency eventhough you might not use Go. Next time we shall see how to do something similar to this in python, or will we ?</p>
<p align="center">
<img src="https://i.imgur.com/1MvLPvn.jpg" alt="monkey_juggle">
</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <guid>https://blog.rahul.onl/posts/2017-03-31-juggling.html</guid>
  <pubDate>Fri, 31 Mar 2017 07:00:00 GMT</pubDate>
</item>
<item>
  <title></title>
  <dc:creator>unrahul </dc:creator>
  <link>https://blog.rahul.onl/posts/2017-03-28-borg.html</link>
  <description><![CDATA[ 






<section id="borg" class="level1">
<h1>Borg</h1>
<p>So I was reading up on some Python and found this interesting pattern by Alex Martelli. It’s call the Borg pattern, which I think is very cool and a bit philosphical.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Borg(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span>):</span>
<span id="cb1-2">    _shared_data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb1-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.__dict__ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._shared_data</span>
<span id="cb1-5"></span>
<span id="cb1-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Singleton(Borg):</span>
<span id="cb1-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, v):</span>
<span id="cb1-8">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>(Singleton, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>).<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb1-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v</span>
<span id="cb1-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__str__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value)</span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># lets create some instances</span></span>
<span id="cb1-14"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> one <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Singelton(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>)</span>
<span id="cb1-15"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(one)</span>
<span id="cb1-16"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'first'</span></span>
<span id="cb1-17"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> two <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Singelton(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"second"</span>)</span>
<span id="cb1-18"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(two)</span>
<span id="cb1-19"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'second'</span></span>
<span id="cb1-20"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(one)</span>
<span id="cb1-21"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'second'</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># wow! thats cool ryt?!</span></span></code></pre></div></div>
<section id="whats-going-on-here" class="level2">
<h2 class="anchored" data-anchor-id="whats-going-on-here">What’s going on here?</h2>
<p>All <strong>Singleton</strong> objects have the same share the same state - it is made possbile by the all powerful <code>__dict__</code> attribute. It is a dictionary that contains all attributes and its values. We first assign <code>__dict__</code> to refer to the dictionary refered to by _shared_data. This makes sure that every time an object for Singelton is created the <code>__dict__</code> attribute of the Borg object is referring to the same instance variable <code>_shared_data</code>. Thus, when inheriting the class, the child class’s <code>__dict__</code> is overwritten by parent class’s <code>__dict__</code>.</p>
</section>
<section id="the-end" class="level2">
<h2 class="anchored" data-anchor-id="the-end">The end</h2>
<p>As a closing note, about the philosphy of Borg, think about why we need a singleton? At least one of the reasons why we need one is to maintain a common state among different objects (some would say, that is the only reason). Borg does that for us, one state for all objects, for we are the Borg, we are all the same:)</p>
<p>The Borg pattern is so cool because it is so simple.</p>


</section>
</section>

 ]]></description>
  <category>coding</category>
  <guid>https://blog.rahul.onl/posts/2017-03-28-borg.html</guid>
  <pubDate>Tue, 28 Mar 2017 07:00:00 GMT</pubDate>
</item>
</channel>
</rss>
