<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Murphy Crosby on Medium]]></title>
        <description><![CDATA[Stories by Murphy Crosby on Medium]]></description>
        <link>https://medium.com/@murphy.crosby?source=rss-96c8f15537d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m6yl4DRSfUsP_Y3lLOk_Sg.jpeg</url>
            <title>Stories by Murphy Crosby on Medium</title>
            <link>https://medium.com/@murphy.crosby?source=rss-96c8f15537d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:18:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@murphy.crosby/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JIT Agents: Real-Time Decisions for Real-Time Systems]]></title>
            <link>https://medium.com/@murphy.crosby/jit-agents-959611aa74e4?source=rss-96c8f15537d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/959611aa74e4</guid>
            <category><![CDATA[jevs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[realtime]]></category>
            <dc:creator><![CDATA[Murphy Crosby]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 13:24:07 GMT</pubDate>
            <atom:updated>2026-09-30T18:39:05.312Z</atom:updated>
            <content:encoded><![CDATA[<h4>The model writes the rule. The stream never stops.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzobXE8uAtaau6drsOLSnA.png" /></figure><p>A customer tells your support agent:</p><blockquote>&gt; “If a shipment from Dallas is more than two hours late, text Murphy.”</blockquote><p>That is a simple request. The usual way to honor it is to have the model interpret it and save it somewhere: a prompt, a memory file, a block of markdown. Then every incoming shipment event goes to a language model, along with that saved text and a list of tools.</p><p>It works. It is also the wrong shape for a real-time system.</p><p>I measured it on an M1 Max with 32 GB of memory, running a local 27B model through Ollama, over 20 events.</p><ul><li>With the model’s default settings, deciding what to do with one event took a median of <strong>10.5 seconds</strong>. Most of that was the model reasoning before it answered.</li><li>With reasoning switched off and the model already loaded, the median dropped to <strong>0.8 seconds</strong>. That is the best case.</li><li>The first call after loading the model took 27 seconds.</li></ul><p>A hosted model on faster hardware will beat my laptop. It will not get anywhere near what a stream needs. A stream that sees a few thousand events a second cannot wait on a model, and it cannot pay for one either.</p><p>The rule itself is one `if` statement. So why is a model reading English on every event?</p><h3><strong>The idea</strong></h3><p>Use the model as the author, not the interpreter.</p><p>When the customer states what they want, an agent turns that into a small function. The function is tested, then injected into the running stream. From then on, every event for that customer runs through plain code. The model is involved once per rule, never once per event.</p><p>I call these <strong>JIT agents</strong>. The code is written just in time, when the customer speaks, and injected just in time, before the next event arrives.</p><p>Here is the function the agent wrote for the request above:</p><pre>def handle(event, tools):<br>    hours = event.hours_late if event.hours_late is not None else 0<br>    if event.warehouse == &quot;Dallas&quot; and hours &gt; 2.0:<br>        tools.notify_sms(<br>            to=&quot;Murphy&quot;,<br>            message=f&quot;Order {event.order_id} is {hours} hours late.&quot;,<br>        )</pre><p>Evaluating that rule takes a median of <strong>0.17 microseconds</strong>. A full dispatch, including the lookup of the customer’s rule and the policy checks around it, runs at about <strong>200,000 events per second on a single core</strong>. That is roughly 5 microseconds per event, against 0.8 seconds for the model at its best.</p><p>Python and JavaScript are the natural targets. Both can turn a string of source into a callable function while the process keeps running. No build, no deploy, no restart.</p><h3><strong>Why not have the model write a config file?</strong></h3><p>It’s the obvious alternative, and for simple cases it’s the right one. The model fills in a config, and fixed code reads it: a field, an operator, a value, an action.</p><p>It works until a customer asks for something you didn’t plan for. “More than 10% over the average of the last 10 invoices” needs a lookup, arithmetic, and a comparison between two computed values. Every request like that means a developer extends the config format and the code that reads it. Eventually the config has conditions, nesting, and expressions, and you’ve built a small programming language that you now have to maintain and teach to the model.</p><p>JIT agents start from the other end. The rule language is a deliberately small subset of Python: no loops, no imports, nothing beyond the tools you provide. In that sense it is a config. But the model already knows the language, and the parser and interpreter already exist.</p><p>The testing described below would be just as valuable with a config file. What generated code adds is room for the requests nobody anticipated.</p><h3><strong>The library</strong></h3><p>I built this as a small Python library. The whole idea fits in five verbs: register, propose, build, inject, and dispatch.</p><pre>from typing import Literal<br>from pydantic import BaseModel<br>from jit_agents import Runtime, Ollama, SqliteStore<br><br>class ShipmentEvent(BaseModel):<br>    customer_id: str<br>    order_id: str<br>    warehouse: Literal[&quot;Dallas&quot;, &quot;Austin&quot;, &quot;Denver&quot;]<br>    hours_late: float = 0<br><br>rt = Runtime(<br>    model=Ollama(&quot;qwen3.8:27b-mlx&quot;),<br>    store=SqliteStore(&quot;rules.db&quot;),<br>    key=lambda event: event.customer_id,<br>)<br>rt.register_event(ShipmentEvent)<br><br>@rt.tool<br>def notify_sms(to: str, message: str) -&gt; None:<br>    &quot;&quot;&quot;Send an SMS.&quot;&quot;&quot;<br>    ...<br><br># Conversation time: the model is involved<br>proposal = await rt.propose(<br>    &quot;acme&quot;, &quot;Text Murphy if a Dallas shipment is over 2 hours late&quot;<br>)<br>rule = await rt.build(proposal)<br>rt.inject(rule)<br><br># Stream time: no model involved<br>rt.dispatch(event)</pre><p><strong>Register</strong> your events, tools, and policy. <strong>Propose</strong> turns intent into tests. <strong>Build</strong> writes the code. <strong>Inject</strong> makes it live. <strong>Dispatch</strong> runs it.</p><p>Each customer gets their own function. When an event arrives, the runtime looks up that customer’s rule and calls it. One customer’s code never sees another customer’s events.</p><p>The model is a plug-in. I’ve run it against Ollama locally, Claude, and Databricks, and anything that speaks the OpenAI API format works.</p><h3><strong>The customer confirms behavior, not code</strong></h3><p>Customers cannot review Python, and they should not have to. So the agent does not start by writing code. It starts by writing tests, in plain terms:</p><ul><li>A Dallas shipment 2.5 hours late sends one SMS to Murphy.</li><li>A Dallas shipment exactly 2 hours late does nothing.</li><li>An Austin shipment 3 hours late does nothing.</li></ul><p>The customer reads those and says yes or no. Only then does the agent write a function, and the function has to reproduce those results exactly.</p><h3><strong>The playfield</strong></h3><p>Injecting model-written code into a live process sounds alarming, and it should. Three things keep it contained.</p><p><strong>The tools are the whole world.</strong> A rule receives an event and a `<em>tools</em>` object. It has no imports and no access to anything else. This is the same idea as tool calling in an LLM, applied to generated code.</p><p><strong>The language is tiny.</strong> Before anything runs, the source is parsed and every node in its syntax tree is checked against an allowlist. No imports, no loops, no `<em>try</em>`, no lambdas, no names that start with an underscore. Field access is checked against the Pydantic model, so a misspelled field is rejected before the code ever executes. With no loops and no function definitions, every rule finishes in time proportional to its length.</p><p><strong>Rules never execute tools.</strong> A rule calls `<em>tools.notify_sms(…)</em>` on a recording object. The runtime collects the calls and executes them afterwards. That makes each rule a pure function from an event to a list of actions, and it means the code path tested in the gate is the same one that runs in production.</p><h3><strong>The gate</strong></h3><p>Nothing is injected until it passes three layers.</p><ol><li><strong>Behavior tests.</strong> The cases the customer confirmed.</li><li><strong>Built-in checks.</strong> The rule must never raise, must give the same answer twice, must pass valid arguments, and must stay inside a latency budget.</li><li><strong>Invariants.</strong> Policy you write once, such as “never send more than one SMS per event.” No customer rule can break it, whatever the customer asked for.</li></ol><p>The second and third layers run on more than the confirmed tests. The library generates extra events from the Pydantic model: every allowed value of each field, empty optionals, and numbers just below, at, and just above each constant in the rule. The rule above was checked against 233 events before it went live.</p><p>If a rule fails, the failure goes back to the model and it tries again.</p><h3><strong>Three times the gate earned its keep</strong></h3><p><strong>The floating point boundary.</strong> I asked for a rule that flags any invoice more than 10% over a running average. The model wrote code that looked correct, and the gate rejected it:</p><pre>100 * 1.1 = 110.00000000000001<br>110 &gt; 110.00000000000001 False<br>110 &gt;= 110.00000000000001 False</pre><p>An invoice of exactly 110 against an average of 100 could never trigger that rule, with either comparison. I read the code and thought the gate was wrong. It was not. The fix was to round the threshold before comparing, and the generator now does that.</p><p><strong>The model contradicted itself.</strong> On another run, the agent proposed two tests with the same amounts and opposite expected results. No function can satisfy both. The gate refused four attempts in a row and nothing was injected. The library now handles this case by sending the gate’s feedback back to the agent so it can correct its own tests.</p><p><strong>The tests are the contract.</strong> A model on Databricks wrote a rule that rounded the delay to a whole number, so a shipment 2.5 hours late produced a text saying 2 hours. The gate passed it. Every confirmed test had used whole hours, so nothing asked the question. The fix was in the proposal step: when an event has a decimal field, at least one test must now use a fractional value. The gate can only enforce what the tests ask.</p><p>The first two are the argument for this design. The model made a mistake each time, and each time it was caught before it reached a live event. The third is the design’s limit, and it’s why the customer confirms the tests.</p><h3><strong>Surviving restarts</strong></h3><p>A loaded function cannot be saved. Its source can.</p><p>Each rule is stored under an ID with its source, its tests, and the customer’s original words. On restart nothing loads up front. The first event for a customer pulls that customer’s rule from the store.</p><p>Each rule also records a fingerprint of the events, tools, and invariants it was built against. If those have not changed, the rule loads directly. If they have, the gate runs again. A rule that no longer passes is marked stale and is not injected.</p><p>Because the original intent is stored, a stale rule can be regenerated without going back to the customer.</p><h3><strong>When a rule needs data</strong></h3><p>Some rules need more than the event. “Flag any Globex invoice more than 10% over the average of the last 10” needs history.</p><p>For that the library has lookups: read-only functions that return a value.</p><pre>@rt.lookup<br>def average_invoice_amount(<br>    customer_id: str, vendor: str | None = None, last: int = 10<br>) -&gt; float | None:<br>    &quot;&quot;&quot;Average amount of this customer&#39;s most recent invoices.&quot;&quot;&quot;<br>    ...  # a database query</pre><p>In the gate, lookups never run. Each test states what the lookup returns, and the gate varies those values, including an empty history.</p><p>Lookups also changed my numbers. A rule with no lookup evaluates in about a microsecond. The same rule with a SQLite query behind it took between 140 and 270 microseconds. That is still thousands of times faster than a model call, but the rule is no longer the bottleneck. The data access is.</p><h3><strong>What about decision models?</strong></h3><p>In September 2026 TypeSafe AI released Jev, which it describes as a “System One” model. It does not generate text. It returns typed values with confidence scores. The company reports response times of 70 to 500 milliseconds and says that is 40 to 200 times faster than frontier LLMs. Those are the company’s figures, and I have not tested them.</p><p>Jev attacks the same problem from the other side. It keeps a model in the loop and makes the model smaller and faster. JIT agents remove the model from the loop.</p><p>I do not think these compete. They split the work by the kind of decision.</p><ul><li><strong>Rule-shaped intent</strong> gets generated code. “Over $500,” “from Dallas,” “more than two hours.” It is faster by orders of magnitude, it gives the same answer every time, and you can read it when something goes wrong.</li><li><strong>Judgment-shaped intent</strong> needs a model. “Does this ticket sound angry?” does not reduce to an `<em>if</em>` statement. Code generated for it would be brittle keyword matching.</li></ul><p>The design I would reach for uses both. Generated code handles everything it can express, and calls a fast decision model as one of its tools for the rare fuzzy judgment.</p><h3><strong>What this does not do</strong></h3><ul><li><strong>It is not a sandbox.</strong> Rules run inside your process. The validator and the gate are the containment. For hostile users, run dispatch in a worker with memory limits.</li><li><strong>Your tools are the trust boundary.</strong> A rule can call any tool you register. The library cannot protect you from registering a dangerous one.</li><li><strong>A wrong rule that passes its tests runs wrong at full speed.</strong> Correctness depends on the tests. This is why the customer confirms them.</li><li><strong>One rule per key.</strong> The key can be a customer, or a customer and an event type. Several rules for the same key, with ordering and conflict detection, are not supported yet.</li><li><strong>It is a prototype.</strong> It has a test suite and no security review.</li></ul><p>To be fair to the model, it was not wrong. I ran the same 20 events through both approaches, and the model chose the same action as the generated code every time. The problem is everything else. It’s slow, it costs money on every event, and nothing guarantees it will give the same answer tomorrow.</p><h3><strong>Try it</strong></h3><p>The code is on GitHub under the Apache 2.0 license: <a href="https://github.com/murphycrosby/jit-agents">https://github.com/murphycrosby/jit-agents</a></p><p>You’ll need uv and a model that supports structured output. Ollama running locally is the default. Claude, Databricks, Azure Foundry, and other hosts that speak the OpenAI format work too. The repo’s examples/providers.py lists the variables each one needs.</p><pre>git clone https://github.com/murphycrosby/jit-agents.git<br>cd jit-agents<br>uv sync --all-extras<br>uv run python examples/quickstart.py</pre><p>There is also a small example site. Type a rule into a text box and watch it get written, tested, and swapped into a running stream while events keep flowing.</p><pre>uv run --extra example examples/webapp/app.py</pre><p>Then open <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> and pick a model from the header.</p><p>If you take one thing from this: the model is a good author and an expensive interpreter. Let it write the rule once, make it prove the rule works, and then let plain code do the job.</p><p><em>All numbers were measured on an M1 Max with 32 GB of memory and the qwen3.8 27B model running through Ollama. Model timings come from Ollama’s own reported durations. Yours will differ. Building a rule took from about 20 seconds to over a minute with the local model, which is fine for something that happens once per rule.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959611aa74e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Scalable Intelligence: Turbocharge Model Inference with Pandas UDFs]]></title>
            <link>https://medium.com/@murphy.crosby/unlocking-scalable-intelligence-turbocharge-model-inference-with-pandas-udfs-32f0b8d1f8bc?source=rss-96c8f15537d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/32f0b8d1f8bc</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[pandasudf]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Murphy Crosby]]></dc:creator>
            <pubDate>Thu, 16 May 2024 15:34:54 GMT</pubDate>
            <atom:updated>2024-05-16T15:34:54.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever had millions of rows in a Spark dataframe, a custom model in mlFlow, and the need to predict on multiple columns? Then prepare to have your socks knocked off. 🧦</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3LjNGbK2adhuR3lHbfaNVQ.png" /></figure><p>That might be a little much, but hopefully this is enlightening and enjoyable in some way. 😁</p><p>Now to start, there are probably many different ways to solve this problem, but I’m just going to show one way that worked for me. If you have a different way, send me a link to your Medium article!</p><h4>Problem:</h4><p>As stated above, I had over a million candidates records in a Spark dataframe that I needed to encode for a Job/Candidate recommendation system. The model is a Tensorflow/Keras model registered and hosted in mlFlow (i.e. Databricks). The model takes 8 features, 3 of which are categorical, and 5 that are numerical.</p><h4>Solution(s):</h4><p>The first time I did this, I exported the Spark dataframe to a pandas dataframe, and did inference on the pandas dataframe. This is problematic because just converting to a pandas dataframe can be time consuming and you have to have enough memory to host all of the records on the Spark Driver. This isn’t a scalable solution.</p><p>Ok…off to the internet to find a better way. In their documentation <a href="https://docs.databricks.com/en/machine-learning/model-inference/resnet-model-inference-keras.html">Model inference using TensorFlow Keras API</a>, Databricks laid the foundation to help solve my problem.</p><p>Dunzo, right? Eh, not quite. Their example was loading the Resnet50 model from an import, and only passing 1 column, which is an image (i.e. an array of floats). My model is a custom Tensorflow/Keras model living in mlFlow, and needs 8 columns. No big, let’s get to work.</p><p>First, let’s register the Pandas UDF.</p><p>*Note: Column names have been obfuscated so my employer doesn’t get mad 😆. They’re also not important to grasp the technical understanding.</p><pre>@pandas_udf(ArrayType(FloatType()), PandasUDFType.SCALAR_ITER)<br>def generate_vectors_udf(<br>    row_batch_iter: Iterator[<br>        Tuple[pd.Series, pd.Series, pd.Series, pd.Series, pd.Series, pd.Series, pd.Series, pd.Series]<br>    ]<br>) -&gt; Iterator[pd.Series]:<br>    model = tf.keras.models.load_model(&quot;/dbfs/models/JobEncoderModel/Production/model&quot;)<br>    for num_column1, num_column2, num_column3, num_column4, num_column5, cat_column1, cat_column2, cat_column3 in row_batch_iter:<br>        num_column1.name = &quot;num_column1&quot;<br>        num_column2.name = &quot;num_column2&quot;<br>        num_column3.name = &quot;num_column3&quot;<br>        num_column4.name = &quot;num_column4&quot;<br>        num_column5.name = &quot;num_column5&quot;<br>        cat_column1.name = &quot;cat_column1&quot;<br>        cat_column2.name = &quot;cat_column2&quot;<br>        cat_column3.name = &quot;cat_column3&quot;<br><br>        pd_data = pd.concat([cat_column3, cat_column1, cat_column2, num_column1, num_column2, num_column3, num_column4, num_column5], axis=1)<br>        data = {<br>            &quot;categorical&quot;: pd_data[[<br>                &quot;cat_column1&quot;, &quot;cat_column2&quot;, &quot;cat_column3&quot;,<br>            ]].to_numpy(),<br>            &quot;continuous&quot;: pd_data[[<br>                &quot;num_column1&quot;, &quot;num_column2&quot;, &quot;num_column3&quot;, &quot;num_column4&quot;, &quot;num_column5&quot;,<br>            ]].to_numpy(),<br>        }<br>        vectors = model.predict(data, verbose=0)<br>        yield pd.Series(list(vectors))</pre><p>Ok, let’s break everything down…</p><p>The first line is the Pandas UDF function decorator.</p><pre>@pandas_udf(ArrayType(FloatType()), PandasUDFType.SCALAR_ITER)</pre><p>Here, the first parameter is the return type, and since the model is an encoder, the return type is an array of floats. The second parameter is the function type, which is a Scalar iterator. The Scalar iterator takes an iterator of batches as input instead of a single batch and, instead of returning a single output batch, it yields output batches.</p><p>The next important line is the function parameters line.</p><pre>row_batch_iter: Iterator[<br>  Tuple[pd.Series, pd.Series, pd.Series, pd.Series, pd.Series, pd.Series, pd.Series, pd.Series]<br>]</pre><p>As you can tell, I’m a big fan of type hints…so it’s kind of self explanatory. It’s an Iterator of a Tuple with 8 pandas series (i.e. Columns).</p><p>Now for the meat and potatoes. The first line of the function is to load the model.</p><pre>model = tf.keras.models.load_model(&quot;/dbfs/models/JobEncoderModel/Production/model&quot;)</pre><p>Since it’s outside the for loop, it only has to load the model once per function call. And as you’ll probably notice, I’m loading the model from DBFS. 😬</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*lAurtT1Tq7PIiu2a-b4dqQ.png" /></figure><p>“<strong>But I thought you said the model was in mlFlow?</strong>”, I heard someone in the back say!</p><p>Well, it is. But as the Pandas UDF gets called, and batches are passed to the function, loading the model from mlFlow causes the mlFlow API to error with “too many 429 error responses” after some time.</p><p>Therefore I need to retrieve it from mlFlow and save it to DBFS before calling the function.</p><pre>model = mlflow.tensorflow.load_model(<br>    model_uri=f&quot;models:/JobEncoderModel/Production&quot;<br>)<br>dbutils.fs.rm(&#39;dbfs:/models/JobEncoderModel/Production/model&#39;, True)<br>tf.keras.Model.save(model, filepath=&quot;/dbfs/models/JobEncoderModel/Production/model&quot;, save_format=&quot;tf&quot;)</pre><p>There might be a way around the “too many 429 error responses” error, but this was a pretty simple solution. Now, there are no issues loading the model, no matter how many rows or how big your cluster is.</p><figure><img alt="Don’t say it Omar." src="https://cdn-images-1.medium.com/max/300/1*AWMxg0qFy6gVB6pNtWNq7A.png" /><figcaption>Don’t say it.</figcaption></figure><p>Next, we loop the Iterator and get the batches, but since they come in as pandas.Series from the Spark columns, there are no column names.</p><pre>num_column1.name = &quot;num_column1&quot;</pre><p>For convenience, I’ll add a name to the pandas Series so I can refer to them more easily later and if any developer comes in after me, it’ll be less confusing.</p><p>Then I concat the Series into a pandas dataframe. This way I can create my dataset the way the model wants it.</p><pre>pd_data = pd.concat([cat_column3, cat_column1, cat_column2, num_column1, num_column2, num_column3, num_column4, num_column5], axis=1)<br>data = {<br>    &quot;categorical&quot;: pd_data[[<br>        &quot;cat_column1&quot;, &quot;cat_column2&quot;, &quot;cat_column3&quot;,<br>    ]].to_numpy(),<br>    &quot;continuous&quot;: pd_data[[<br>        &quot;num_column1&quot;, &quot;num_column2&quot;, &quot;num_column3&quot;, &quot;num_column4&quot;, &quot;num_column5&quot;,<br>    ]].to_numpy(),<br>}</pre><p>Lastly, predict the batch, and yield it back to Spark.</p><pre>vectors = model.predict(data, verbose=0)<br>yield pd.Series(list(vectors))</pre><p>Now, I can create a new column and call the function on all of my records.</p><pre>df_vectors_1 = df_vectors.withColumn(&#39;profileVector&#39;, <br>                    generate_vectors_udf(<br>                        &#39;num_column1&#39;,<br>                        &#39;num_column2&#39;,<br>                        &#39;num_column3&#39;,<br>                        &#39;num_column4&#39;,<br>                        &#39;num_column5&#39;,<br>                        &#39;cat_column1&#39;,<br>                        &#39;cat_column2&#39;,<br>                        &#39;cat_column3&#39;<br>                    )<br>                ) \<br>                .groupBy(&quot;candidateId&quot;).agg(F.collect_list(&#39;profileVector&#39;).alias(&#39;profileVectors&#39;)) \<br>                .cache()</pre><p>What you’ll notice here is that a candidate can have multiple vectors depending on their profile, and they need to get aggregated into an array in the profileVector column which is then stored in our Vector Database (ElasticSearch in this case).</p><p>Ok, great. How long does it take?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*4tmFxr3ZctyA3nQvN8qKAQ.png" /></figure><p>1.5 million records took 39 seconds to vectorize on a cluster of 10 workers. The 1,255,416 records was after the candidates were aggregated and the vectors were collected into a list.</p><p>Looks good, Ship it!</p><p>Hopefully this was helpful in some way…and if it wasn’t, then why are you still here. 🤣</p><p>Anyway…Thanks and Happy Coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*SCbjCsd7fbSF041-wF4R0Q.png" /><figcaption>Pandas UDF’s for the win!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32f0b8d1f8bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Tensorflow and Tensorflow Text on a M1 Mac]]></title>
            <link>https://medium.com/@murphy.crosby/building-tensorflow-and-tensorflow-text-on-a-m1-mac-9b90d55e92df?source=rss-96c8f15537d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b90d55e92df</guid>
            <category><![CDATA[m1-chip]]></category>
            <category><![CDATA[tensorflow-text]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[m1]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Murphy Crosby]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 04:17:32 GMT</pubDate>
            <atom:updated>2022-12-12T14:51:29.911Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you asking yourself, “Hey dummy, why would I want to build <em>tensorflow</em> and <em>tensorflow_text</em> from source when I can just install <em>tensorflow-macos, tensorflow-metal</em>, then install <em>tensorflow_text</em>?”? Well, I’m glad you asked StackOverflow user (Am I the only one that has been berated on StackOverflow for asking a question? 🤣). Unfortunately, there is no wheel for <em>tensorflow_text</em> for the <strong>arm64</strong> architecture, and it seems no one has built one publicly. Until now.</p><p>Since I need <em>tensorflow_text</em> and I have a M1 Mac, I need to build them from source. So, after much googling and frustration, I happened upon the correct tensorflow issue and response that allowed me to build <em>tensorflow</em> and <em>tensorflow_text </em>from source so that I can install and run on my M1 MacBook. Thanks to <a href="https://github.com/freedomtan"><strong><em>freedomtan</em></strong></a> for spelling it out. The links to the issues are <a href="https://github.com/tensorflow/tensorflow/issues/58805">https://github.com/tensorflow/tensorflow/issues/58805</a> and <a href="https://github.com/tensorflow/tensorflow/issues/58368">https://github.com/tensorflow/tensorflow/issues/58368</a>.</p><p>If you want a walkthrough so you can build for different python or tensorflow versions, feel free to follow along. Otherwise, links to the wheels I made are below for download.</p><p>First you need to backup your current Xcode linker, <em>ld</em>. Check your version, and take note to ensure we are running the correct one.</p><pre># ld -v<br><br>@(#)PROGRAM:ld  PROJECT:ld64-820.1<br>BUILD 18:42:42 Sep 11 2022<br>configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em<br>LTO support using: LLVM version 14.0.0, (clang-1400.0.29.202) (static support for 29, runtime is 29)<br>TAPI support using: Apple TAPI version 14.0.0 (tapi-1400.0.11)</pre><p>The version here is<em> ld64–820.1</em>. Run <em>xcrun -f ld </em>and then mv it to a new name. I moved mine to <em>ld.backup</em>.</p><pre># xcrun -f ld<br><br>/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld<br><br># sudo mv /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld ld.backup</pre><p>If you receive a permission error, you may need to ensure that your terminal has full access to your disk. Open Mac System Settings, then click Privacy and Security ➡️ Full Disk Access. At the bottom, click the ➕ and navigate and click on the terminal that you use. Then rerun the mv.</p><p>Next you will need to download Xcode 13.1. This is located on the Apple Developer site in the additional downloads section. <a href="https://developer.apple.com/download/all/?q=xcode%2013.1">Xcode 13.1 Downloads</a>. This will download a 10GB Xcode_13.1.xip file. Once downloaded, double click Xcode_13.1.xip, and this will unpack the application to <em>Xcode.app (note: it’ll take about 5–10 minutes to unpack)</em>. At this point you’ll go back to the terminal and navigate to where Xcode.app was unpacked. Mine was in <em>~/Downloads. </em>Then copy <em>ld</em> to where the other one was located.</p><pre># cd ~/Downloads<br># cp Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/</pre><p>Then rerun <em>ld -v.</em></p><pre># ld -v<br><br>@(#)PROGRAM:ld  PROJECT:ld64-711<br>BUILD 18:11:19 Aug  3 2021<br>configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em<br>LTO support using: LLVM version 14.0.0, (clang-1400.0.29.202) (static support for 27, runtime is 29)<br>TAPI support using: Apple TAPI version 14.0.0 (tapi-1400.0.11)</pre><p>Now we can tell we are on the older Xcode Linker since we now have <em>ld64–711.</em></p><p>Next we need to make sure we have bazelisk and the version of python we want for our tensorflow version.</p><pre># brew install bazelisk<br># brew install python@3.9</pre><p>Now we’re ready to build Tensorflow. This closely follows the the tensorflow build process, with one minor caveat I mentioned below.</p><p>We’ll need to clone tensorflow, setup a python virtual environment, and run configure.</p><pre># git clone --branch v2.10.1 https://github.com/tensorflow/tensorflow.git<br># cd tensorflow<br># python3.9 -m venv .venv<br># source .venv/bin/activate<br># pip install numpy==1.23.5 wheel==0.38.4 packaging==21.3 requests==2.28.1 opt-einsum==3.3.0<br># pip install Keras-Preprocessing==1.1.2 --no-deps<br># ./configure</pre><p>I took all of the defaults on the configure. <em>Side note:</em> No Cuda GPU support on the build. If later you install the <em>tensorflow-metal</em> that matches your tensorflow version, you can get GPU support there. 😉 There’s no chart on <em>tensorflow-metal </em>that matches it to tensorflow, so I figured out the version based on the published dates.</p><p>This is also where I deviated slightly. I used the config value of <em>macos_arm64</em>.</p><pre># sudo bazel build --config=&quot;macos_arm64&quot; //tensorflow/tools/pip_package:build_pip_package<br># ./bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg<br># deactivate</pre><p>This took around 30-45 minutes to build. It seemed to keep going and going. After it was complete, <em>tensorflow-2.10.1-cp39-cp39-macosx_13_0_arm64.whl</em> was in the <em>tmp/tensorflow_pkg</em> directory.</p><p>Next we need to build tensorflow-io. You’ll want to match the io version to the tensorflow version. There is a table on the <a href="https://github.com/tensorflow/io.git">https://github.com/tensorflow/io.git</a> page that will tell you which version.</p><pre># git clone --branch v0.27.0 https://github.com/tensorflow/io.git<br># cd io<br># python3.9 -m venv .venv<br># source .venv/bin/activate<br># pip install setuptools==65.4.1 wheel==0.38.4<br># python setup.py -q bdist_wheel --project tensorflow_io_gcs_filesystem<br># deactivate</pre><p>This will produce <em>tensorflow_io_gcs_filesystem-0.27.0-cp39-cp39-macosx_13_0_arm64.whl</em> in the dist folder.</p><p>Now, we’re ready to build Tensorflow Text.</p><pre># git clone --branch v2.10.0 https://github.com/tensorflow/text.git<br># cd text<br># python3.9 -m venv .venv<br># source .venv/bin/activate</pre><p>Copy the tensorflow and tensorflow-io wheels into this directory. Install tensorflow-io first, then tensorflow.</p><pre># pip install tensorflow_io_gcs_filesystem-0.27.0-cp39-cp39-macosx_13_0_arm64.whl<br># pip install tensorflow-2.10.1-cp39-cp39-macosx_13_0_arm64.whl</pre><p>Next you need to edit ./<em>oss_scripts/pip_package/setup.py</em> and remove the <em>tensorflow-macos</em> line from the requirements. This messes up the tensorflow wheel we just created when we install it later. It essentially installs <em>tensorflow-macos</em> on top of tensorflow. Remove line 77.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaVS-xPQ7VD2gtW-K-fddA.png" /></figure><p>Now we can build.</p><pre># ./oss_scripts/run_build.sh<br># deactivate</pre><p>This one doesn’t take near as long. When it’s complete you should have <em>tensorflow_text-2.10.0-cp39-cp39-macosx_11_0_arm64.whl</em></p><p>Now you can copy all three wheels into a new directory and install them and watch the magic.</p><pre># python3.9 -m venv .venv<br># source .venv/bin/activate<br># pip install tensorflow_io_gcs_filesystem-0.27.0-cp39-cp39-macosx_13_0_arm64.whl<br># pip install tensorflow-2.10.1-cp39-cp39-macosx_13_0_arm64.whl<br># pip install tensorflow_text-2.10.0-cp39-cp39-macosx_11_0_arm64.whl<br># pip install tensorflow-metal==0.6.0</pre><p>Run python, import tensorflow and tensorflow_text…then profit?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9W-XgEJFL-v_AtlurFABoA.png" /></figure><p>Like I mentioned above, if you want to bypass all this razzmatazz and just download the wheels, go to my <a href="https://drive.google.com/drive/folders/1eHfUjjb5kOaQ-SZom5ldHROyr5Rwa5mh?usp=sharing">Google Drive</a> and download away.</p><p>I also want to give credit to TeoZosa for his repo <a href="https://gist.github.com/TeoZosa/da88a858ad73a18e3f7410c4b615466d">here</a>. This didn’t quite work for me, but it gave me some ideas and helped me figure some things out.</p><p>Thanks and Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b90d55e92df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>