Machine learning
Training and Serving Multimodal LLMs in Production
Canva’s 4B vision-language model performs 30+ content and quality checks on 100k+ images a day. Here’s how we trained and served it to return probabilities for each check, cut LLM costs by 85%, and reduced p50 production latency from 3.5 s to 240 ms.
Introduction
Every day, Canva reviews hundreds of thousands of images for its public library, checking each against more than 30 content and quality criteria. As that volume grew, so did the cost of using third-party language models. We set out to build a specialized vision-language model that could make those checks more accurately and at a lower cost.
This is the story of taking that model from training to production: teaching it our review criteria, turning its answers into useful confidence scores, and overcoming the bottlenecks that made serving it slow. Along the way, we cut costs by 85%, halved the rate of missed violations without increasing false positives, and reduced p50 production latency by 15x.
We’ll walk through these stages:
- Training the model: Formatting conversations consistently, fitting fine-tuning into GPU memory, and focusing the loss on the true/false decisions.
- Serving structured outputs with probabilities: Enforcing the JSON format and extracting a probability for each review check.
- Accelerating inference: Using the predictable output structure to verify many tokens in a single forward pass with speculative decoding.
- We finally wrap this up by showing how to wire up the whole system and showing the results in latency improvements.
Why train your own model?
Put simply, a custom model can be more accurate and cheaper for well defined problems like this.
Content review repeats the same checks across hundreds of thousands of images every day. At that scale, fine-tuning a small vision-language model offered substantial savings. After the initial investment in training, running it on our own GPUs reduced our LLM costs by around 85%.
Fine-tuning also let us teach through examples. Subjective criteria such as poor styling were difficult to capture in a prompt alone. Rather than relying only on written definitions, we trained on labeled images that demonstrated what each flag meant. Our final model halved the false negative rate (proportion of violations that slipped through) without increasing the false positive rate (proportion of acceptable content that's incorrectly flagged).
This approach suited our workload because the task was clearly defined, relatively stable, and repeated at high volume. For smaller workloads or tasks with frequently changing requirements or output schemas, a third-party hosted model can still be the more practical choice.
Training
This section walks through the tools and techniques we used to fine-tune our 4B model. Although small by today’s standards, it still needed to fit within our GPU memory budget and train in a reasonable amount of time. That meant being deliberate about which parameters we trained, how we stored them, and where we focused the learning.
Formatting conversations for training and serving
Before fine-tuning, we needed to make sure the model saw each conversation in the format it had learned to recognize. We used the same chat template during training and serving so that the system and user messages were formatted consistently. During training, we supplied the labeled assistant response, during serving, the model generated it.
A chat template turns the system, user and assistant messages into a single formatted sequence. Special tokens are used to mark who is speaking and where each message begins and ends. The text is then tokenized and converted into the integer IDs the model processes. For Qwen3.5, the template follows the ChatML format:
<|im_start|>systemYou are an expert image curator specializing in content quality and appropriateness assessment.<|im_end|><|im_start|>userAnalyze this image and respond with a JSON object following this schema: {...}Feature definitions:- animal cruelty: Animals in distress, ...- political content: Political figures, names, symbols, ...<|vision_start|><|image_pad|><|vision_end|><|im_end|><|im_start|>assistant
You never build this string by hand. You build a list of messages and call apply_chat_template, and the model’s own template inserts the special tokens:
messages = _build_input_messages(schema=schema, features=features, image_url=image_url) # see Appendix A for definition of _build_input_messagesprompt_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
Appendix A shows how the processor builds the messages and final tensors.
Training fewer parameters with LoRA

Full fine-tuning would require gradients and optimizer states for all 4 billion parameters. LoRA (Low-Rank Adaptation) reduces that memory cost by freezing the original weights and learning an update represented by two smaller matrices.
Using the notation in the diagram, the updated weight matrix is:
W_new = W_old + (lora_alpha / r) × B Aᵀ
Only A and B are trained; W_old stays fixed. For a 1000 × 1000 weight matrix and rank r = 24, A and B can each have shape 1000 × 24. That gives us 48,000 trainable parameters instead of one million. 4.8% of the original matrix’s parameter count.
We apply LoRA to all linear layers using the configuration below:
peft.LoraConfig(r=24,lora_alpha=48,lora_dropout=0.05,target_modules="all-linear", # every linear layer, not just q/k/vtask_type="CAUSAL_LM",ensure_weight_tying=model.config.tie_word_embeddings,)
We also used QLoRA to store the frozen base weights in 4-bit form, freeing enough GPU memory to increase our batch size from 4 to 24. The quantization details and configuration are in Appendix B.
Focusing the loss on the response

Each training example contains the full conversation: the instructions, the image, and the assistant’s labeled JSON response. We train with next-token cross-entropy loss(opens in a new tab or window), which penalizes the model when it assigns a low probability to the correct next token.
We calculate that loss only on the assistant’s response. The instructions and image still provide the context needed to make each decision, but their token positions are excluded from the loss. This is called loss masking. It focuses training on predicting the answer rather than reproducing the input.
We need to calculate the response boundary per row in each batch. We render the chat template twice per example. First, with the full conversation and second with the instruction prompt alone.
full_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)prompt_text = processor.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
Setting add_generation_prompt=True includes the assistant’s opening header in prompt_text. We include that header in the masked region so the loss starts with the JSON response itself. After processing the prompts, we use their token counts to locate that boundary:
prompt_lengths = prompt_attention_mask.sum(dim=1) # token count per promptpositions = torch.arange(labels.shape[1]).unsqueeze(0)labels = labels.masked_fill(positions < prompt_lengths.unsqueeze(1), -100)
Summing each row of prompt_attention_mask gives the number of prompt tokens for that example. With right-padded sequences, positions below that count belong to the prompt. We set their labels to -100, which tells the cross-entropy loss to ignore them. Padding labels must also be set to -100.
At this stage, the model learns to predict both the JSON structure and the boolean answers. Training encourages the expected format; the decoding constraints described later enforce it.
Training directly on the boolean decisions
A typical assistant response looks like this:
{"UNSAFE_CONTENT":false,"LOW_QUALITY":true}
The decisions are the false and true values. The remaining tokens spell out feature names and JSON syntax. In a second stage of training, we focused the loss exclusively on the boolean positions, so those formatting tokens no longer contributed to the loss.
At each position, the model produces a logit—an unnormalised score—for every token in its vocabulary. Across a batch, these scores form a tensor with shape batch_size × sequence_length × vocab_size. At positions where the next labeled token is true or false, we take the difference between those two scores:
boolean_logit = logits[true_id] - logits[false_id]
A positive value means the model favors true; a negative value means it favors false. We train this single value with a binary classification loss, using a target of 1 for true and 0 for false. This gives us a direct way to train the decisions while keeping the model’s existing vocabulary and output format.
The core calculation is below. true_id and false_id are the token IDs for the two boolean values, and loss_fn is the binary classification loss.
# Align each prediction with the next token in the labelled response.next_token_logits = logits[:, :-1, :]next_token_labels = labels[:, 1:]# Select positions whose labelled answer is true or false.boolean_logits = next_token_logits[..., true_id] - next_token_logits[..., false_id]targets = (next_token_labels == true_id).float() # 1's and 0's# Calculate loss only where labels are the true or false tokens.boolean_mask = (next_token_labels == true_id) | (next_token_labels == false_id)loss = loss_fn(boolean_logits[boolean_mask], targets[boolean_mask])
The shift (first two lines above) matters because the logits at position t predict the token at position t + 1.
Serving structured outputs with probabilities
Jev(opens in a new tab or window) is TypeSafe AI’s product for returning typed decisions with probabilities. Our system addresses a similar need for image review, using a fine-tuned vision-language model running on our own GPUs.
For each review check, we wanted both a boolean answer and the probability the model assigned to it. We also needed the output to follow a fixed JSON schema, so downstream code could reliably consume the results. The next step was to enforce that structure during decoding while preserving the scores behind each decision.
vLLM (the LLM serving library) ships with structured-output support out of the box. The textbook way to constrain a JSON response is by setting the guided_decoding argument in the library.
import vllmfrom vllm import sampling_paramsschema = {"type": "object","properties": {"UNSAFE_CONTENT": {"type": "boolean"},"LOW_QUALITY": {"type": "boolean"},# ... thirty more},"required": ["UNSAFE_CONTENT", "LOW_QUALITY"], # ... all of them"additionalProperties": False,}params = vllm.SamplingParams(temperature=0.0,max_tokens=512,guided_decoding=sampling_params.GuidedDecodingParams(json=schema),)
Schema-constrained decoding gives us a response that matches the requested structure. Our workload also had a useful property: every response used the same feature names in the same order. Only the boolean values changed.
Our first serving implementation used that fixed layout directly. We built a token template for the JSON response, forcing the known structural tokens and allowing the model to choose between true and false at each value position. At those positions, we preserved both scores so we could recover the probability of true.
To build the template, we rendered a compact JSON object with every value set to true, tokenized it, and recorded the positions of the true tokens. These became the boolean slots where the model could make a decision.
See Appendix C for the code used to build the template.
Three state mask - Enforcing the format

At each decoding step, we restrict which tokens the model can select. We do this by setting disallowed logits to negative infinity, giving those tokens zero probability after softmax. The template determines which of three rules applies:
- Structural position: allow only the next token from the template.
- Boolean position: allow only
trueandfalse, preserving their original logits. - End of the template: allow only the end-of-sequence (EOS) token, which stops generation.
At a boolean position, normalizing over the two allowed tokens gives us the probability of true:
p_true = torch.sigmoid(logits[true_id].float() - logits[false_id].float())
This uses the same logit difference we trained in the previous section. The decoding rules enforce the output format while preserving the model’s relative preference between the two answers.
Accelerating inference with speculative decoding

The previous implementation served in production for months. Then we replaced most of the custom decoding code with speculative decoding without a draft model (we’ll get to this soon), reducing p50 production latency from 3.5 s to 240 ms. The output constraints stayed the same: we expressed the three-state mask as a grammar (next section) so it could be enforced during draft verification.
Production latency was a near constant 3.5 s per image. 97% of it was decode: 190 output tokens at ~56 tokens per second on an L40S, one full forward pass for each token. Only 33 of those tokens carry information, the true / false values. The other 157 are {, ", animal, _, cruelty, ":, ," and so on, all known before the model starts. The three-state mask was decoding each token one at a time, so the GPU spent 3.4 s confirming things we already knew.
It is a common assumption that every token used in an LLM takes O(n^2) to process. However, during prefill, GPUs can process the known token positions in parallel within a single forward pass. For short sequences that fit within the GPU’s available parallel capacity, this can take roughly constant time. Since we know the structure of our json, with variability only in the true/ false tokens, we can exploit this during serving.
Normal decoding produces one token per forward pass. Speculative decoding has a cheap model (draft) guess the next K tokens, then feeds all K to the real model in a single forward pass. The real model scores every position at once, and you keep the drafted tokens up to the first one it disagrees with. Verifying K=32 tokens costs about the same as generating one, because it is a small prefill, and the result is identical to greedy decoding. The only question is how often the draft is right.
The usual draft is a small model, with some of the latest Qwen model just predicting the next few tokens (Multi-Token Prediction - MTP). We don't need one. Our draft is the pre-tokenized template with every boolean set to false, plus EOS:
def draft_template_token_ids(template: BooleanJsonTemplate,boolean_token_ids: BooleanTokenIds,) -> list[int]:draft = [boolean_token_ids.false_token_id if index in template.boolean_positions else token_idfor index, token_id in enumerate(template.template_ids)]draft.append(template.eos_token_id)return draft
Most flags are false on most images, making false a useful default guess. The main model still verifies the draft. If it chooses true at a boolean position, we accept that decision, discard the remaining draft suffix, and propose a new block from the updated position. The largest gains come when long stretches of the draft are accepted together.
We connected the template to vLLM through a custom proposer class. The component that supplies draft tokens for the main model to verify. For each active request, the core operation is a slice of the stored token list:
draft_ids = self._draft_ids[position : position + K]
Here, position is the next ungenerated position in the output template, and K is the maximum number of draft tokens proposed for verification in one pass.
The stored draft already contains the fixed JSON structure, the default false values, and EOS. After verification, the proposer starts its next slice from the request’s updated output position.
We register this proposer using vLLM’s custom_class speculative method. The configuration appears in “Wiring it up” below, after we explain the grammar used to constrain verification.
Expressing three-state mask as grammar
The draft only proposes tokens. It doesn't force the main model to accept them. Without the same output constraints during verification, the model could reject a structural token even when it would produce equivalent JSON another way. For example, preferring to use two tokens of , and " instead of ," for our json structure.
To avoid this, we expressed our three masking rules as a grammar using XGrammar, vLLM’s structured-output backend. A grammar defines which token sequences are allowed. Ours specifies exact token IDs at structural positions and allows either true or false at boolean positions, so vLLM can enforce these constraints while verifying the draft:
def build_boolean_json_grammar(*,template: BooleanJsonTemplate,boolean_token_ids: BooleanTokenIds,) -> str:atoms = ["boolean" if index in template.boolean_positions else f"Token({token_id})"for index, token_id in enumerate(template.template_ids)]true_id = boolean_token_ids.true_token_idfalse_id = boolean_token_ids.false_token_idreturn f"root ::= {' '.join(atoms)}\nboolean ::= Token({true_id}) | Token({false_id})"
A sample result is shown below.
root ::= Token(4754) Token(46300) boolean Token(1288) Token(16714) ...boolean ::= Token(1802) | Token(3721)
Each Token(id) permits exactly that token at that position. The boolean rule permits either the true or false token. The grammar therefore preserves the fixed layout while leaving each review decision to the model.
This is the three-state mask, expressed declaratively. Exactly one token is legal at each structural position, exactly two at each boolean slot, and EOS only after the closing brace. The drafted token is always the only legal token, so structural drafts are accepted by construction.
Wiring it up
We connect the proposer and grammar in two places. The engine configuration registers our proposer by its full Python class name and sets the draft length to 32 tokens. Each request then supplies the grammar that constrains verification, along with the settings needed to return log probabilities for the boolean tokens:
engine_args = AsyncEngineArgs(model="Qwen/Qwen3.5-4B",max_model_len=1536,logprobs_mode="processed_logprobs",enable_prefix_caching=True,speculative_config={"method": "custom_class","model": "my_package.template_proposer.BooleanTemplateProposer","num_speculative_tokens": 32,},)params = vllm.SamplingParams(temperature=0.0,max_tokens=len(template.template_ids) + 1, # the template, then EOSlogprobs=2, # only true/false are legal at a boolean slotstructured_outputs=StructuredOutputsParams(grammar=grammar),)
Latency results
On an L40S GPU, production latency improved at both the median (p50) and the 99th percentile (p99):
Production latency | Before | After |
|---|---|---|
p50 | 3.5 s | 240 ms - 15x speedup |
p99 | 4.6 s | 0.52 s - 8.8x speedup |
Separate benchmarks showed how the speedup varied with concurrency and draft length. Here, concurrency is the number of requests processed at once, and K is the maximum number of draft tokens proposed per verification pass.
Concurrent requests | Speedup over the baseline decoder |
|---|---|
1 | 12.5× with K = 32; 15.8× with K = 128 |
32 | 3.7× with K = 32 |
Our largest benchmark speedup came with a single request and a longer draft. At higher concurrency, the GPU has less spare capacity to absorb the additional work of draft verification, so the relative gain is smaller.
Closing
We started with a small vision-language model and a well-defined review task. Training directly on the boolean decisions gave us a classification objective, and the same logit difference gave us probabilities at serving time.
Our final model halved the false negative rate without increasing false positives, while running on our own GPUs reduced LLM costs by around 85%. The serving optimisations reduced p50 production latency from 3.5 s to 240 ms, a 15× speedup. Those results came from treating training and serving as parts of the same system, using what we knew about the task at each stage.
If you’re building something similar, read Appendices for the war stories and practical tricks we learned along the way. These include a weight-tying mistake that caused vLLM to discard our trained output head, checkpointing that silently stopped gradients in the vision tower, and the memory and serving optimisations that helped make the system practical. These are the details we would have liked to have known before starting.
References
- vLLM documentation — https://docs.vllm.ai(opens in a new tab or window)
- vLLM structured outputs — https://docs.vllm.ai/en/latest/features/structured_outputs.html(opens in a new tab or window)
- HuggingFace TRL (
SFTTrainer) — https://huggingface.co/docs/trl(opens in a new tab or window) - Qwen3.5-4B model card — https://huggingface.co/Qwen/Qwen3.5-4B(opens in a new tab or window)
- Liger Kernel — https://github.com/linkedin/Liger-Kernel(opens in a new tab or window)
Appendix
Appendix A: Vision language tokens
In the rendered prompt the image appears as a single <|image_pad|> token sitting between <|vision_start|> and <|vision_end|>. That single token is a placeholder, not the image. The processor does two things with it.
First, it expands the placeholder. The image is split into a grid of patches, and the processor replaces the one <|image_pad|> with one pad token per patch. The count depends on resolution. Qwen-3's vision encoder uses a 32x32 pixel patch. This is why our image preprocessing rounds dimensions to multiples of 32: a 1024 × 1024 image becomes exactly 32 × 32 = 1024 image tokens, sitting inline with the text tokens.
Second, at the embedding layer the pad tokens are swapped out entirely. Text tokens go through the usual embedding lookup. The image goes through a vision encoder (a ViT), which turns each patch into an embedding vector of the same dimension as the text embeddings. Those vectors are scattered into the positions the pad tokens occupied. From that point on the LLM makes no distinction between the two: it just sees one sequence of embedding vectors and attends over all of them.

The above diagram is how the processor module returns tensors. The input messages to this is show in the code below:
def build_input_messages(schema: dict[str, Any], features: list[str], image_url: str, labels_json: dict[str, bool]) -> list[dict]:definitions = "\n".join(f"- {f}: {FEATURE_DEFINITIONS[f]}" for f in features)return [{"role": "system","content": [{"type": "text", "text": SYSTEM_PROMPT}],},{"role": "user","content": [{"type": "text","text": "Analyze this image and respond with a JSON object "f"following this schema: {json.dumps(schema)}",},{"type": "text", "text": f"Feature definitions:\n{definitions}"},{"type": "image", "image": image_url},],},{"role": "assistant","content": [{"type": "text","text": json.dumps(labels_json, separators=(",", ":")),}],}]
One thing worth calling out here is the output schema. For a flat set of boolean flags, you don't need pydantic. A plain function that builds the schema does the job with less machinery. Here's the one we use. It tells the model the target output is simply {"animal cruelty": false, "political content": true, ...}.
def get_schema_for_labels(labels: list[str]) -> dict:return {"type": "object","title": "MultiLabelBooleanOutput","additionalProperties": False,"required": labels,"properties": {k: {"type": "boolean"} for k in labels},}
Training and serving must produce identical token sequences in the system/ user messages. We enforce it by reusing the build_input_messages function, imported by both the trainer and the vLLM server. The only difference between the two paths is that at training time we append the assistant turn containing the boolean feature response JSON, while at serving time the sequence stops at the open assistant header and the model takes it from there.
Appendix B: Training tricks used
Fitting larger batches with QLoRA. Even with LoRA, we initially struggled to fit more than 4 examples in a batch before running out of GPU memory. Freezing the base weights reduced the memory needed for training, but those weights still had to fit on the GPU.
QLoRA addresses this by storing the frozen base weights in 4-bit form while keeping the trainable LoRA weights at higher precision. We used NormalFloat 4 (NF4) quantization. Moving from 16 bits to 4 bits cuts the raw storage for the quantized weights to a quarter, although total training memory also includes activations, adapter weights, and other overhead.
This freed enough memory for us to increase the batch size from 4 to 24. The configuration below enables 4-bit weight storage with bfloat16 computation:
quantization_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16,)model = transformers.AutoModelForImageTextToText.from_pretrained(pretrained_model_name_or_path=”Qwen/qwen3.5-4b”,quantization_config=quantization_config,)
Image augmentations. Augmentation is standard practice when training CNNs. Showing slightly altered versions of each image (flipped, rotated a little, color-shifted) teaches the model the concept rather than the exact pixels. This also allows us to increase the training sample size without having to hunt for rare positive examples.

Surprisingly, the training libraries, transformers/TRL stack has no built-in support for it. We wired it in ourselves at the collator (data transformation) level, applying augmentations to the image before the processor tokenizes it. It’s worth noting that we do this at the collator so that augmentations don’t take up disk space which is limited.
The above diagram depicts the following code block.
T.Compose([T.RandomHorizontalFlip(p=0.5),T.RandomApply([T.RandomRotation(degrees=(0, 10))], p=0.2),T.RandomApply([T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)], p=0.2),])
Gradient checkpointing. During the forward pass the framework normally stores every layer's activations for every token position, because the backward pass needs them to compute gradients. With image-heavy sequences those activations, not the weights, are what blows up memory. Gradient checkpointing stores activations only at layer boundaries and recomputes the rest on the fly during the backward pass. The cost is roughly one extra forward pass worth of compute; the payoff is that activation memory scales with the number of checkpoints instead of the full depth, which is what lets us run large batches under QLoRA. One trap worth flagging: use the non-reentrant implementation. The older reentrant path silently produced dead gradients in our vision tower. Nothing errors, the model just stops learning from images.
Liger kernels. Liger replaces the RMSNorm and SwiGLU implementations in the model with fused Triton kernels. This resulted in roughly 20% more training throughput and 30% more memory headroom. Liger only matters for training; vLLM ships its own fused kernels for serving.
Both are a single flag on the TRL config, which handles patching the model classes in the right order for you:
sft_config = trl.SFTConfig(...gradient_checkpointing=True,gradient_checkpointing_kwargs={"use_reentrant": False},use_liger_kernel=True,...)
Choosing alpha. This blog(opens in a new tab or window) by unsloth.ai recommends setting alpha = 2 x r. The r is the rank and needs to be a value that's << hidden_dim.
Weight tying. It is important to set ensure_weight_tying=model.config.tie_word_embeddings in the peft.LoraConfig. This is because LLMs occasionally tie the incoming token embeddings and the final vocab head output. By not setting this parameter, we accidentally trained the two as separate vectors, but vllm ended up discarding the trained head.
Appendix C: Serving tips and tricks
Building the serving template:
@dataclass(frozen=True)class BooleanJsonTemplate:template_ids: list[int]boolean_positions: frozenset[int]eos_token_id: intdef build_boolean_json_template(tokenizer,feature_names: list[str],boolean_token_ids: BooleanTokenIds,) -> BooleanJsonTemplate:"""Build a pre-tokenized JSON template for guided boolean decoding."""true_id = boolean_token_ids.true_token_idtemplate_json = json.dumps({name: True for name in feature_names},separators=(",", ":"), # no spaces, so token boundaries are stable)template_ids = tokenizer.encode(template_json, add_special_tokens=False)boolean_positions = frozenset(i for i, t in enumerate(template_ids) if t == true_id)return BooleanJsonTemplate(template_ids=template_ids,boolean_positions=boolean_positions,eos_token_id=tokenizer.eos_token_id,)
A few things that aren't headline-worthy but cost real latency or accuracy if you skip them.
enable_prefix_caching=Trueis essentially free for our workload. Every prompt starts with the same system message plus the same feature list. Prefix caching reuses the KV cache for that prefix across requests and gives us a meaningful tail-latency win.- Exact
max_tokens. Don't pad. Computemax_tokens = len(tokenizer.encode(template_json, add_special_tokens=False))+1and pass that. The last+1being for the EOS token. temperature=0.0for boolean classification. There's no reason to sample. The decoder masks two tokens at every boolean slot; sampling vs argmax across two tokens is the same operation with extra noise.- Merged-LoRA over dynamic-LoRA in serving. Dynamic adapters are great for development (swap in seconds), but in production they add 27–140 ms of per-request overhead.