Qwen3-1.7B LoRA: strict JSON generation by schema
2 min readupdated
This LoRA adapter (small add-on to a base model for targeted tuning) is trained on top of Qwen/Qwen3-1.7B to handle specific data structures. It takes a text prompt and a JSON Schema (description of data formats) as input, and outputs a compact JSON object without extra explanations or Markdown formatting. Created as part of a university lab project on a free Colab T4, the adapter helps avoid the base model's main issue of truncating long text with indents. The tool is useful for developers who need to reliably parse language model outputs in applications.
Key features
- Increased JSON syntactic accuracy from 70.00% to 88.67% on the test set
- Improved schema compliance from 68.00% to 86.33% thanks to compact output
- Uses SFT (supervised fine-tuning) with LoRA (r=16, alpha=32) trained exclusively on assistant tokens
- Fast training on Colab T4 in 16 minutes with peak VRAM usage of 7.67 GB
What you can do
- Integrate the adapter into text processing pipelines for automated data structuring
- Use in bots and services where strict and silent JSON output is critical
- Combine with the base model Qwen/Qwen3-1.7B for local runs on consumer graphics cards
Example
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base_id = "Qwen/Qwen3-1.7B"
tok = AutoTokenizer.from_pretrained(base_id)
model = AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.float16, device_map="auto")
model = PeftModel.from_pretrained(model, "Bloody03/qwen3-1.7b-json-schema-lora").merge_and_unload().eval()
system = ("Extract information from the text and format it strictly as a JSON object conforming to the "
"provided JSON Schema. Return only valid JSON, without explanations or Markdown.")
schema = '{"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}'
user = "JSON Schema:\n" + schema + "\n\nText:\nGive me a person's name."
prompt = tok.apply_chat_template(
[{"role": "system", "content": system}, {"role": "user", "content": user}],
tokenize=False, add_generation_prompt=True, enable_thinking=False)
inputs = tok(prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
out = model.generate(**inputs, max_new_tokens=384, do_sample=False)
print(tok.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))
Read more
DetailsDataset: 2,395 examples from ChristianAzinn/json-training (synthetic, Apache-2.0)
Metrics: JSON Syntax Rate increased from 70.00% to 88.67%; Schema Compliance increased from 68.00% to 86.33%
Hardware: Colab T4, peak VRAM 7.67 GB
Limitations: synthetic English data, not suitable for precise fact extraction (may hallucinate values instead of null)










Comments