[{"content":"I am starting to think LLMs are reliable enough that we can experiment with modeling DAG calls as just an LLM model making a decision on what the next step is. The next step just uses that decision. A DAG tool like Airflow becomes more for monitoring and less for making explicit decisions.\nI do think we still have to treat this step as a software component. Maybe evals replacing tests, typed inputs and typed outputs. But the conflict is to find the balance between over-constraining vs under-constraining.\n","permalink":"https://vikramsg.github.io/snacks/dag/","summary":"\u003cp\u003eI am starting to think LLMs are reliable enough that we can experiment with modeling DAG calls as just an LLM model making a decision on what the next step is.\nThe next step just uses that decision.\nA DAG tool like Airflow becomes more for monitoring and less for making explicit decisions.\u003c/p\u003e\n\u003cp\u003eI do think we still have to treat this step as a software component.\nMaybe evals replacing tests, typed inputs and typed outputs.\nBut the conflict is to find the balance between over-constraining vs under-constraining.\u003c/p\u003e","title":"A non-deterministic DAG"},{"content":"If I go through the halls of X, I would probably come back with a very confused opinion on the state of open source today. On the one hand there are examples like opencode with tons and tons of open PRs with seemingly no moderation mechanism. On the other hand there is ghostty which has introduced a Vouch system meaning only approved contributors can submit PRs. But overall the feeling I get is that maintainers on popular open source projects are overwhelmed with PRs. And the worst offenders among these PRs are usually purely agent-written code.\nI would assume that way more repositories are also being created, mostly via pure agent driven code. Github incidents is obvious evidence. So the obvious first conclusion that many people seem to have come to is Open source is dead. First because new contributions are being cut off from popular projects. And second because in a flood of new repos how would one find new projects?\nBut what is happening is different and I am going to divide my observations into 2 themes that I am thinking about.\nTaste First, taste. It\u0026rsquo;s a trending theme among on X. There are strong opinions being shared on what the most important characteristics required in engineers are right now. In fact, some claim it may be the only remaining characteristic required And I agree to an extent because I am seeing some projects coming up where the main distinguishing element is probably taste.\nSome examples of projects I have started to use are opencode and herdr. I am not sure how much taste was part of my choice for opencode but the look of opencode matching my neovim setup was certainly a nudging factor! As for herdr I am a long time user of tmux. And tmux is very much from the neovim school. Meaning, lots of config tinkering, plugins, subtle bugs etc. And like neovim I have always wished for something where I just got on with doing stuff rather than fixing it, hence my on and off relationship with Zed! So when I started using herdr it felt like someone had listened to my inner thoughts. Lots of very opinionated takes on how a multiplexer should work. For example, having an indicator in tabs showing if I am in a zoomed pane (I had to configure tmux to do this). Or just having a single config line to pick my theme (I had to install a plugin in tmux and to install a plugin in tmux I first need to install a plugin manager). So, basically taste. And I did not even talk about how good the agent integration is with herdr because that\u0026rsquo;s an evolving area overall. But the rest was something that tmux itself could have done. But chose not to.\nCraft Which brings me to my second theme. I am fairly certain that taste will increasingly determine how more projects will rise to the top of the pile of popular open source projects. Rehashing existing concepts won\u0026rsquo;t cut it since it\u0026rsquo;s so easy to copy using agents now. However the thing that will start to cause issues in sustaining popularity is how good the engineering in the project is. I am already starting to see projects starting to see a lot of pressure in sustaining features. opencode and pi, 2 very popular open source harnesses are going through a v1 to v2 transition. opencode V1 had started to become really painful for me to use and while v2 is certainly way better, I don\u0026rsquo;t yet know how good it is to sustain whatever new directions the project wants to go in.\nAnother popular open source project that I used to hear more about but much less so these days is cmux. Which is on 0.64.x since May and I believe is also trying to create a v2. And I have been seeing issues with herdr when it comes to seeing images using the kitty protocol. I don\u0026rsquo;t want to make it feel like I am throwing these projects under the bus because both cmux and herdr are really good. But I also feel like a lot of these projects will suffer from 2 things.\nNeeding to create unrelated primitives, meaning a lot of project time is spent not on core areas but on a necessary abstraction (or abstractions) that enables the product. How much the maintainers are going to lean on agents. openclaw is a big example of 1. It started off as a very, very popular project but it suffered from needing to create so many primitives. An example of a question it needed to answer was how an agent accesses email without doing destructive operations, which is important but not really a responsibility that openclaw should be handling. As for 2, I am not going to cite any examples since I am not privy to how maintainers are working with agents, but a lot of open source projects seem to be relying heavily on AI. My current belief is, the heavier agents are relied on, the more complicated the architecture becomes and the harder it will be to evolve in the future. And depending on the volume of code that agents create, that future could come in weeks, rather than years.\nIt\u0026rsquo;s still going to be exciting Having said all that I am still really excited about what is coming. After all 6 months ago, I had not used opencode. But right now it feels like most of my day is spent interacting with it. 2 weeks ago, I had not used herdr. Now it\u0026rsquo;s a core part of my daily workflow. So, I am rooting for more such projects succeeding. And hopefully there\u0026rsquo;s enough Taste and Craft in them to make sure they become sustainable projects.\nDisclaimer The entire post was hand-written (shocking!) by me (in NeoVim inside herdr). However I used GPT5.6 Sol to research all citations and put them in the slots I put in the post.\n","permalink":"https://vikramsg.github.io/open-source-in-the-age-of-ai/","summary":"\u003cp\u003eIf I go through the halls of X, I would probably come back with a very confused opinion on the state of open source today.\nOn the one hand there are examples like \u003ca href=\"https://github.com/anomalyco/opencode/pulls\"\u003e\u003ccode\u003eopencode\u003c/code\u003e\u003c/a\u003e with tons and tons of open PRs with seemingly no moderation mechanism.\nOn the other hand there is \u003ca href=\"https://github.com/ghostty-org/ghostty/blob/main/CONTRIBUTING.md\"\u003e\u003ccode\u003eghostty\u003c/code\u003e\u003c/a\u003e which has introduced a \u003ca href=\"https://github.com/ghostty-org/ghostty/pull/10559\"\u003e\u003ccode\u003eVouch\u003c/code\u003e\u003c/a\u003e system meaning only approved contributors can submit PRs.\nBut overall the feeling I get is that maintainers on popular open source projects are overwhelmed with PRs.\nAnd the worst offenders among these PRs are usually purely agent-written code.\u003c/p\u003e","title":"Open Source in the age of AI"},{"content":"I am not completely new to React. A couple of years ago I spent a few weeks struggling with frontend tools to create 49travel. I learnt a lot about tooling, especially Vercel, a little bit about React but I can hardly say I really understood it. Now it is part of my job, so I do want to understand it better. And what better way to understand it than by trying to write a blog post about it.\nA side note about that last statement. I often have vague understanding about various concepts that I gather from various sources I skim or read. But often there are gaps in my understanding. However, when I write as if I am introducing a concept to an audience (real or virtual), I have to concretize these vague concepts. And in doing so, I realize gaps in my understanding which I then research and fill. And hopefully in the process be a useful introduction to others on the internet. Now let\u0026rsquo;s start.\nIn the beginning, there was HTML. You went to a website in your browser, entered a URL, and the browser would do a server request. The server would send back some HTML, and the job of the browser was to accurately render the HTML. But that was mostly it. The browser\u0026rsquo;s main job was to be a renderer and send whatever interactive requests you made to the server.\nsequenceDiagram participant User participant Browser participant Server User-\u0026gt;\u0026gt;Browser: Enter URL Browser-\u0026gt;\u0026gt;Server: GET /index.html Server--\u0026gt;\u0026gt;Browser: HTML (Full Page) Browser--\u0026gt;\u0026gt;User: Render Page User-\u0026gt;\u0026gt;Browser: Click Link Browser-\u0026gt;\u0026gt;Server: GET /about.html Server--\u0026gt;\u0026gt;Browser: HTML (Full Page) Browser--\u0026gt;\u0026gt;User: Render New Page And then came Javascript. Javascript allowed the browser to not just be a renderer + HTTP client, but also a runtime. The server could send back HTML + Javascript, and in interacting with the site you could be interacting with HTML. Or you could be interacting with Javascript which could be doing things that programming languages do, like do calculations etc. This allowed even more interactivity. You could click a button and it could increment a counter! Among other things.\nAnd then came React. (I know, I know, that is a really bad chronology but I am not a historian so I will do my version!) React flipped the model to be more Javascript heavy. As against the server deciding completely what would show up on the browser, now it became common for websites to become completely client side. In other words it was an app now! When you visited a website that was React based, the server would send a thin HTML but heavy Javascript bundle. Once you had completely downloaded it (completely unaware of course), the entire site could in theory never interact with the server again. Your site was now more or less like an app installed on your machine doing some computations, rendering etc using browser APIs.\nsequenceDiagram participant User participant Browser participant Server User-\u0026gt;\u0026gt;Browser: Enter URL Browser-\u0026gt;\u0026gt;Server: GET /index.html Server--\u0026gt;\u0026gt;Browser: HTML (Empty Div) + bundle.js Browser-\u0026gt;\u0026gt;Browser: Execute JS (React) Browser-\u0026gt;\u0026gt;Server: GET /api/data (JSON) Server--\u0026gt;\u0026gt;Browser: { \u0026#34;data\u0026#34;: ... } Browser--\u0026gt;\u0026gt;User: Render Content User-\u0026gt;\u0026gt;Browser: Click Link Browser-\u0026gt;\u0026gt;Browser: Update DOM (Client-side Routing) Note over Browser, Server: No page reload! But people had issues with this model. The so called Single Page App (SPA) model. React is famously unopinionated and so one usually introduces a lot of dependencies which directly affects bundle size. As apps became more sophisticated, bundle sizes ballooned, and so load times increased. Many were also very nostalgic for the old simpler server first approach. And meantime Typescript was exploding in popularity because the developer experience is nicer with a types first approach. This coincided with the creation of Next. It was the answer to the question, what if we could create a server first React framework but completely in React so that developers could build entire apps without changing language or git repo.\nNext has an opinionated way of how you structure apps. One can have some functionality that is pure React, that is, client side. But it is server first meaning if you lean into the Next way of thinking, when you open a url in the browser, Next renders on the server and sends the appropriate HTML + Javascript back. Therefore bundle sizes are smaller and time to first load can be much faster.\nsequenceDiagram participant User participant Browser participant Server User-\u0026gt;\u0026gt;Browser: Enter URL Browser-\u0026gt;\u0026gt;Server: GET /index.html Note over Server: Server renders React to HTML Server--\u0026gt;\u0026gt;Browser: HTML (Pre-rendered Content) + RSC Payload Browser--\u0026gt;\u0026gt;User: Show Content Browser-\u0026gt;\u0026gt;Browser: Hydrate (Make Interactive) User-\u0026gt;\u0026gt;Browser: Click Link Browser-\u0026gt;\u0026gt;Browser: Client-side Navigation (like SPA) Browser-\u0026gt;\u0026gt;Server: GET /new-page (RSC Payload) Server--\u0026gt;\u0026gt;Browser: RSC Payload (Streaming) Browser-\u0026gt;\u0026gt;Browser: Reconcile React Tree But building APIs in Next can be inelegant. It is of course possible to define all APIs using Next but it can require quite some boilerplate to wire up correctly to the frontend. And the middleware/proxy thing is really confusing. People have resorted to various ways to make this easier. One popular way is to use tRPC where you write backend code and call it from your frontend and tRPC handles most of the wiring and boilerplate. But it does not help if you need to build REST/HTTP APIs. The most elegant solution that I have found to address this is to use Hono. It is not a full blown server like Express but is still plenty powerful. Next handles the entrypoint and then hands off API handling to Hono. One can build REST APIs with Hono while also having an RPC like interface similar to tRPC. And you know for sure that any code running inside Hono is running on the server, including the middleware!\nAnd that is where we will stop for today. This was definitely a highly compressed take on React and Next. I am sure that there were many technical nuances I completely glossed over but my objective was to create a good mental model of the frontend world as I see it. And hopefully create an entertaining post along the way!\nDisclaimer The blog post was completely written by a human, me! The diagrams were completely created by an LLM, Gemini (using Gemini 3 Pro Preview in the Gemini CLI)!\nNotes In Next if you mark some files as use client they increase bundle sizes, even though Next will still decide how much to render on the server vs what executes on the client. RSC stands for React Server Components which has more technical nuance but probably a subject for another blog post. Note also that Next has a Pages router which I have completely skipped over. ","permalink":"https://vikramsg.github.io/an-introduction-to-react-next-from-a-backend-engineer/","summary":"\u003cp\u003eI am not completely new to React.\nA couple of years ago I spent a few weeks struggling with frontend tools to create \u003ca href=\"https://49travel.vercel.app\"\u003e49travel\u003c/a\u003e.\nI learnt a lot about tooling, especially Vercel, a little bit about React but I can hardly say I really understood it.\nNow it is part of my job, so I do want to understand it better.\nAnd what better way to understand it than by trying to write a blog post about it.\u003c/p\u003e","title":"A Backend Engineer's Guide to Understanding React and Next.js"},{"content":"In Part 1, we talked about the \u0026ldquo;Why\u0026rdquo;. Why write a spec? Because English is ambiguous, and debugging design flaws in code is expensive. We looked at Quint and modeled a simple TCP Handshake. We verified that our logic was sound (no safety violations).\nBut as I hinted at the end of Part 1: a spec is just a file. If I go off and write code and ignore the spec, I haven\u0026rsquo;t really gained anything. In fact, I\u0026rsquo;ve just wasted time writing a spec.\nIn this part, we will close the loop. We will use what is called Model-Based Testing to ensure our Python implementation behaves exactly like our verified spec.\nThe Strategy: Trace Replay We can\u0026rsquo;t easily \u0026ldquo;compile\u0026rdquo; Quint to Python (yet). And we probably don\u0026rsquo;t want to, because the spec is an abstraction, not an implementation. The spec doesn\u0026rsquo;t care about hardware, dependencies or deployment! The implementation does.\nInstead, we treat the spec as a test case generator.\nFirst, generate a trace by using quint to run a simulation and save the sequence of steps (the trace) to a file. Then, we replay the trace in Python, but we instrument it so that it looks like a test. For every step in the trace (e.g., SendSyn), we execute the corresponding method in our Python class. Finally, after each step, we check if our Python object\u0026rsquo;s state matches the spec\u0026rsquo;s state. If the test passes, we know our code handles the scenarios defined by the spec correctly.\nStep 1: Generating the Trace In Part 1, we ran quint run to see text output. Now, we want a machine-readable format. Quint supports a format called ITF. Luckily, its a JSON format, meaning its both easy to read as well as integrate in code.\nRunning:\nquint run --mbt --max-steps=10 --out-itf=trace.itf.json tcp_simple.qnt This produces a JSON file that looks roughly like this:\n{ \u0026#34;vars\u0026#34;: [\u0026#34;client_state\u0026#34;, \u0026#34;server_state\u0026#34;, \u0026#34;mbt::actionTaken\u0026#34;], \u0026#34;states\u0026#34;: [ { \u0026#34;#meta\u0026#34;: { \u0026#34;index\u0026#34;: 0 }, \u0026#34;client_state\u0026#34;: { \u0026#34;tag\u0026#34;: \u0026#34;INIT\u0026#34; }, \u0026#34;server_state\u0026#34;: { \u0026#34;tag\u0026#34;: \u0026#34;INIT\u0026#34; }, \u0026#34;mbt::actionTaken\u0026#34;: \u0026#34;init\u0026#34; }, { \u0026#34;#meta\u0026#34;: { \u0026#34;index\u0026#34;: 1 }, \u0026#34;client_state\u0026#34;: { \u0026#34;tag\u0026#34;: \u0026#34;SYN_SENT\u0026#34; }, \u0026#34;server_state\u0026#34;: { \u0026#34;tag\u0026#34;: \u0026#34;INIT\u0026#34; }, \u0026#34;mbt::actionTaken\u0026#34;: \u0026#34;SendSyn\u0026#34; }, ... ] } It captures the exact state of the system at every step. Note that this is just one possible execution path. In the \u0026ldquo;Scaling Up\u0026rdquo; section below, we will discuss how to test against many random traces.\nStep 2: The Python Implementation Now let\u0026rsquo;s write an implementation. We want to make sure that unrepresentable states are actually unrepresentable. We will use Pydantic, Enums, Tagged Unions, and one of my favourite newish feature of Python - Pattern Matching for this.\n# tcp.py from enum import Enum from typing import Literal, Union, Annotated from pydantic import BaseModel, Field class State(str, Enum): INIT = \u0026#34;INIT\u0026#34; SYN_SENT = \u0026#34;SYN_SENT\u0026#34; SYN_RCVD = \u0026#34;SYN_RCVD\u0026#34; ESTABLISHED = \u0026#34;ESTABLISHED\u0026#34; # We define each valid \u0026#34;System State\u0026#34; as a separate Model. class InitState(BaseModel): tag: Literal[\u0026#34;Init\u0026#34;] = \u0026#34;Init\u0026#34; client_state: Literal[State.INIT] = State.INIT server_state: Literal[State.INIT] = State.INIT class SynSentState(BaseModel): tag: Literal[\u0026#34;SynSent\u0026#34;] = \u0026#34;SynSent\u0026#34; client_state: Literal[State.SYN_SENT] = State.SYN_SENT server_state: Literal[State.INIT] = State.INIT # ... other valid state models (SynRcvdState, FullyEstablishedState, etc.) ... TCPState = Annotated[ Union[InitState, SynSentState, ...], # All valid states Field(discriminator=\u0026#34;tag\u0026#34;) ] class TCPModel: def __init__(self): self.state: TCPState = InitState() def send_syn(self): match self.state: case InitState(): self.state = SynSentState() return True case _: return False # ... receive_syn, receive_syn_ack, receive_ack, etc. This looks simple, but notice how the logic in send_syn uses the match statement? By using specific Pydantic models for each state, it becomes impossible to even construct an invalid state (like Server being ESTABLISHED while Client is INIT). If we messed up the transition logic, the state wouldn\u0026rsquo;t match the spec.\nStep 3: The Replay Test The way we ensure the implementation matches the spec is by doing replay tests. We write a test that reads the JSON trace and drives the Python model.\n# test_tcp.py (simplified) import json from tcp import TCPModel def main(): with open(\u0026#34;trace.itf.json\u0026#34;) as f: trace = json.load(f) model = TCPModel() # Skip index 0 as it is the initial state for i, state_json in enumerate(trace[\u0026#34;states\u0026#34;][1:], 1): action = state_json[\u0026#34;mbt::actionTaken\u0026#34;] match action: case \u0026#34;SendSyn\u0026#34;: success = model.send_syn() case \u0026#34;ReceiveSyn\u0026#34;: success = model.receive_syn() # ... handle other actions ... if not success: raise Exception(f\u0026#34;Action {action} failed at step {i}\u0026#34;) # Verify state matches assert model.state.client_state.value == state_json[\u0026#34;client_state\u0026#34;][\u0026#34;tag\u0026#34;] assert model.state.server_state.value == state_json[\u0026#34;server_state\u0026#34;][\u0026#34;tag\u0026#34;] print(\u0026#34;Trace verified successfully!\u0026#34;) Its a little bit finicky, since we will have to do a match between the action as specified in the spec vs the function/method in the code. But, it does what we want, namely reads the action from the trace, executes it on the model, and asserts that the resulting state matches the spec. If the implementation (Python) and the Spec (Quint) disagree, this test fails.\nWhy is this powerful? It gives us fuzzing for free. Quint\u0026rsquo;s random simulation generates edge cases we might forget to test manually. The spec is documentation, and the tests ensure the code respects it. We made unrepresentable state impossible (within the margins of how strict one can be with types in Python). By using Pydantic tagged unions, we ensure that the code can only ever be in a valid state. Scaling Up In this simple TCP example, the logic is linear because of guards we put in the spec, so every random trace looks identical. However, for complex protocols, we typically run this process in a loop (generating lots of traces). Since Quint picks random paths, this effectively fuzzes any implementation against the spec.\nHowever, note that the scale of this approach has a limit. More complicated specs have many different trace paths. And we cannot possibly test again all of them. But testing a sample of traces is definitely better than none.\nWhat about Invariants? You might ask: \u0026ldquo;Where are we checking the invariants (like Safety) in the Python test?\u0026rdquo; Well, we don\u0026rsquo;t, Quint does! During the simulation phase, if a sequence of steps leads to a violation, Quint reports it as a Violation Error. The job of the tracing test is purely to ensure that the code conforms to the spec. And if the code matches the spec, then we will be reasonably confident that the code is correct.\nThe Caveat: We still need Unit Tests Formal methods are great for logic and state machines, but they don\u0026rsquo;t replace unit tests entirely. Specs often abstract away details. For example, in TLS, the spec might say:\naction Encrypt = { encrypted_data\u0026#39; = encrypt(data, key) } The spec assumes encrypt works mathematically. It doesn\u0026rsquo;t check if your AES-GCM implementation handles padding correctly, or if you have an off-by-one error in your buffer allocation. For those lower-level implementation details, standard unit tests are still required. We use formal methods to verify the orchestration and logic, and unit tests to verify the primitives. I believe verification aware languages like Dafny could possibly bridge the gap but that is a topic for another day.\nConclusion So, we went from high level requirement to a formal spec in Quint. We did verification via model checking in Quint. Then actually did an implementation and showed the mechanism for proving the implementation matches the spec (in a fuzzy sense). Pretty neat!\nI hope that is a convincing argument to think about adopting specs to make working with Agents easier. Instead of struggling with English to produce concrete requirements, we can collaborate with our favourite agent to produce a spec for the set of components we are building. And if the tooling is in place, we can just tell the agent to build the component, and the trace tests will make sure we adhere to the spec.\nCode The code used in this post can be found here.\n","permalink":"https://vikramsg.github.io/introduction-to-formal-methods-part-2/","summary":"\u003cp\u003eIn \u003ca href=\"https://vikramsg.github.io/introduction-to-formal-methods-part-1/\"\u003ePart 1\u003c/a\u003e, we talked about the \u0026ldquo;Why\u0026rdquo;.\nWhy write a spec? Because English is ambiguous, and debugging design flaws in code is expensive.\nWe looked at \u003cstrong\u003eQuint\u003c/strong\u003e and modeled a simple TCP Handshake.\nWe verified that our logic was sound (no safety violations).\u003c/p\u003e\n\u003cp\u003eBut as I hinted at the end of Part 1: a spec is just a file.\nIf I go off and write code and ignore the spec, I haven\u0026rsquo;t really gained anything.\nIn fact, I\u0026rsquo;ve just wasted time writing a spec.\u003c/p\u003e","title":"Introduction to Formal Methods (Part 2): From Spec to Code"},{"content":"Formal methods, sounds very\u0026hellip; formal! But I have been trying to explore what they are and so I decided to write down my learnings. Hopefully this proves a good starting point for someone else who is curious about the idea but doesn\u0026rsquo;t have a good starting point.\nThis post is part 1 of 2. In part 1, I will try to give a more conceptual understanding, while also introducing tooling using Quint. In part 2, I will try to show how it can be wired up so that we make sure software implementations actually benefit from formal methods.\nThe Problem with English (and AI) First a warning, and then if you stick around, we can go deeper. My dive into formal methods was motivated by posts like this. I have been increasingly using AI Agents and I believe something is required to make the use of AI more productive. And if the word AI is triggering, then this would be a good time to stop reading. If you are still here, let\u0026rsquo;s talk about AI a little bit, and the programming language for AI - English.\nWe prompt agents in English. We write requirements documents in English.\n\u0026ldquo;The user is authenticated after a successful handshake.\u0026rdquo; \u0026ldquo;The program is crashing. Fix it.\u0026rdquo; But English is inherently ambiguous. What \u0026ldquo;program\u0026rdquo;? What exactly constitutes a \u0026ldquo;successful handshake\u0026rdquo;? Are we talking about a human handshake?\nWhen we jump straight to code based on English prompts, the implementation becomes the specification. If the Agent guesses wrong, that guess can lead to some very complicated code. And cue the inevitable conversation,\n{ \u0026#34;user\u0026#34;: \u0026#34;This isn\u0026#39;t what I meant\u0026#34;, \u0026#34;agent\u0026#34;: \u0026#34;You are absolutely right. You are amazing. I will fix it.....\u0026#34; ... ... \u0026#34;agent\u0026#34;: \u0026#34;Here\u0026#39;s the updated code.\u0026#34; \u0026#34;user\u0026#34;: \u0026#34;That\u0026#39;s still wrong\u0026#34;. } If that feels familiar, hopefully the following points to a way forward.\nMore and more software will be written by AI. That leaves me, the human, needing to somehow verify that the software is correct, but I don\u0026rsquo;t have the ability to read thousands of lines of code constantly. But what if we had the ability to define the system with a much smaller volume of text that I can read and verify and have the confidence that if the software meets this spec, it is correct. The Scary Part: TLA+ This isn\u0026rsquo;t a new problem. Decades ago, Leslie Lamport (the creator of LaTeX and distributed systems legend) gave us TLA+ (Temporal Logic of Actions). It is the gold standard for formal verification. It is used by AWS (DynamoDB, S3) and Azure. It works.\nBut then I looked at TLA+. And this is what it looks like.\nTotal == LET S == { r[type] : r \\in Records } IN Cardinality(S) Inv == \\A r \\in Records : r.amount \u0026gt;= 0 Yes, if you are thinking that looks like LaTeX, that\u0026rsquo;s exactly how I felt. Don\u0026rsquo;t get me wrong, I loved LaTeX back when I was in Graduate School. There\u0026rsquo;s nothing better to write equations. But if we could write equations (and the other stuff required to write a paper or thesis) in Python, I would take Python over LaTeX anyday. And my job does not involve equations (most of the time). Ultimately, if the spec is harder to read than the code, the spec is almost never going to be written.\nEnter Quint This is where Quint comes in. It is TLA+ for humans, or software engineers (who are also humans for now). It looks way closer to something like TypeScript than LaTeX. I think if you can read code, you can read Quint.\nA Concrete Example: The TCP Handshake To understand what we can do with this, let\u0026rsquo;s look at something a lot of us know and understand: the TCP 3-way handshake. We want to verify that a client and server can establish a connection correctly.\nIn code, we\u0026rsquo;d worry about packets, sequence numbers, buffers, and timeouts. In a spec, we worry about State and Transitions.\n1. Modeling State We define the universe of our protocol.\nmodule tcp_simple { // Types type State = INIT | SYN_SENT | SYN_RCVD | ESTABLISHED // State Variables var client_state: State var server_state: State // Initial State action Init = all { client_state\u0026#39; = INIT, server_state\u0026#39; = INIT, } 2. Defining Actions (Transitions) Next, we define what can happen. These are the rules of the road.\n// Client sends SYN action SendSyn = all { // \u0026#39;all\u0026#39; means all statements must hold true (Logical AND) client_state == INIT, // Precondition: Client must be INIT client_state\u0026#39; = SYN_SENT, // Transition: Client moves to SYN_SENT (Note the \u0026#39; for next state) server_state\u0026#39; = server_state // Server state doesn\u0026#39;t change yet } // Server receives SYN, sends SYN-ACK action ReceiveSyn = all { server_state == INIT, client_state == SYN_SENT, // Wait for Client to send SYN server_state\u0026#39; = SYN_RCVD, client_state\u0026#39; = client_state } // Client receives SYN-ACK, sends ACK action ReceiveSynAck = all { client_state == SYN_SENT, server_state == SYN_RCVD, client_state\u0026#39; = ESTABLISHED, server_state\u0026#39; = server_state } // Server receives ACK action ReceiveAck = all { server_state == SYN_RCVD, client_state == ESTABLISHED, server_state\u0026#39; = ESTABLISHED, client_state\u0026#39; = client_state } action step = any { SendSyn, ReceiveSyn, ReceiveSynAck, ReceiveAck, } } This is very readable. Now, let\u0026rsquo;s go over what the snippet says. First note that there is no explicit ordering. We are not saying \u0026ldquo;Run SendSyn then ReceiveSyn\u0026rdquo;.\nIn Quint, these actions are a menu of choices. At every step, the system (the Quint simulator) asks: \u0026ldquo;Which of these actions is allowed to happen right now?\u0026rdquo;, for example, at the beginning, everyone is in the INIT state.\nCan ReceiveSyn happen? No. It requires client_state == SYN_SENT. Can SendSyn happen? Yes. It requires client_state == INIT. So, the simulator picks SendSyn. The order isn\u0026rsquo;t hardcoded. The order emerges from the logic.\n3. Simulation Unlike a static diagram, we can run this. Quint has a built-in simulator. We can ask it: \u0026ldquo;Run this logic for 10 steps and see what happens.\u0026rdquo;\nquint run --max-steps=10 tcp_simple.qnt It will execute the actions randomly, effectively \u0026ldquo;fuzzing\u0026rdquo; our design logic. It produces a trace: Init -\u0026gt; SendSyn -\u0026gt; ReceiveSyn -\u0026gt; ReceiveSynAck ...\n4. Invariants (The Guardrails) This is the superpower. We can define properties that must always be true.\nFor example, we might want to assert that the Server never thinks the connection is established before the Client has at least initiated it.\nval Safety = not (server_state == ESTABLISHED and client_state == INIT) If we run the simulator (or the model checker), and it finds a sequence of events that leads to this invalid state, it reports a Violation. It gives us the exact trace of steps that caused the bug. We fix the logic in the spec, long before we\u0026rsquo;ve written a single line of C or Rust or Mojo.\nRecap To summarize, with Quint we get:\nA Readable Spec: A precise description of the system (State \u0026amp; Transitions) that is easy to read. Simulation: A way to run the spec and explore behaviors (like fuzzing). Invariants: A way to define properties that must always be true. Caveats Having just gone through all of that, I do have to warn about shortcomings. Formal methods and spec driven development isn\u0026rsquo;t the single solution to all our problems. Notably:\nThe model is only as good as our description of the world. If we don\u0026rsquo;t model the complete system (or are unable to) then there are gaps. Note that tools like TLA+ and Quint are best suited for modeling a state machine. So figure out which parts of your system is a state machine and which parts pure functions. Model functions using unit tests. We are not solving for non functional requirements like performance, readability etc. What\u0026rsquo;s Next? So we have a verified spec. We know our logic is sound. We know that our state machine respects our safety properties.\nBut a spec in a file is just some text (or outdated documentation!). How do we ensure our actual code implements this logic correctly?\nIn Part 2, we will explore how to make sure the code follows the spec.\n","permalink":"https://vikramsg.github.io/introduction-to-formal-methods-part-1/","summary":"\u003cp\u003eFormal methods, sounds very\u0026hellip; formal!\nBut I have been trying to explore what they are and so I decided to write down my learnings.\nHopefully this proves a good starting point for someone else who is curious about the idea but doesn\u0026rsquo;t have a good starting point.\u003c/p\u003e\n\u003cp\u003eThis post is part 1 of 2.\nIn part 1, I will try to give a more conceptual understanding, while also introducing tooling using \u003ccode\u003eQuint\u003c/code\u003e.\nIn part 2, I will try to show how it can be wired up so that we make sure software implementations actually benefit from formal methods.\u003c/p\u003e","title":"Introduction to Formal Methods (Part 1): Why Spec First?"},{"content":"The last couple of posts have been about 49travel and the way I built it. This week I am going to be talking about decorators for a bit. It seems very disconnected from the last posts, but I started reflecting on this while writing some Python for 49travel. So there\u0026rsquo;s still a connection!\nPython requests As a reminder, to build 49travel, I had to use the amazing Transport Rest API. However, this is obviously not built for production and so does rate limiting. Which is fine since we can just add a rate limit on our side by introducing time.sleep. For eg., this would be one way to do this.\nimport requests def _request(): location_url = \u0026#34;https://v6.db.transport.rest/locations?query=Hamburg\u0026amp;results=1\u0026#34; location_response = requests.get(location_url) time.sleep(1) This would ensure that everytime we call _request, we would wait 1 second after the get request, ensuring less than 60 requests per minute. But while working with this code, I started seeing issues. First I had to introduce a timeout inside the get request.\nlocation_response = requests.get(location_url, timeout=1) I really have no explaination for this, but the request would wait infinitely if I did not add this to the request. Which is fine, but I kept getting connection errors even after this. So I decided to introduce retries into the request session. Pay attention to this because we will get back to this later. This is how I add retries.\ndef session_with_retry() -\u0026gt; requests.Session: session = requests.Session() retries = 3 backoff_factor = 0.3 retry = Retry( total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, ) adapter = HTTPAdapter(max_retries=retry) session.mount(\u0026#34;http://\u0026#34;, adapter) session.mount(\u0026#34;https://\u0026#34;, adapter) return session In the function, retries = 3 ensures that if the connection fails, requests will try 3 more times. The backoff_factor ensures that after each failure past the second try, the request waits exponentially longer.\n{backoff factor} * (2 ** ({number of previous retries})) We edit our previous function to now use the retry strategy.\ndef _request(): location_url = \u0026#34;https://v6.db.transport.rest/locations?query=Hamburg\u0026amp;results=1\u0026#34; request_session = session_with_retry() location_response = request_session.get(location_url, timeout=1) Problem solved, right? Yes, but as you can see, the code isn\u0026rsquo;t very nice. First, the weird timeout inside the request, and then the ugly Retry code.\nPyhafas While thinking of making this cleaner, I discovered pyhafas. And remarkably, it solved my first problem. I no longer had to use the _request function, create query parameters etc. Instead of a REST API, I could use the pyhafas API!\nfrom pyhafas import HafasClient def _journey(): client = HafasClient() return client.journeys( origin=origin, destination=destination, ... ) But I still had my second problem. A few requests, and I would get Connection Error. And now I don\u0026rsquo;t have direct control over the Retry strategy. So, I decided to create my own!\nfor i in range(4): try: journeys = _journey() return journeys except requests.exceptions.ConnectionError as e: print(f\u0026#34;Connection reset. Error: {e.args[0]}. Waiting to try again.\u0026#34;) time.sleep(2 * (i + 1) * 20) print(\u0026#34;Trying again\u0026#34;) Here, the i loop is the number of retries and I made my own custom exponential backoff with some tuning. It worked. I hated it!\nTenacity I decided that the ideal way forward would be to actually change the code in pyhafas. But when I started to write the changes, I realized something else. The retry code is really ugly. Look at this monstrosity again. Also notice that we need 3 different imports to implement it.\nimport requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry session = requests.Session() retries = 3 backoff_factor = 0.3 retry = Retry(... adapter = HTTPAdapter(max_retries=retry) session.mount(\u0026#34;http://\u0026#34;, adapter) session.mount(\u0026#34;https://\u0026#34;, adapter) At this point I discovered tenacity while reading through some OpenAI examples. And this is so much nicer.\nfrom tenacity import retry, retry_if_exception_type, wait_exponential, stop_after_attempt @retry( wait=wait_exponential(multiplier=tenacity_multiplier), stop=stop_after_attempt(tenacity_retry_attempts), retry=retry_if_exception_type(requests.ConnectionError), ) def journey(... Now I don\u0026rsquo;t have to deal with creating sessions and adapters and all that jazz anymore. The imports are all together on a single line. And this is in fact even more general. It doesn\u0026rsquo;t necessarily apply to only connection errors. That\u0026rsquo;s just the choice I want to make here. Plus, you control the retries explicity rather than through indirections.\nComposability using decorators Going through this exercise really highlighted to me how powerful decorators are. There are many examples of how they are being used in a similar manner. Consider Airflow.\nfrom airflow.decorators import dag, task @dag def my_dag(): @task def task1(): # Task 1 logic goes here @task def task2(): # Task 2 logic goes here This is such a nice way of defining the DAG. You just write the functions for a task and wrap it with a decorator and it becomes a DAG(of course you also need to define inter task dependencies).\nOr Numba, which we touched upon in a previous post.\nfrom numba import njit @njit def plus_one(a): return a+1 I think this is a template that should be followed to make Python libraries more composable, as opposed to the boilerplate we needed to do for Retry.\nFinal thoughts This post became longer than I had originally thought, but I figured that these are the steps I went through to make this realization. And so I needed the context to be clear. Library design is not easy, but recognizing these patterns will lead to better designs. Decorators really make trying out new stuff super simple and I wish to see more of this in the future.\n","permalink":"https://vikramsg.github.io/blog_python_decorators_style/","summary":"\u003cp\u003eThe last couple of posts have been about \u003ca href=\"https://49travel.vercel.app/\"\u003e49travel\u003c/a\u003e and the way I built it.\nThis week I am going to be talking about decorators for a bit.\nIt seems very disconnected from the last posts, but I started reflecting on this\nwhile writing some Python for 49travel.\nSo there\u0026rsquo;s still a connection!\u003c/p\u003e\n\u003ch2 id=\"python-requests\"\u003ePython requests\u003c/h2\u003e\n\u003cp\u003eAs a reminder, to build \u003ca href=\"../blog_49travel/\"\u003e49travel\u003c/a\u003e, I had to use the amazing \u003ca href=\"https://transport.rest/\"\u003eTransport Rest API\u003c/a\u003e.\nHowever, this is obviously not built for production and so does rate limiting.\nWhich is fine since we can just add a rate limit on our side by introducing \u003ccode\u003etime.sleep\u003c/code\u003e.\nFor eg., this would be one way to do this.\u003c/p\u003e","title":"Decorators in Python make composability easier"},{"content":"Last week I talked about how I created 49travel. I went over broadly on the ingredients and often glossed over many details. This week I want to talk about one particular aspect which was pretty interesting for me. It was a nice introduction to the various projects going on in the LLM world that are being furiously worked on since the entry of ChatGPT.\nThe problem As I mentioned in the last post, the reason I wanted to use an LLM was to produce a short summary of the WikiVoyage page so that a visitor to the page could get a nice overview. I originally tried to do this by simply trying to extract the list of places to see and things to do using some ill-formed Regex, but it was soon obvious that this would require a lot of effort. Not all Wikivoyage pages follow the same format and some listings can have really strange formatting. I then thought that an LLM could be a good candidate to solve this problem. What if we simply give it the page, and it summarizes the page for us? But how do I go about doing this?\nLangchain The idea to use Langchain came to me while I was attending a Machine Minds Hackathon. Sebastian was kind enough to show me what he had been doing using gpt on Discord for summarizing and so I thought this would be the right time to dive into langchain. But there was a catch. One of the constraints that I had put on myself while developing 49travel was to use only free stuff. There was no specific reason for this except for me to find out if this was even possible. gpt is of course not free. So what do I do?\nThere was another development in LLM that I had been following. This was the open-assistant project. This was trying to recreate the ChatGPT training process but with open models. They actually already had a model up and running, but there was a problem. This was using LLAMA, and I didn\u0026rsquo;t want to touch it with all its licensing issues. But they had also done the same with a different model, which was the Pythia model with 12 Billion parameters. But how do I run this? I don\u0026rsquo;t have a GPU lying around. Turns out there\u0026rsquo;s an easier way to do this. HuggingFace provides a Hosted Inference API with rate limits, with which you can run models of reasonable size but with rate limits.\nMaking it work The way the summarization works is that bigger documents are split up into smaller documents, then each chunk is summarized and finally they are all combined and then the combined text is summarized. This in a way is MapReduce and that is exactly what the langchain API calls it.\nchain = load_summarize_chain( llm, chain_type=\u0026#34;map_reduce\u0026#34;, combine_prompt=combine_prompt ) However, at this point I hit a hitch. langchain has inbuilt functions for gpt as well as other models that are loaded locally. But I couldn\u0026rsquo;t quite figure out how to use it for an API that was not gpt. So, I did the most obvious thing, and built a simple MapReduce loop. I get the WikiVoyage text, break it up into chunks, summarize each one using the API and then combine the summaries and then use the API again to summarize it.\nGPT4ALL I also wanted to test out gpt4all-groovy since it was supposed to be small enough to run locally. No API calls required! But that was a bit of a pain. It has an installer, but it did not support my older MacOS. So I installed it from source, which was in fact not so painful, but there were multiple steps. Then there were some pip installs required and so I had to mix poetry with pip. Finally, it did work though, which was a win. So, what were the results?\nSummaries The first thing I noticed was that prompting the Pythia model was a bit of a pain. At the Hackathon, we discussed some possible prompts, and initially it seemed to work. But I realized when trying to do multiple WikiVoyage pages that it was very unpredictable. Sometimes, it would produce very nice summaries. Other times, it wouldn\u0026rsquo;t produce anything at all. And sometimes it would spit out complete nonsense.\ngpt4all is fairly slow, but in my experience, fairly consistent. However, it is more or less impossible to steer. It spits out whatever it wants to spit out and nothing else! Of course, as you know, at the end I gave up and just used gpt-3.5-turbo. That turned out to cost about $4 and it was incredibly reliable and required very little prompt tuning. On the other hand, as some of you may have noticed, it likes the word charming a bit too much when describing touristy places.\nI have created a comparison of summaries for the WikiVoyage page of Allgäu. The prompts are all more or less the same. First, I ask it to summarize each chunk using\nSummarize the following text. Then I combine the resulting summaries, and ask it to use the following prompt to produce an overall summary.\nCombine all the summaries on {city} provided within backticks ```{total_summary}```. Can you summarize it as a tourist destination in 8-10 sentences. Notice how well gpt performs. Pythia seems to do an ok job, but it completely misses some of the nice places to visit such as Neuschwanstein castle. And it does not really stick to 8-10 sentences. gpt4all is very formal and answers like its a college exam question!\nFinal thoughts I think this was an interesting exercise to do, just to find out what the state of the art is. The first thing I learnt was that langchain is incredibly useful. Summarization is just one of its many intended usecases. I need to explore more. Using Pythia was interesting. First, I learnt of the hosted inference API, which seems very useful for just testing out models that you don\u0026rsquo;t want to self-host without having a go. HuggingFace seem to be doing a very nice job. Don\u0026rsquo;t expect to use the free API in production though. The rate limits kick in very quickly. gpt4all seems more like a toy. But the very fact that it even runs on my CPU only system is remarkable. Of course, gpt just works. But I look forward to other models atleast try to catch up.\nCode The code is available here. gpt-3.5-turbo and pythia are fairly easy to use since they are both API\u0026rsquo;s but gpt4all requires some setup work. This is explained in the README file.\n","permalink":"https://vikramsg.github.io/blog_langchain/","summary":"\u003cp\u003eLast \u003ca href=\"../blog_49travel/\"\u003eweek\u003c/a\u003e I talked about how I created \u003ca href=\"https://49travel.vercel.app/\"\u003e49travel\u003c/a\u003e.\nI went over broadly on the ingredients and often glossed over many details.\nThis week I want to talk about one particular aspect which was pretty interesting for me.\nIt was a nice introduction to the various projects going on in the LLM world that are being furiously worked on\nsince the entry of ChatGPT.\u003c/p\u003e\n\u003ch2 id=\"the-problem\"\u003eThe problem\u003c/h2\u003e\n\u003cp\u003eAs I mentioned in the last post, the reason I wanted to use an LLM was to produce a short summary of the WikiVoyage\npage so that a visitor to the page could get a nice overview.\nI originally tried to do this by simply trying to extract the list of places to see and things to do using\nsome ill-formed Regex, but it was soon obvious that this would require a lot of effort.\nNot all Wikivoyage pages follow the same format and some listings can have really strange formatting.\nI then thought that an LLM could be a good candidate to solve this problem.\nWhat if we simply give it the page, and it summarizes the page for us?\nBut how do I go about doing this?\u003c/p\u003e","title":"Comparing GPT with Open Source LLM's"},{"content":"49travel\nThis post will be very different than the last few. Over the last couple of weeks, I have been working on an idea for a webapp. In May, Germany launched the Deutschland Ticket. This is an amazing new offer where we can buy a ticket for 49 Euros a month, and access any public transport across Germany. Its all included! So, I made a website to find out all places you could go with this ticket, how long it takes and why that city is worth visiting. To start with, it only shows all places you can get to from Hamburg, but other cities are coming soon. Stay tuned.\nKernel of an idea The starting idea came during a trip to Bremen. Bremen is just over an hour away from Hamburg and we decided to visit because of the freedom of the 49 Euro ticket. You can now visit so many places without worrying about the cost of the travel. Bremen was great but then we started thinking. How do we find out ALL places we could visit that we may not know about? And that was the starting point. I started with the notion that this should be fairly simple to do. Deutsch Bahn should have some API and we simply need to extract data from that, right?\nAPI shenanigans So I registered for DB API\u0026rsquo;s. And I tried to follow the documentation. And zilch. There is more or less just one API and all it tells me are the timetables at particular stations. It does not help since what I wanted to get were journeys between stations. I deep dived into the world of available API\u0026rsquo;s and found an amazing resource. There\u0026rsquo;s a Transport API, that actually has the API that, in its own words \u0026ldquo;it returns whatever data the DB Navigator app shows\u0026rdquo;. That is amazing! So we have an API.\nWhat\u0026rsquo;s the content? So we have an API, but what do we get out of it? Of course, first we use query parameters to exclude IC/ICE/EC trains, since they are not included in the 49 euro ticket. Weirdly the API considers Flix trains as regional trains so I had to filter them out.\nThe very first requirement I had put when starting to work on this was that I want to know all places I could get to from Hamburg. So, my initial idea was to just get all \u0026ldquo;Trips\u0026rdquo; from Hamburg. This would mean that I find all destinations of regional trains. And then the destinations after that. Immediately, that notion had 2 problems. The Trips endpoint does not provide journey times, so I would have to call yet another API to find journey times. Second, and more important, I would miss places that are not destinations. This immediately excludes places like Lübeck which is a popular tourist destination. So, I needed to rethink.\nWikiVoyage Clearly, the answer was that we first need to find the places to visit, and then do a Journey query from Hamburg to that destination. But where do we find those places. That\u0026rsquo;s where I started thinking about WikiVoyage. I knew it existed, but does it have an API or would I have to scrape it? And how would I know how to extract touristy places? Well, first, it turns out WikiVoyage has the exact same API as Wikipedia! So, you use it the exact same way and just replace wikipedia with wikivoyage in the URL. And you can just use the API to get page extracts for the full page.\nBut what about finding cities. After some furious Googling, I found, as is typical, some random post on StackOverflow that mentions Categories. Category pages have the directory structure of a particular category. So everything belonging to some category will have a top page, and then sub-categories and then finally all pages within those category and sub-categories. So of course, there is a Category: Germany page. And so I used a queue to traverse the whole directory structure and get all cities. There was some filtering required because some of the pages were \u0026ldquo;Regions\u0026rdquo; and not \u0026ldquo;Cities\u0026rdquo; but that was fairly easy.\nOnce I had all cities(or towns), I used the tranport API to extract Stop ID for each city. And then I could just do a Journey query between Hamburg and those cities. So, I could extract journey times for all of those cities. Now what?\nDeploy From the start I felt that this was going to be the scary part. I have no frontend experience besides using Streamlit or Dash, which would be insufficient. I was sure I needed a frontend that made it useful, but how do I do that with my limited knowledge. So, I had to make a leap of faith. I knew that Vercel makes it easy to deploy websites. So I made an account and staying to true to engineering wisdom, made a boring choice. I deployed the Create React App on Vercel. The leap of faith was that with zero JavaScript experience I could still make it work with ChatGPT. But I felt a bit overwhelmed and so decided that the first version was going to be just a big MarkDown file, since MarkDown I understood. So that was my first version. A huge text file! On the internet.\nEnter gpt-3.5-turbo I now had a trip API and all cities worth visiting in Germany. But what do I put on the website? My initial idea was that I would put the list of cities, sorted by journey time and a short touristy description for the city. But where do I get the description? Initially I thought I would just scrape WikiVoyage. But the text was very unstructured and I get very weird output. The solution, and it took some time for me to figure this out, was to actually use gpt-3.5-turbo to summarize the pages. I will write another post about that since I had to do quite a bit of experimentation for that. That was the only part that cost money. A whopping $4 for summarizing ALL cities in Germany on Wikivoyage!\nShare app and brace for feedback So, having finally created a crazy big text file and put it on the internet, I decided to share it with friends. I was sure that the ugliness would be the first thing that would be commented on. But there were quite a few suggestions apart from the ugliness. Infinite scroll was one of the ones I was surprised about. Another one that I had not considered were having live status(solving that was another rabbit hole).\nNext I went on another quest of fighting with React using ChatGPT. I made the wrong choice of using Material UI since I had read somewhere that it was the popular choice. That was a mistake. Chose boring technology everytime. I realized my mistake and shifted to Bootstrap. And gradually made some progress. Decided on a simple layout and organized the pages. Put in drop down buttons. And finally, pagination to remove infinite scroll. And that\u0026rsquo;s what you see now.\nFinal thoughts This was a long post. And while writing it, I realized that there was so much that I skimmed over. It was a fun build, but that does not mean I am going to stop. The initial objective was to make something quickly, ask for feedback and iterate. I think I accomplished that. There\u0026rsquo;s more to do, but I think its at a stage where I can share it with the world. Hopefully, you find it useful. I know I will.\n","permalink":"https://vikramsg.github.io/blog_49travel/","summary":"\u003cp\u003e\u003ca href=\"https://49travel.vercel.app/\"\u003e49travel\u003c/a\u003e\u003c/p\u003e\n\u003cp\u003eThis post will be very different than the last few.\nOver the last couple of weeks, I have been working on an idea for a webapp.  \u003cbr\u003e\nIn May, Germany launched the Deutschland Ticket.\nThis is an amazing new offer where we can buy a ticket for 49 Euros a month,\nand access any public transport across Germany. Its all included!\nSo, I made a \u003ca href=\"https://49travel.vercel.app/\"\u003ewebsite\u003c/a\u003e to find out\nall places you could go with this ticket,\nhow long it takes and why that city is worth visiting.\nTo start with, it only shows all places you can get to from Hamburg,\nbut other cities are coming soon. Stay tuned.\u003c/p\u003e","title":"49travel - Travel across Germany with your 49 Euro ticket"},{"content":"In our last couple of posts we looked at how we could optimize pandas functions. This post will be different. We still want to address issues that we face in the PySpark world, but today we will not look at performance at all.\nParameters in a Pandas UDF In PySpark, when we want to use a Pandas UDF, we actually have 2 options. We can use the regular Pandas UDF, or we can use the Pandas Function API. While both of them address the UDF question, the actual function implemented still operates on a Pandas DataFrame, so that simplifies what we want to address in this post.\nSuppose, just as before, we create a Pandas DataFrame for 3 categories, and have a column represent sales over a year.\n_CATEGORIES = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] _YEARS = range(2010, 2021) _X_VALUES = [0, 0.1, 0.25, 0.5, 1.0] def create_dataframe() -\u0026gt; pd.DataFrame: data = [] for category in _CATEGORIES: for year in _YEARS: for x in _X_VALUES: y = 25.0 * x + random.uniform(0, 1) data.append([category, year, x, y]) return pd.DataFrame(data, columns=[\u0026#34;category\u0026#34;, \u0026#34;year\u0026#34;, \u0026#34;x\u0026#34;, \u0026#34;y\u0026#34;]) We can easily convert this to a Spark dataframe using spark.createDataFrame. Next, we want to get sales after a particular fraction of the year. Previously, we did the groupBy inside the Pandas function, but let\u0026rsquo;s do it using PySpark now.\n_INTERPOLATE_AT = 0.3 def numpy_interpolate_global_args(indices: Tuple[int, int], df: pd.DataFrame) -\u0026gt; pd.DataFrame: interpolated_value = np.interp(_INTERPOLATE_AT, df[\u0026#34;x\u0026#34;], df[\u0026#34;y\u0026#34;]) return pd.DataFrame( data={ \u0026#34;category\u0026#34;: indices[0], \u0026#34;year\u0026#34;: indices[1], \u0026#34;interpolated_value\u0026#34;: interpolated_value, }, index=[indices[0]], ) interpolated_df_global_args = spark_df.groupBy(F.col(\u0026#34;category\u0026#34;), F.col(\u0026#34;year\u0026#34;)).applyInPandas( numpy_interpolate_global_args, schema=interpolated_schema ) Notice that the Pandas Function numpy_groupby_global_args has a specific signature. We can omit the first argument, and it will still work, but that\u0026rsquo;s about the extent of the flexibility. This is the required signature. So, to decide at what fraction of the year we want to interpolate at, we have used the global variable _INTERPOLATE_AT. This is\u0026hellip; ugly, but it gets the job done. For now.\nHowever, what if we got the argument from a file, or CLI args. In theory, we could still use global arguments, but it gets messy really quickly. And testing becomes hard as well. So what do we do?\nUse partial for arguments Let\u0026rsquo;s use partial from functools. We can use this to specialize the UDF for a particular input value and then use the new function as the argument for PySpark. Here\u0026rsquo;s what it looks like.\ndef numpy_interpolate_local_args(indices: Tuple[int, int], df: pd.DataFrame, interpolate_at: float) -\u0026gt; pd.DataFrame: interpolated_value = np.interp(interpolate_at, df[\u0026#34;x\u0026#34;], df[\u0026#34;y\u0026#34;]) return pd.DataFrame( data={ \u0026#34;category\u0026#34;: indices[0], \u0026#34;year\u0026#34;: indices[1], \u0026#34;interpolated_value\u0026#34;: interpolated_value, }, index=[indices[0]], ) numpy_groupby_interpolate_at = partial(numpy_interpolate_local_args, interpolate_at=_INTERPOLATE_AT) interpolated_df = spark_df.groupBy(F.col(\u0026#34;category\u0026#34;), F.col(\u0026#34;year\u0026#34;)).applyInPandas( numpy_groupby_interpolate_at, schema=interpolated_schema ) Neat, right? I like this pattern, but having partial can sometimes feel jarring as well as hacky.\nFinal thoughts So what are your thoughts. Do you think this is a nice pattern to pass arguments to a Pandas UDF. If you have a better pattern, I would be interested to know.\nCode The code is available here.\n","permalink":"https://vikramsg.github.io/blog_spark_args/","summary":"\u003cp\u003eIn our last \u003ca href=\"../blog_pandas_groupby_with_numpy/\"\u003ecouple\u003c/a\u003e of \u003ca href=\"../blog_numba_slower_than_pandas/\"\u003eposts\u003c/a\u003e\nwe looked at how we could optimize pandas functions.\nThis post will be different. We still want to address issues that we face in the PySpark world,\nbut today we will not look at performance at all.\u003c/p\u003e\n\u003ch2 id=\"parameters-in-a-pandas-udf\"\u003eParameters in a Pandas UDF\u003c/h2\u003e\n\u003cp\u003eIn PySpark, when we want to use a Pandas UDF, we actually have 2 options.\nWe can use the regular Pandas UDF, or we can use the \u003ca href=\"https://docs.databricks.com/pandas/pandas-function-apis.html\"\u003ePandas Function API\u003c/a\u003e.\nWhile both of them address the UDF question, the actual function implemented still operates on a Pandas DataFrame,\nso that simplifies what we want to address in this post.\u003c/p\u003e","title":"Using arguments in a Pandas UDF for PySpark"},{"content":"In our last post we saw that we can get much more performance by rewriting Pandas GroupBy - Apply in NumPy. I also mentioned that I could not get Numba working with this code to see if it helps. In this blog, I want to talk about how I got Numba working and what the results were, but first, what\u0026rsquo;s Numba?\nNumba Numba is a just-in-time (JIT) compiler for Python that specializes in optimizing the performance of numerical computations. Well, that\u0026rsquo;s all well and good, but what is a JIT compiler? Most people are aware of compiled languages like C++, Rust or Java. For these languages, the development flow is to write code, then compile the code to a binary and then run the binary. But for an interpreted language like Python, the second step is missing. Python is dynamic so the type of variables can be anything. This often means that Python functions spend a lot of time checking variable attributes to then do the correct function call on them. The final function call usually involves a C function call which is fast, but the overhead of type checking and edge cases are huge.\nCompiled languages are typed and so no type checking is necessary. Compilers can use this and other knowledge to create optimized binaries. The question then arises: how can we leverage compilers for Python code? JIT is one way to solve this issue. While the code is running, Numba analyzes variables and code flow to create optimized functions. This also means that the first function call can be slow and therefore JIT is not recommended for code with low runtimes. On the other hand if your code spends a long time on certain functions, then it can be very worthwhile. There are ways around this but we will keep that out of scope of this post.\nBack to Numba. It is a JIT compiler for Python, especially for numeric applications. The simplest way to use it is to use a decorator around your function. For eg.\nfrom numba import njit @njit def plus_one(a): return a+1 And that\u0026rsquo;s it. In theory this should make the function much faster. But the important part is \u0026ldquo;in theory\u0026rdquo;.\nCustomizations So let\u0026rsquo;s get back to our problem. We were trying to speed up the Pandas GroupBy-Apply with NumPy. And we did manage to make it much faster. But what if we could make it even faster. Well, how about using Numba. Almost immediately, we hit a wall. We want to use the njit decorator around functions that have NumPy API calls. And the issue is that Numba does not support all NumPy functions. And amongst the unsupported ones is lexsort that we are using. We are stuck. Or are we? Turns out others have asked the same question. And some have answered. So, we use this version of lexsort.\nBut then we hit another wall. apply_along_axis is also not supported. But this is simpler to solve. This is just an optimized for loop, so let\u0026rsquo;s just create a for loop and hopefully Numba should take care of speedup.\ninterpolate_values = np.zeros(reshape_x_size) for i in range(reshape_x_size): interpolate_values[i] = np.interp( x=_INTERPOLATE_AT, xp=x_unique_values, fp=y_values[i, :] ) Benchmarking And that\u0026rsquo;s it(I make it sound simple even though I had to spend quite some time finding and fixing issues). We now have a function decorated with njit and we are ready to reap the rewards. So, as always, we benchmark. Recall that we use timeit for this. What do we get?\nPandas times: [0.35364490200000004, 0.33443024, 0.3303176189999999, 0.32855506999999995, 0.33024766799999994] Numpy times: [0.0469579229999999, 0.036730967, 0.03578966599999989, 0.035751120000000025, 0.03562025000000002] Numba with NumPy times: [4.562287851, 0.6207038340000004, 0.6222665610000009, 0.584906624, 0.5903799620000001] Which is\u0026hellip; pretty bad. You can see that the first function call is pretty slow and that is expected. It should become much faster in subsequent function calls to recoup that loss. But actually, its so much slower. In fact, it is slower than the Pandas time!\nFinal thoughts I am sure that there are optimizations that could be tried. But Numba itself was pretty finicky and it was so slow that I did not want to delve deeper. Still, I think it was an interesting exercise. I had the chance to look at Numba, and believe me sometimes it can really be way faster. However, know that this is not guaranteed and so, always Benchmark!\nCode The code is available here.\n","permalink":"https://vikramsg.github.io/blog_numba_slower_than_pandas/","summary":"\u003cp\u003eIn our last \u003ca href=\"../blog_pandas_groupby_with_numpy/\"\u003epost\u003c/a\u003e we saw that we can get much\nmore performance by rewriting Pandas GroupBy - Apply in NumPy.\nI also mentioned that I could not get Numba working with this code to see if it helps.\nIn this blog, I want to talk about how I got Numba working and what the results were,\nbut first, what\u0026rsquo;s Numba?\u003c/p\u003e\n\u003ch2 id=\"numba\"\u003eNumba\u003c/h2\u003e\n\u003cp\u003eNumba is a just-in-time (JIT) compiler for Python\nthat specializes in optimizing the performance of numerical computations.\nWell, that\u0026rsquo;s all well and good, but what is a JIT compiler?\nMost people are aware of compiled languages like C++, Rust or Java.\nFor these languages, the development flow is to write code,\nthen compile the code to a binary and then run the binary.\nBut for an interpreted language like Python, the second step is missing.\nPython is dynamic so the type of variables can be anything.\nThis often means that Python functions spend a lot of time\nchecking variable attributes to then do the correct function call on them.\nThe final function call usually involves a C function call which is fast,\nbut the overhead of type checking and edge cases are huge.\u003c/p\u003e","title":"Sometimes Numba can be slower than even Pandas... or why you should always benchmark"},{"content":"If you use PySpark a lot you would know that the DataFrame API is great. However there are times when it is not sufficient because it does not cover every single piece of functionality we may want. This is where the Pandas UDF functionality comes in. The nice thing about the Pandas UDF functionality is that it uses Arrow for data transfer between Spark and Pandas which minimizes serialization-deserialization costs. I have a slight preference for Pandas Function API over Pandas UDF but now let\u0026rsquo;s get to the meat of the post which is about speeding up the Pandas GroupBy-Apply pattern by using NumPy instead.\nSetup data Let\u0026rsquo;s first start with example data to explain what we are doing. We construct an artificial dataset that has 4 columns, category, year, x, y. We will select 3 categories for category, namely [\u0026quot;red\u0026quot;, \u0026quot;green\u0026quot;, \u0026quot;blue\u0026quot;]. We have years representing every year from 2010 to 2020. The x column always have the same values for each category and year, 0, 0.1, 0.25, 0.5, 1 and the y values monotonically increase with the x values. If you, like me, struggle to make sense of artificial data, let\u0026rsquo;s assume this data represents the sales of 3 categories of balls for each year. The y value is the total sales after x fraction of the year is finished.\n_CATEGORIES = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] _YEARS = range(2010, 2021) _X_VALUES = [0, 0.1, 0.25, 0.5, 1.0] def create_dataframe() -\u0026gt; pd.DataFrame: data = [] for category in _CATEGORIES: for year in _YEARS: for x in _X_VALUES: y = 25.0 * x + random.uniform(0, 1) data.append([category, year, x, y]) return pd.DataFrame(data, columns=[\u0026#34;category\u0026#34;, \u0026#34;year\u0026#34;, \u0026#34;x\u0026#34;, \u0026#34;y\u0026#34;]) Pandas GroupBy So, what do we want to do? Let\u0026rsquo;s assume that we want to find out what the sales for at 30% of each year and category. How do we do that? Since we already spoiled this in the title, let\u0026rsquo;s get to it. We can do a GroupBy-Apply for this.\ndef pandas_groupby(df: pd.DataFrame) -\u0026gt; pd.DataFrame: return ( df.groupby([\u0026#34;category\u0026#34;, \u0026#34;year\u0026#34;]) .apply(lambda df: np.interp(0.3, df[\u0026#34;x\u0026#34;], df[\u0026#34;y\u0026#34;])) .rename(\u0026#34;y\u0026#34;) .reset_index() ) That\u0026rsquo;s pretty easy, right? It does what we want, although Pandas does weird stuff when you do GroupBy. It creates a multi-index with the columns that were used for the GroupBy. So, for example, if we were to use this UDF for PySpark, we would waste processing time resetting the index. But that\u0026rsquo;s Pandas.\nNumPy How would we do this in NumPy? There is no GroupBy in NumPy. There\u0026rsquo;s a very old NEP that proposed this, but obviously it was not implemented. So, how would we do this? Essentially what we need to do is group indices for category and year first. NumPy has a nice way of doing this with lexsort.\nsort_indices = np.lexsort((x_values, years, categories)) This will first sort by categories, then years, then x_values. We also sort by x_values since we need this for the next step. Then what we do is reshape the 1D array to a 2D array. So basically, for each category and year we have a column of y_values. And then we use apply_along_axis, since we don\u0026rsquo;t want to use a Pandas apply. A Pandas apply is essentially a Python for loop which is slow! So, we use the NumPy vectorized version.\ndef _interpolate_wrapper(fp: np.ndarray, xp: np.ndarray, x: float) -\u0026gt; float: return float(np.interp(x=x, xp=xp, fp=fp)) def numpy_groupby(df: pd.DataFrame) -\u0026gt; pd.DataFrame: .... .... y_values = y_values.reshape([-1, num_x_unique_values]) interpolated_y_values = np.apply_along_axis( _interpolate_wrapper, axis=1, arr=y_values, x=_INTERPOLATE_AT, xp=x_unique_values, ) Why did we have to create a new function _interpolate_wrapper? Well, that is because apply_along_axis wants to use the first argument of the function being passed, even though we are specializing that in the function arguments. So, we had to create a wrapper to make y_values be the first argument. We can of course use different functions, if that is what we wanted to do. So that\u0026rsquo;s it. We have implemented the same functionality. But why do this? This brings us to\u0026hellip;. benchmarking.\nBenchmarking We use timeit to compare the times of the 2 different ways of doing our interpolation.\nif __name__ == \u0026#34;__main__\u0026#34;: numpy_times = timeit.repeat( \u0026#34;numpy_groupby(df)\u0026#34;, \u0026#34;from __main__ import create_dataframe, numpy_groupby;df = create_dataframe();\u0026#34;, number=100, ) print(f\u0026#34;Numpy times: {numpy_times}\u0026#34;) pandas_times = timeit.repeat( \u0026#34;pandas_groupby(df)\u0026#34;, \u0026#34;from __main__ import create_dataframe, pandas_groupby;df = create_dataframe()\u0026#34;, number=100, ) print(f\u0026#34;Pandas times: {pandas_times}\u0026#34;) This will run the 2 functions a 100 times, and repeat it 5 times which is the default value for repeat. The output will be then a list of 5 numbers for each of the 2 function calls. Each of the 5 numbers represent the time for one of the 5 runs. I am running this on a 2019 MacBook with an i9 Intel processor.\nAnd here are the results.\nNumpy times: [0.039644957000000036, 0.03817060300000008, 0.037790082, 0.037306608000000074, 0.03735358100000008] Pandas times: [0.36932151, 0.36356516000000005, 0.358974868, 0.3752171339999999, 0.36828465099999974] Well, clearly we can see almost an order of magnitude(10X) improvement in performance. That is A LOT. And as our data becomes bigger and bigger in size, this can be the difference between having a $500 vs a $5000 job. Or $5000 vs $50000. Or\u0026hellip;. you get the point.\nClosing thoughts So, is the conclusion that we need to write everything in NumPy. Well, it\u0026rsquo;s complicated. But here are the steps that I would go through to decide what to do.\nDon\u0026rsquo;t write a UDF. Don\u0026rsquo;t do it! If you have to write a UDF, use a Pandas UDF. Use Pandas API. Don\u0026rsquo;t use NumPy. But if costs start becoming a concern, use NumPy. Benchmark your UDF. Then benchmark some more. I would also have liked to have a look at whether we could speed up the NumPy code even more with Numba. Unfortunately Numba does not support lexsort. But all in all, I am happy with the performance while keeping the code fairly simple.\nCode The code is available here.\n","permalink":"https://vikramsg.github.io/blog_pandas_groupby_with_numpy/","summary":"\u003cp\u003eIf you use PySpark a lot you would know that the DataFrame API is great.\nHowever there are times when it is not sufficient\nbecause it does not cover every single piece of functionality we may want.\nThis is where the \u003ca href=\"https://spark.apache.org/docs/3.1.2/api/python/user_guide/arrow_pandas.html\"\u003ePandas UDF\u003c/a\u003e functionality comes in.\nThe nice thing about the Pandas UDF functionality is that it uses Arrow for data transfer\nbetween Spark and Pandas which minimizes serialization-deserialization costs.\nI have a slight preference for Pandas Function API over Pandas UDF\nbut now let\u0026rsquo;s get to the meat of the post which is about speeding up\nthe Pandas GroupBy-Apply pattern by using NumPy instead.\u003c/p\u003e","title":"Using NumPy to replace Pandas GroupBy-Apply pattern for performance"},{"content":"There are many differen ways to do machine learning. The most popular methods use neural networks. We are usually given some data and we train the neural network to fit this data. In this post I will review an interesting way to look at this problem that converts the training problem to an ordinary differential equation. We will look at a property of this ODE that indicates a possible way to optimize the training process.\nThe training of machine learning models require optimizing an objective function. For example, using Tensorflow, you could define a loss function in the following manner. This is simply least squares.\nimport keras.backend as K def loss(y_true,y_pred): return K.mean( K.square( y_pred - y_true) ) Then you select an optimization function such as ADAM and then wait for the learning to happen. But what is really happening when you do this. Well, most popular optimization functions are really stochastic gradient descent. Maybe I will talk of stochastic gradient descent in a future post, but right now I am more interested in discussing gradient descent and its connections to differential equations and conservation laws.\nLet us first look at how gradient descent works. First, define the parameters of the neural network, namely the weights and biases as the vector xxx, and the loss function, for example the one above, as VVV. What we want to do is find the minimum of this function VVV and we use gradient descent for this. Then gradient descent is simply\nxn+1=xn−γ∇V(xn). x^{n + 1} = x^{n} - \\gamma \\nabla V(x^n). xn+1=xn−γ∇V(xn). Here ∇V\\nabla V∇V is the gradient of VVV. This is an iterative algorithm that states how the parameters at step n+1n+1n+1 should be updated using parameters at step nnn and γ\\gammaγ is called learning rate for machine learning. The gradients in packages such as Tensorflow are done using automatic differentiation. The iterations in general go on until the loss function is sufficiently small. However, an interesting way to look at this algorithm is to think of Euler time stepping. You are given an equation\nx˙=−∇V(x). \\dot{x} = - \\nabla V(x). x˙=−∇V(x). Here x˙\\dot{x}x˙ is the time derivative of the parameters. This is called gradient flow. There\u0026rsquo;s an excellent blog post1 that goes into more detail. This is now simply an ordinary differential equation(ODE) although a very big one!\nBut once we realize it is an ODE there are some new ways to think of this problem. First, we realize that we are doing Euler time stepping and to people familiar with numerical methods that is usually a strict no-no. Its usually not stable and restricts you to using very small sized steps. Therefore, it is possible that gradient descent is not very efficient especially for large problems. Second, this suggests that we could come up with some kind of convergence proof for the algorithm. Of course then we have to start making assumptions about the function VVV but I guess having guarantees on how efficiently we can do learning for a machine learning problem would be a sort of Holy Grail. So this is a very active area of research. And third, we can start thinking about conservation laws that the ODE may satisfy and investigate whether the algorithm satisfies this law. The second and third point is interconnected but I have separated them because I want to talk more about this third point.\nIn computational fluid dynamics(CFD) which is what I work on, conservation laws are everywhere. In CFD, we want to conserve mass, momentum and energy, which is what the conservation laws tell you to do. However, when approximating the equations, we often don\u0026rsquo;t guarantee conservation resulting in bad results or the solver crashing. However, even if you do satisfy conservation, it turns out that the flow satisfies additional laws. For example, the compressible Navier Stokes satisfy entropy conservation and it turns out if you satisfy them in your approximation your solver becomes much more stable in general. My last post on wall models explored one such stability aspect. Similarly for gradient flows there\u0026rsquo;s a conservation law, or rather a stability law that is satisfied. To see this, we just multiply ∇V\\nabla V∇V to the ODE to get\n∇V⋅x˙=−(∇V)2. \\nabla V \\cdot \\dot{x} = - (\\nabla V)^2. ∇V⋅x˙=−(∇V)2. Now we simply use the chain rule dVdxdxdt=dVdt\\frac{dV}{dx}\\frac{dx}{dt} = \\frac{dV}{dt}dxdV​dtdx​=dtdV​ to get\nV˙=−(∇V)2. \\dot{V} = - (\\nabla V)^2. V˙=−(∇V)2. Notice that the right hand side is always negative, meaning that VVV will always decrease which is what we want since we want its minimum. But does gradient descent do this? We multiply ∇V(xn)\\nabla V(x^n)∇V(xn) with the gradient descent equation to get\n∇V(xn)xn+1−xnγ=−(∇V(xn))2. \\nabla V(x^n) \\frac{x^{n + 1} - x^{n}}{\\gamma} = - ( \\nabla V(x^n) )^2. ∇V(xn)γxn+1−xn​=−(∇V(xn))2. Notice that the left hand side is only an approximation for V˙\\dot{V}V˙. As γ\\gammaγ becomes bigger this approximation gets worse (using Taylor series) and so you cannot have large learning rates.\nOne way to solve this issue would be to define the gradient in a different way. This approach is called the discrete gradient approach and the earliest reference I found was a paper from the 70\u0026rsquo;s2. The first two authors of the paper are 2 giants of CFD and of course I should not have been surprised. Recent studies I have found usually explore applications in image3 regularization4. In this approach we define the gradient in the following manner.\n∇ˉV(x,y)(x−y)=V(x)−V(y). \\bar{\\nabla} V(x, y) (x - y)= V(x) - V(y). ∇ˉV(x,y)(x−y)=V(x)−V(y). Now, if we use this definition of the gradient, then our iterative algorithm will in fact satisfy the stability condition. Some people familiar with CFD will recognize that this condition looks very similar to the famous Tadmor shuffle condition 5. There also, we define a function such that we can satisfy a conservation law. However, there are 2 issues that makes this new definition difficult to use. First, we cannot use automatic differentiation anymore which could affect efficiency. And second, this then becomes an implicit equation. For example, gradient descent will look like the following\nxn+1=xn−γ∇ˉV(xn,xn+1). x^{n + 1} = x^{n} - \\gamma \\bar{\\nabla} V(x^n, x^{n+1}). xn+1=xn−γ∇ˉV(xn,xn+1). So, we have an implicit equation, which looks like implicit time stepping used in CFD. Obviously we don\u0026rsquo;t have something as simple as Euler time stepping, but here\u0026rsquo;s something that CFD tells us. If we do implicit time stepping, we can usually get away with much larger time steps. I suspect the same is true for this problem as well. So, if we come up with efficient ways to do the implicit time stepping, we can do training with a much larger learning rate. This would make it much more efficient.\nSo that is it. My aim with the post was to summarize some of the ideas in literature that allows people from the numerical analysis community to get familiar with the problem. I think this is an interesting direction to attack the problem and come up with solutions to make training more efficient. Don\u0026rsquo;t hesistate to contact me if you have any questions or suggestions.\nReferences https://francisbach.com/gradient-flows/\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nhttps://doi.org/10.1002/cpa.3160310205\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nhttps://doi.org/10.1088/1751-8121/aa747c\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nhttps://arxiv.org/pdf/1805.06444.pdf\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nhttps://doi.org/10.2307/2008251\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n","permalink":"https://vikramsg.github.io/blog_cons_laws_ml/","summary":"\u003cp\u003eThere are many differen ways to do machine learning.\nThe most popular methods use neural networks.\nWe are usually given some data and we train the neural network to\nfit this data.\nIn this post I will review an interesting way to look at this problem\nthat converts the training problem to an ordinary differential equation.\nWe will look at a property of this ODE that indicates a\npossible way to optimize the training process.\u003c/p\u003e","title":"Can we make machine learning more efficient using conservation laws?"},{"content":"The second paper from my PhD got published recently in Computers and Fluids. If you don\u0026rsquo;t have access, there\u0026rsquo;s a free version on ResearchGate and the preprint on Arxiv.\nThe idea of the paper was to look at wall models from an angle that is not usually looked at. Wall models are a popular way to reduce the cost of simulations. To see why let us first say something about accurate ways of solving for flow around walls, such as say the wing of an airplane. Direct numerical simulation(DNS) is the most accurate way to solve the Navier Stokes equations, but if we have a wall then the cost of simulations is crazy expensive. I think the Channel Flow test case, which is very idealized took 9 months to solve on a supercomputer for a realistic Reynolds\u0026rsquo; number. So usually people look at the next most accurate way of doing it, which is large eddy simulation(LES). However, the wall still poses a problem since the cost is still exponenetial. I recall a talk where people were using billions of grid points to just solve the flow around a car. And I don\u0026rsquo;t think they were even doing LES.\nHence wall models. The idea is to do LES away from the wall, and use a simple model near it. The grid need not be so refined then and so we can get away with doing simulations at much lower cost. However, stability is not usually something that is looked at when using wall models even though it is very important. Without stability, you submit a simulation overnight, hoping to see results in the morning and instead you come back to see that the solver stopped barely after starting.\nWe looked at kinetic energy 12ρu2\\frac{1}{2} \\rho u^221​ρu2(ρ\\rhoρ being density and uuu being velocity) to see the effects of the wall model on it. We proved that a simple relation at the wall decides the stability. Using this, we looked at a couple of wall models. It turns out that the algebraic wall model, which is very popular, is actually unstable. Which is surprising, not only because its so popular but because it often gives fairly accurate results. We created an idealized test case to demonstrate this issue on an airfoil. So next time you simulate flow around a wall, and start seeing robustness issues, maybe the wall model is the issue. On the other hand a recently developed slip wall model is actually stable, but is not accurate. So, we decided to test one that is a hybrid of the two. It worked fairly well but we need to push the accuracy forward.\nI am happy at how the paper turned out and am really thankful to Prof. Nordström for pushing us to investigate this direction as well as his detailed revisions of the manuscript and to Prof. Frankel for all his help. Have a look at the paper and if you have any questions or suggestions feel free to send me a message.\n","permalink":"https://vikramsg.github.io/blog_paper_wall_model/","summary":"\u003cp\u003eThe second paper from my PhD got published recently in\n\u003ca href=\"https://www.sciencedirect.com/science/article/abs/pii/S0045793021000360\"\u003eComputers and Fluids\u003c/a\u003e.\nIf you don\u0026rsquo;t have access, there\u0026rsquo;s a free version on\n\u003ca href=\"https://www.researchgate.net/publication/349396252_Impact_of_wall_modeling_on_kinetic_energy_stability_for_the_compressible_Navier-Stokes_equations\"\u003eResearchGate\u003c/a\u003e\nand the preprint on\n\u003ca href=\"https://arxiv.org/abs/2102.05080\"\u003eArxiv\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eThe idea of the paper was to look at wall models from an angle that\nis not usually looked at.\nWall models are a popular way to reduce the cost of simulations.\nTo see why let us first say something about accurate ways of solving\nfor flow around walls, such as say the wing of an airplane.\nDirect numerical simulation(DNS) is the most\naccurate way to solve the Navier Stokes equations,\nbut if we have a wall then the cost of simulations is crazy expensive.\nI think the Channel Flow test case, which is very idealized took\n9 months to solve on a supercomputer for a realistic Reynolds\u0026rsquo; number.\nSo usually people look at the next most accurate way of doing it,\nwhich is large eddy simulation(LES).\nHowever, the wall still poses a problem since the cost is\nstill exponenetial.\nI recall a talk where people were using billions of grid points\nto just solve the flow around a car. And I don\u0026rsquo;t think they were even doing LES.\u003c/p\u003e","title":"Are wall models stable?"},{"content":"Hello world!!\nI thought I will start of by posting on how I setup this blog. First I decided to use GitHub Pages since I already had a Github account and it sounded simple to set it up. Not simple at all as it turned out. While there are many posts around with headlines like setup your blog in 5 minutes, the reality is that it takes 5 minutes if you want to setup an exact replica of a pre-existing template. Figure out how to do even the most simple customizations can take quite some time. Let us begin then.\nFirst steps I decided to use Jekyll since that is what Github recommends. Now, Jekyll requires Ruby. A version of Ruby is already available on Mac. However, I had some issues, so I used Homebrew to install Ruby. If you don\u0026rsquo;t have Ruby, please install it for your platform. Next, create a directory where you will keep the website files and in the terminal do the following inside this directory.\ngem install bundler jekyll Now, we could use the steps listed at various steps such as here to use the default theme. But I decided to use the Minimal Mistakes theme which looked better. Download the repository to your folder and then inside the folder do\nbundle update And you are done! You can view your website by doing\nbundle exec jekyll serve and then putting the following in your browser.\nhttp://localhost:4000/ That took 5 minutes. So what\u0026rsquo;s the problem. Well, quite a few of them. But first, the easy part. Use the _config.yml to change things such as the name of the website, your social media links etc. Every time, you make a change, you can do the above steps to open it in the browser and check the results. Its exactly like compiling and running!\nCustomize The very first thing I wanted to do was figure out how to add a page for blog posts. To do this add a folder _pages in the home directory and inside this directory add a file called blog.md. Write the following inside this file\n--- title: \u0026#34;Blog\u0026#34; layout: archive permalink: /Blog/ author_profile: true --- Next edit the file _data/navigation.yml to look like this.\nmain: - title: \u0026#34;Blog\u0026#34; url: /Blog/ This completes the setup. To write posts, create a new folder _posts and add blog posts there. The file must be named like this.\nyyyy-mm-dd-name.md The top of the file must have\n--- layout: single title: \u0026#34;Name\u0026#34; date: yyyy-mm-dd --- and then start writing your post below. Note that if you name the files with .md extension, you are basically telling Jekyll that you are using Markdown. So we are done with setting up blogging. There\u0026rsquo;s a slight hitch though, although this is just a personal choice. With this setup Jekyll puts the posts on your home page. I did not want this. So I deleted the index.html page in the home directory and added an index.md file with the following lines.\n--- title: \u0026#39;About me\u0026#39; layout: single author_profile: true --- One more customization I decided to do was to add a newsletter sign-up form. To do this, I signed up at Mailchimp and created an embedded signup form. Mailchimp gave me the HTML for the form which I copy-pasted into a new file _data/signup.html. I also added the following line into _layouts/single.html.\n{# if page.signup == true #}{# include signup.html #}{# endif #}. Replace # with % in the above. Jekyll thinks I am trying to execute this from inside the blog post. I modified the defaults in _config.yml to add the signup line.\ndefaults: - scope: path: \u0026#34;\u0026#34; type: posts values: layout: single author_profile: true share: true related: true signup: true signup: true Finally, in _pages/blog.md I added the following in the header.\nsignup: true Phew!! And now we need to do the easiest part. Put it all online. Go to your GitHub account, and setup a new repository username.github.io. From the terminal do\ngit init git remote add origin git@github.com:\u0026lt;your_github_username\u0026gt;/\u0026lt;your_github_repo_name\u0026gt;.git git add * git commit -m \u0026#34;Setting up Jekyll\u0026#34; git push -u origin master And we are done. So that is how I setup my blog. Of course I continue to change things here and there. If you are interested, have a look at the files on my GitHub.\n","permalink":"https://vikramsg.github.io/blog_setup/","summary":"\u003cp\u003eHello world!!\u003c/p\u003e\n\u003cp\u003eI thought I will start of by posting on how I setup this blog.\nFirst I decided to use\n\u003ca href=\"https://pages.github.com/\"\u003eGitHub Pages\u003c/a\u003e\nsince I already had a Github account and it sounded simple to set it up.\nNot simple at all as it turned out.\nWhile there are many posts around with headlines like\nsetup your blog in 5 minutes, the reality is that\nit takes 5 minutes if you want to setup an exact replica of a pre-existing template.\nFigure out how to do even the most simple customizations can take quite some time.\nLet us begin then.\u003c/p\u003e","title":"Setting up the blog"},{"content":"I am a Senior Data Engineer working at Orbio helping make methane predictions more accurate. Previously I was a Software Engineer at Cervest working to bring ML models to life that predict physical risk to customer assets due to climate change.\nIn a past life, I spent a few years in academia working on various computational physics problems. I was a PostDoc at the Max Planck Institute for Meteorology where I worked on the ocean model ICON-O. Keeping climate models stable is a complex problem and requires careful analysis of the numerical method. I worked on improving the structure preserving numerics of ICON-O to push the model towards more flexibility and stability.\nI did my PhD at Technion, Israel. I worked on the Discontinuous Galerkin (DG) method, an arbitrary high-order, unstructured method for the solving the compressible Navier Stokes (CNS) equation. I wrote the solver in C++ making extensive use of the MFEM library. I developed the techniques required to make the solver robust and efficient.\n","permalink":"https://vikramsg.github.io/about/","summary":"\u003cp\u003eI am a Senior Data Engineer working at \u003ca href=\"https://www.orbio.earth/\"\u003eOrbio\u003c/a\u003e\nhelping make methane predictions more accurate.\nPreviously I was a Software Engineer at Cervest working to bring\nML models to life that predict physical risk to customer assets due to climate change.\u003c/p\u003e\n\u003cp\u003eIn a past life, I spent a few years in academia working on various computational physics problems.\nI was a PostDoc at the Max Planck Institute for Meteorology where I worked on the ocean model ICON-O.\nKeeping climate models stable is a complex problem and\nrequires careful analysis of the numerical method.\nI worked on improving the structure preserving numerics of ICON-O\nto push the model towards more flexibility and stability.\u003c/p\u003e","title":"About me"},{"content":"Experience Orbio Senior Software Engineer\nDecember 2023 – Present\nProductionize machine learning models in collaboration with Data Scientists but on Gitlab instead of Github this time! Implemented ELT/ETL data pipelines to predict methane emissions but on Airflow this time! Mentor Engineers and Scientist to improve code quality and ways of working. Cervest Software Engineer\nJan 2022 – June 2023\nProductionized machine learning models in collaboration with Data Scientists by creating Python libraries and introducing reusable CI/CD workflows using GitHub Actions. Implemented ELT/ETL data pipelines using Argo workflows on Kubernetes (AWS EKS) to accelerate data validation times from 40 hours to 1 hour. Lead the migration of data pipelines for processing multiple TB\u0026rsquo;s of data to Databricks which uses PySpark\u0026rsquo;s distributed capabilities. Optimized PySpark Pandas UDF using NumPy to reduce costs by 20 times. Contributed to FastAPI based library for delivering data within a Service Oriented Architecture(SOA) framework. Created Hyperparameter optimization for statistical models, reducing workflow time by 10x. Helped promote best practices by upskilling others using pair programming, proposing improvements in ways of working and collaborating on code guidelines. Contributed to the open source AWS SDK for Pandas. Max Planck Institute for Meteorology Scientific Programmer\nJul 2019 – Dec 2021\nDeveloped new mathematical model for the in-house climate model that delivered increased precision and accuracy. Built Python based ETL pipelines for visualization of large climate geospatial data output from climate model simulations. Co-ordinated projects with multiple researchers in multiple countries resulting in new publications. Aeronautical Development Agency Engineer\nAug 2009 – Oct 2015\nDeveloped a Python-based Hyperparameter Tuning framework for aerodynamic design, resulting in new configuration design delivery time reducing from 5 days to 10 hours. Utilized Genetic Algorithms for optimized configuration derivation and achieved significant results that earned me the DRDO Young Scientist Award. Education Technion PhD in Mechanical Engineering\nOct 2015 – Jul 2019\nI worked on the Discontinuous Galerkin (DG) method, an arbitrary high-order, unstructured method for the solving the compressible Navier Stokes (CNS) equation. High order methods suffer from aliasing instabilities which leads to robustness issues. I showed that we can solve this issue if we used split forms. In addition, split forms work well with wall modeling to enable high Reynolds\u0026rsquo; number flows.\nIIT Kanpur BTech-MTech in Aerospace Engineering\nAug 2004 – May 2009\nI worked on airfoil design to optimize for bypass transition. I developed a FORTRAN code for design using B-splines and introduced a new technique to optimize airfoil flow characteristics.\n","permalink":"https://vikramsg.github.io/CV/","summary":"\u003ch2 id=\"experience\"\u003eExperience\u003c/h2\u003e\n\u003ch3 id=\"orbio\"\u003eOrbio\u003c/h3\u003e\n\u003cp\u003eSenior Software Engineer\u003cbr/\u003e\n\u003cem\u003eDecember 2023 – Present\u003c/em\u003e\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eProductionize machine learning models in collaboration with Data Scientists but on Gitlab instead of Github this time!\u003c/li\u003e\n\u003cli\u003eImplemented ELT/ETL data pipelines to predict methane emissions but on Airflow this time!\u003c/li\u003e\n\u003cli\u003eMentor Engineers and Scientist to improve code quality and ways of working.\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"cervest\"\u003eCervest\u003c/h3\u003e\n\u003cp\u003eSoftware Engineer\u003cbr/\u003e\n\u003cem\u003eJan 2022 – June 2023\u003c/em\u003e\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eProductionized machine learning models in collaboration with Data Scientists by creating Python libraries and introducing reusable CI/CD workflows using GitHub Actions.\u003c/li\u003e\n\u003cli\u003eImplemented ELT/ETL data pipelines using Argo workflows on Kubernetes (AWS EKS) to accelerate data validation times from 40 hours to 1 hour.\u003c/li\u003e\n\u003cli\u003eLead the migration of data pipelines for processing multiple TB\u0026rsquo;s of data to Databricks which uses PySpark\u0026rsquo;s distributed capabilities.\u003c/li\u003e\n\u003cli\u003eOptimized PySpark Pandas UDF using NumPy to reduce costs by 20 times.\u003c/li\u003e\n\u003cli\u003eContributed to FastAPI based library for delivering data within a Service Oriented Architecture(SOA) framework.\u003c/li\u003e\n\u003cli\u003eCreated Hyperparameter optimization for statistical models, reducing workflow time by 10x.\u003c/li\u003e\n\u003cli\u003eHelped promote best practices by upskilling others using pair programming, proposing improvements in ways of working and collaborating on code guidelines.\u003c/li\u003e\n\u003cli\u003eContributed to the open source AWS SDK for Pandas.\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"max-planck-institute-for-meteorology\"\u003eMax Planck Institute for Meteorology\u003c/h3\u003e\n\u003cp\u003eScientific Programmer\u003cbr/\u003e\n\u003cem\u003eJul 2019 – Dec 2021\u003c/em\u003e\u003c/p\u003e","title":"Curriculum Vitae"}]