Zero Labs
Industry News / AI

Build a Jev-Style Decision Model from an LLM, Part 4: Letting the Backbone Learn, Then Giving It…

Source · Towards AI By Divye Singh

From the publisher’s feed, collected in the ZeroLabs newsroom.

Build a Jev-Style Decision Model from an LLM, Part 4: Letting the Backbone Learn, Then Giving It EyesLetting the backbone learn with LoRA and then giving the same scoring head images to read.Photo by Franck V. on UnsplashWhere Part 3 left offPart 3 ended with a working decision model on a frozen backbone. A head with 524,288 trainable numbers turned four vectors into probabilities. On synthetic tickets it reached 0.963 accuracy over three seeds on the test set. Random guessing gives 0.352. The same part named its own limit. The department question stayed at 0.882 while refund, tone and urgency were at 0.985 or above. A frozen model can only offer what is already easy to read at the decide token.This part removes that limit and then adds a second kind of input. First we let the backbone learn with LoRA. Then we let the same machinery read images.The story so far:Part 1 made a model answer with one token by biasing its output scores.Part 2 opened the model, found a hybrid design with memory layers and attention layers and wrote each question into one token sequence with one-token markers.Part 3 read a vector at each marker, scored the options with a pointer head and trained that head. It also made the probabilities trustworthy with calibration.The whole pipeline, with this part marked:One example runs through this part. Imagine the billed-twice ticket again. This time the customer also attaches a screenshot of the failed payout screen. The state of a question can now be text, an image or both. The same scoring machinery decides.What this part covers:LoRA, which lets the backbone learn without changing its original numbers. We cover how it works and what it costs. We also show what it fixed on the text tickets, with full hyperparameters.Vision. We cover how the model sees an image, a shapes dataset where every label is exact and a control that proves the model uses the picture. We also report the vision results.What we did not finish.Where it stops: every number comes from synthetic data, either templated tickets or rendered shapes. We show that the pipeline works end to end. We do not show that it handles real tickets or photographs.Letting the backbone learn: LoRAA frozen backbone can only expose what is already easy to read at the decide token. LoRA (low-rank adaptation) lets the backbone learn without touching its original numbers. Here is the idea in plain terms.A linear layer takes a list of numbers x and multiplies it by a big table of numbers W. A table like that is called a matrix. LoRA freezes W. It adds a small correction built from two thin matrices, A and B:W is the frozen matrix. A and B are the two thin trainable matrices. A has r rows and as many columns as x has numbers. B has r columns and as many rows as y has numbers. r is the rank, which is how thin they are. We use r = 8. Alpha is a fixed scale. We use 16, so the scale alpha/r is 2.The correction has the full shape of W but is built from far fewer numbers. Take the layer that turns 1,024 inputs into 6,144 outputs:Here is a tiny layer with 3 inputs and 2 outputs that we can follow by hand. Use rank 1 and alpha 2, so the scale is 2.Two details carry weight. B starts at zero. So the adapted model begins as exactly the original model. Training then moves it away smoothly. And alpha/r is a fixed scale. It lets you change the rank without retuning the learning rate much. The bet behind LoRA is that the change a task needs is low rank.Where we put the adaptersWe put adapters on every linear layer in the 24 language layers. That covers the memory-layer projections, the attention projections and the feed-forward blocks. We skipped two tiny gate projections and left the vision tower alone. A regular expression selects the layers. The result is 5,111,808 trainable parameters, which is 0.60% of the model. The count matches a hand calculation over the selected layers. Before any training we verified four things:The cost of adaptingUntil now the output of the backbone never changed, so one pass cached it forever. With LoRA the output changes at every step. So there is no cache. Every question needs a full forward and backward pass in every epoch.Memory is the harder problem. Backpropagation must keep the activations of every layer and this model’s recurrence creates large intermediate tensors. We measured about 0.55 GB per sequence without any tricks. The graphics card has 8.08 GB:Two changes fixed it. Gradient checkpointing stores only the input of each layer and recomputes the insides during the backward pass. It trades compute for memory. With it, a batch of 4 peaked at 2.0 GB in total. The second change was turning the KV cache off. The model builds a cache by default. Recomputation during the backward pass appended to it a second time. That crashed with a shape mismatch, a cache of length 154 where 77 was expected. Disabling the cache removes the problem and does not change results. We confirmed the outputs are bit-identical.What adapting the backbone gave usEvery main number below is the mean of three seeds. The task is the 800-ticket synthetic set from Part 3. The test set was used once per run. Each run first trains the frozen head. Then it trains the adapters and the head together. Both stages come from the same run, so the comparison is paired.The recipe, called main_brier:The spread over seeds was small in every main comparison. The accuracy spread was 0.005 or less. So the differences are not noise. Chance accuracy is 0.352. Per question on test, the accuracies are:Two things stand out.The adaptation fixed exactly the weakness from Part 3. The department question went from 0.882 to 0.970. The other three questions were already at 0.985 or above.The answers stopped depending on the order of the options. On the validation set, tickets with at least one wrong option order fell from 64 of 235 to 11 of 235. The number wrong in every order barely moved, from 2 to 3. LoRA removed the order sensitivity. It did not remove the genuinely hard tickets.Here is the department question by true answer, for seed 0 on validation, with all option orders counted. The frozen column is the retrained head from the paired run, so it differs a little from the Part 3 table:The Brier term. Adding it to the loss gave a small gain on test, in the last two columns of the results table. Validation does not separate the two versions, so this is the best configuration with test evidence and not a proven one. Brier looks at the whole probability vector and is bounded, which may be why it helps. On the frozen head it made no difference (test Brier 0.056 against 0.055), probably because that head has few parameters and its errors come from features it cannot change.Training cost and the learning curveThe gain has to be weighed against the cost. The frozen backbone is read once and its features are cached. LoRA needs a full pass in every epoch.If the frozen head is good enough, its training step is about fifty times cheaper. Extracting the features still takes minutes.Training converged quickly. Quick validation accuracy uses the first 60 validation tickets in 2 orders. After epoch 1 and epoch 2 it read 0.997 and 0.997. A run with 4 epochs read 0.964, 0.997, 0.992 and 0.992. So the second epoch was enough.Adaptation is not always better. With few tickets the adapted model was worse than the frozen head. These are single-seed validation runs. The number of epochs was fixed, so fewer tickets also meant fewer update steps. The two effects are not separated here.The crossover lies between 200 and 400 tickets.Settings we varied and what we did not confirmEach row changes one setting of the default recipe. They are single seeds scored on validation only. A gap of about 0.005 in accuracy is inside the noise.The pattern is consistent. A higher learning rate and a higher rank did better. A lower rate and a lower rank did worse. Four epochs cost twice the time for 0.002 more accuracy.Best observed, not confirmed: LoRA learning rate 5e-4 reached 0.999 validation accuracy and a Brier of 0.003. Rank 16 reached 0.997. Neither was run with three seeds. Neither was scored on the test set. We found them on validation, so their numbers are optimistic. A natural next step is to run both with three seeds on test and to try them together with the Brier term.Are the probabilities trustworthy after LoRA?On validation the fitted temperature was 1.30 for LoRA with cross-entropy and 1.41 for LoRA with Brier. The frozen head had 1.41 and 1.32. Both are a little above 1, so the models are slightly overconfident before scaling. After LoRA the model was already calibrated, with an ECE of 0.003 to 0.004 on test. The raw Brier score had fallen by a factor of four, from 0.056 to 0.013, so there was much less left for temperature scaling to repair.This is the reliability table for LoRA with cross-entropy on the test set. Seed 0, with the temperature from validation. Each test prediction goes into a bin by the probability it gave to its top option. Each bin reports how often that top option was right. In a calibrated model the last two columns match.There are no predictions below 0.4. The lower bins hold few examples, so they are noisy. The last bin holds 3,543 of the 3,628 test predictions and dominates the ECE. Its mean confidence of 0.997 and accuracy of 0.998 agree.Best after this experiment, result (test, 3 seeds): the main_brier recipe, with its hyperparameters and test numbers in the tables under “What adapting the backbone gave us”.Vision: giving the decision model eyesThis was the goal of the project. The screenshot of the failed payout screen from our running example now becomes part of the question, and the same scoring machinery decides.How the model sees an imageAn image takes four steps to become something the language model reads:Patches: The image processor cuts the picture into squares of 16 by 16 pixels.Vision tower: A separate 12-layer transformer (768 numbers wide, about 100 million parameters) turns each patch into a feature vector.Merge: Each 2 by 2 block of neighbouring patches is merged into one vector. It is projected to 1,024 numbers, which is the width of the language model. This is what lets image and text share one sequence.Insertion: Those vectors replace placeholder tokens in the text. From there the language model treats them like any other token. Its causal attention lets every later token read them, including our decide token.The cost of an image in tokens follows from the geometry. Count the patches across and down, multiply them and divide by 4 for the merge:H and W are the height and width of the image in pixels. p is the patch size, which is 16. m is the merge size, which is 2. For a 256 by 256 image: (256 / 16) x (256 / 16) / 4 = 16 x 16 / 4 = 64 tokens.The processor enforces a minimum area of 65,536 pixels, which is 256 x 256. That is why a 224 by 224 image is enlarged first. In one of our questions the whole sequence was 97 tokens. Of those, 64 were the image. So two thirds of the work goes into the picture.We probed the interface with one tiny experiment, a plain red circle on white. Every number came out as the geometry says:Two checks showed that the whole stack responds to pixels:Our decision pipeline never uses the language head. But the second check proves that the vision model, the processor and the language model are wired correctly in this environment.A dataset where every label is exactReal photos are impressive and hard to label. So we generate scenes. Each scene has one to four shapes that do not overlap. A shape is a circle, a square or a triangle. There are six colours and distinct sizes on a grey background. The generator places every shape, so each question has a known answer:Here is a made-up scene to show how the labels follow. It has three shapes:Half of the records also carry an uninformative caption, “Photo uploaded by a user.” So the state mixes an image part and a text part, as real tickets would. A record’s state becomes a list of parts and an image part is just a file path. Pointing the pipeline at real photos therefore needs new records and not new code.Extending the pipelineThree small changes handle images:Renderer: An image part becomes the model’s own image block. That is a start token, the run of image placeholder tokens and an end token. Markers, option tokens and sanitizing are unchanged. The image comes before the question, so the question, every option and the decide token can all attend to it.Encoder: It joins the batch’s pixel data, grids and token-type masks. It passes them to the backbone with the ids.Batching: Checked, not assumed. A padded batch with images matched one-at-a-time processing with a cosine of 0.997 or better.The control that keeps you honestA high score on a vision task proves little until you rule out the alternative. The model might be answering from label frequencies alone. The cheapest strong test is swapped images. Give each validation record the image of the next record. Keep its own questions and labels. Then evaluate again. The text and the labels are unchanged, but the picture no longer matches.If accuracy stays high, the model is not looking. If it falls toward chance, the answers come from the image. The drop measures how much each answer depended on the picture. We also ran a second control, no image, which removes the image and keeps the caption. Both controls were applied to the validation set. These are real numbers, the mean of 3 seeds:Overall chance on validation is 0.337. Both controls land on chance. So the answers come from the picture. Adapting the backbone did not teach it to answer from the caption or from label frequencies. The one exception is the triangle question. It stays near 0.5 under the controls because the answer is yes more often than no. That is a prior and not vision.What the shapes experiment showedWe used the same protocol as for text: 800 training records, three seeds, validation for choices and a test set used once per run. The recipe is the same as for text. The only difference is that the frozen head sees 4 shuffled option orders per question and not 6.Chance on this task is 0.337. Adaptation helped, but by less than on text. The gain came mainly from the leftmost question, which went from 0.880 to 0.950 on test and from the colour question, which went from 0.924 to 0.958. Counting and triangle detection were already at 0.978 or above with a frozen backbone. This fits a check we ran on the decide vector. We replaced the pixels of one question with another record’s image and kept the tokens identical. The vector moved only slightly, with a cosine of 0.9985. As Part 3 found for text, the vector is dominated by a large shared part and the image content is a small residual that the head has to find. For easy questions the head finds it. For spatial questions the adapters make it easier to find.Order stability is the one measure where the Brier variant is not better on test, with 0.970 against 0.977. The gap is inside the spread over seeds.Where the errors remain. The remaining errors are spatial and perceptual. These are seed 0 on validation, with all option orders counted:On the leftmost question, tickets with at least one wrong option order fell from 36 of 200 to 16 of 200. Those wrong in every order fell from 11 to 6. LoRA does not fix every class. For the colour question the error rate for red and purple went up, while blue went to 0%. Each question has 200 validation records, so a per-class rate rests on a few dozen examples. These movements are only suggestive. Orange and purple are the worst colours.Two results differ from text. First, adding Brier to the loss helped more here. On validation with LoRA, accuracy was 0.980 against 0.972 and Brier was 0.032 against 0.040. The gain was on the leftmost question, 0.974 against 0.944. The spread for the Brier variant was only 0.001 over three seeds. It is still one synthetic dataset, so we call it a hint. Second, adaptation helped even with few records:These are single-seed validation runs. The frozen head already starts high at 0.912. The adapters need little data to improve the hard spatial questions.Settings we varied. Each row changes one setting of the default. They are single seeds on validation, so a gap under 0.01 is inside the noise.Unlike text, the vision model was still improving after two epochs. The quick validation accuracy was 0.967 and 0.975 after two epochs. A 4-epoch run read 0.963, 0.981, 0.981 and 0.983. So more training helps here.Best observed, not confirmed: 4 epochs reached 0.982 accuracy with a stability of 0.987 and a Brier of 0.023, at double the time. A learning rate of 5e-4 reached 0.981. Rank 16 reached 0.980. None was run with three seeds or scored on the test set. The Brier variant above is the best configuration with three seeds and test evidence.Calibration. The frozen head was overconfident, with a fitted temperature of 1.87. Temperature scaling cut its ECE from 0.028 to 0.008 on validation. After LoRA the temperature was about 1.1 and scaling barely mattered. LoRA made the probabilities better calibrated without any repair step. The reliability table below is for LoRA with cross-entropy on the test set, seed 0, with the temperature from validation:The lower bins hold few examples and are noisy. The last bin holds most predictions and its confidence and accuracy agree.Cost. LoRA training took 436 seconds for two epochs on 800 records. That is 1.6 times the text cost, because every record carries 64 image tokens. Peak graphics memory was 2.84 GB. The frozen head trained in 4.9 seconds on cached features. Extracting the frozen features, which includes the vision tower, took 409 seconds in the first run.Best after this experiment, result (test, 3 seeds): the recipe with Brier in the loss, with its hyperparameters and test numbers in the tables under “What the shapes experiment showed”.These are rendered shapes in six colours on a plain background. This shows that the pipeline and the adaptation work end to end. It does not show that the model handles photographs.What we did not finishThe limit of this whole series is the data. Everything we measured is on synthetic tickets or synthetic shapes. The pipeline works end to end. We have not shown that it works on real traffic. Here is what is left and what would settle each item:What to take awayA frozen model plus a small pointer head reads a decision off one forward pass. LoRA lifts the accuracy from 0.963 to 0.995 on text. The same machinery reads images and the controls show that it looks at them. Here is the whole series in one table. Each row is the best configuration with test evidence:For business readersDecision models are cheap and fast. One forward pass replaces a generated paragraph. The output is always a valid choice with a probability.The data needed is modest, but it must be varied. Accuracy rose with every doubling of data. Tiny datasets produce numbers that look perfect and mean nothing. Insist on results measured on tickets the model has never seen.Probabilities have to be earned. Accuracy does not tell you whether “0.9 sure” is trustworthy. Ask for calibration measures such as the Brier score and the calibration error. Ask for a held-out test too. Our auto-close example showed how a miscalibrated model hides 200 extra wrong closures in every 1,000 tickets.Synthetic data is a smoke test and not a benchmark. If the labels are encoded in keywords, high accuracy proves little about real traffic.Check that the model uses the evidence. For image tasks the swapped-image test is a cheap and decisive question to ask any vendor or team.For engineersInspect the real object before trusting an API, a tutorial or an attribute name.Hybrid models with attention plus recurrent memory break assumptions that hold for pure transformers. You cannot mask tokens out of a recurrent state.Compare in fp32 before declaring a bug in bf16 code. Think in units of the rounding step of the number format.A symmetric head on a causal backbone is not order-invariant. Shuffle the options with the label moved and measure order stability.Check baselines such as random guessing. Report seeds. Split by the unit that shares information, which is the ticket and not the question.Write the unit test with data that looks like production. Our temperature-scaling bug needed minus-infinity padding to appear.Features can be cached while the backbone is frozen. That stops being true with LoRA, so plan the compute for it.Try it yourself: the jev packageThe whole pipeline from these four parts is available as a small Python package called jev. You give it a state, which can be text or an image or both, and typed questions with fixed options. One forward pass per question returns a probability for every option. No text is generated, so nothing needs parsing and the answer is always one of your options.The files follow the parts of this series:render.py and vision.py write a question into one token sequence with the marker tokens from Part 2 and add image tokens when a state contains pictures. They also sanitise user text so nobody can forge a marker.features.py runs the backbone over padded batches and caches the readout vectors. head.py holds the masked pointer head from Part 3.calibration.py has NLL, Brier, ECE, reliability tables and temperature scaling.train.py trains the head and the LoRA adapters of this part, with the optional Brier term in the loss.data.py and shapes.py load and convert records and generate the shapes images with exact labels.A record is one JSON object per line, made of a state and a list of questions. Each question has a type (choice, noul or score) and its options. Training has two stages: the frozen head always runs and LoRA is switched on with a flag. At the end a temperature is fitted on the validation set, so the probabilities come out calibrated.python -m jev train --train data/synthetic/train.jsonl --val data/synthetic/val.jsonl --out runs/text_lora --max-train-records 800 --lorapython -m jev evaluate --model runs/text_lora --data data/synthetic/test.jsonlpython -m jev predict --model runs/text_lora --request request.jsonA prediction for a yes or no question looks like this. Score questions also return the expected level, which is the probability-weighted position on the scale.[{"id": "has_triangle", "type": "noul", "options": ["no", "yes"], "probabilities": [0.16, 0.84], "prediction": "yes", "confidence": 0.84}]On the 8 GB laptop GPU used in this series the caching step runs at about 8 ms per text example and 25 ms per image example. LoRA training peaks at about 2.7 GB of memory at the default batch of 16. The limits are the ones from this part: the vision tower stays frozen and the bundled data is synthetic, so its numbers are a pipeline check and not a benchmark. Test on your own records before trusting a number.The repository also holds nine notebooks that walk through the same steps, from opening the model to answering questions about images.This is the end of the series. Every number comes from three result files in the results folder. RESULTS.md covers the frozen head. RESULTS_LORA.md covers LoRA on text. RESULTS_VISION.md covers images.The Supplement is the lookup page for the series. It collects every best recipe with its hyperparameters and test numbers. It also holds a glossary of every term used in the four parts and the log of the mistakes we made. The takeaways and the questions that came up for each part are there too.https://github.com/sdivye92/create_jev/blob/main/supplementary_material.mdBuild a Jev-Style Decision Model from an LLM, Part 4: Letting the Backbone Learn, Then Giving It… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.