Run this model with HF Jobs
Run lukashm/LitLex-Llama-LT-v1 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/lukashm/LitLex-Llama-LT-v1. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/lukashm/LitLex-Llama-LT-v1 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/lukashm/LitLex-Llama-LT-v1. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/lukashm/LitLex-Llama-LT-v1. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use lukashm/LitLex-Llama-LT-v1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use lukashm/LitLex-Llama-LT-v1 with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("unsloth/llama-3-8b-bnb-4bit") model = PeftModel.from_pretrained(base_model, "lukashm/LitLex-Llama-LT-v1") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Unsloth Desktop
⚖️ LitLex-Llama-LT-v1: Lithuanian Legal AI
Built with Meta Llama 3
LitLex v1 is a LoRA adapter for Meta Llama 3 8B, trained on 498 Lithuanian question and answer pairs about the Code of Administrative Offences of the Republic of Lithuania (Administracinių nusižengimų kodeksas, ANK). It is a small personal experiment, not a tested legal tool. It mostly repeats fines it saw during training and its answers are often wrong, so please do not use it for legal advice.
Code and data: github.com/lukamaga/LitLex-Llama-LT-AI
Quick facts
| Item | Value |
|---|---|
| Base model | unsloth/llama-3-8b-bnb-4bit, a 4-bit (NF4) version of Meta Llama 3 8B. This is the pretrained base model, not the Instruct one |
| What this repo contains | A LoRA adapter (PEFT) and the Llama 3 tokenizer files. It is not a standalone model: you need the base weights to run it |
| Method | QLoRA: LoRA trained on top of the 4-bit base with Unsloth and TRL's SFTTrainer |
| Adapter size | 167,772,160 parameters (about 2.1% of the 8.03B base), stored in fp32, 671 MB |
| Language | Lithuanian |
| Training data | 498 question and answer pairs generated with GPT-4o from the ANK text, not reviewed before training |
| Law version | ANK consolidated version valid from 2026-01-12 to 2026-03-31 |
| Evaluation | None. There is no held-out test set |
| License | Meta Llama 3 Community License (llama3). The code on GitHub is MIT |
| Author | Lukash Magalinski |
| Built | January 2026 |
What it can and cannot do
What it does reasonably well:
- It answers short Lithuanian questions like "Kokia bauda už ...?" in the same style as its training answers, usually "Pagal ANK N str., bauda yra nuo X iki Y eurų".
- When a question is close to one in the training set, it often gives the right article and fine range. This is recall of memorized answers, not an understanding of the law.
What it does not do:
- It does not handle reworded questions reliably. Of the four example answers in the GitHub README, two are wrong (see Example outputs).
- It does not reason about a specific situation or calculate anything. It repeats ranges from the Code, and it often leaves out extra sanctions such as license suspension.
- Its fine-tuning data covers only the ANK, in its January 2026 version. It was not trained on the Criminal Code (BK), the Civil Code (CK) or the Road Traffic Rules (KET).
- It does not look up or quote the official text, so it cannot show where an answer comes from.
- It is not a chat model. The base model is not instruction-tuned and has no chat template, so it only works with the prompt format shown below. Other formats give rambling or broken output.
How to run it
Prompt format
The model was trained on this exact Alpaca template, with an English header and a Lithuanian question:
Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{question}
### Response:
- The prompt ends with
### Response:and a newline. The answer follows and ends with<|end_of_text|>. - The tokenizer adds
<|begin_of_text|>on its own, so do not add it by hand. - Do not use
tokenizer.apply_chat_template. There is no chat template, and<|eot_id|>was never used in training. - Use
do_sample=Falseif you want the same answer every time. Without it, the base model's generation config samples with temperature 0.6 and top_p 0.9, and the answer changes between runs. With greedy decoding, transformers prints a warning thattemperatureandtop_pare ignored. It is harmless. - Decode only the newly generated tokens with
skip_special_tokens=True. This is simpler than splitting the full output on### Response:, which is whatsrc/test.pydoes.
Option A: Unsloth on an NVIDIA GPU
You need an NVIDIA GPU with about 7 GB of VRAM, for example a T4 on Colab or Kaggle. This is the same loading setup as src/test.py in the GitHub repo.
pip install unsloth
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="lukashm/LitLex-Llama-LT-v1",
max_seq_length=2048,
dtype=None,
load_in_4bit=True,
)
FastLanguageModel.for_inference(model)
prompt = """Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{}
### Response:
"""
question = "Kokia bauda gresia už greičio viršijimą daugiau kaip 50 km/h?"
inputs = tokenizer(prompt.format(question), return_tensors="pt").to("cuda")
output = model.generate(**inputs, max_new_tokens=256, do_sample=False)
answer = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(answer.strip())
Option B: transformers, peft and bitsandbytes on an NVIDIA GPU
Same hardware, without Unsloth. The 4-bit base is about a 5.7 GB download.
pip install -U "transformers>=4.56" "peft>=0.18" accelerate bitsandbytes
import torch
import bitsandbytes as bnb
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
base_id = "unsloth/llama-3-8b-bnb-4bit"
adapter_id = "lukashm/LitLex-Llama-LT-v1"
tokenizer = AutoTokenizer.from_pretrained(adapter_id)
base = AutoModelForCausalLM.from_pretrained(base_id, device_map="auto", dtype=torch.float16)
for module in base.modules():
if isinstance(module, bnb.nn.Linear4bit):
module.compute_dtype = torch.float16
model = PeftModel.from_pretrained(base, adapter_id)
prompt = """Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{}
### Response:
"""
question = "Kokia bauda gresia už greičio viršijimą daugiau kaip 50 km/h?"
inputs = tokenizer(prompt.format(question), return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=256, do_sample=False)
answer = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(answer.strip())
About the loop: the base checkpoint is already quantized, and its config sets the 4-bit compute dtype to bfloat16. A BitsAndBytesConfig passed to from_pretrained is ignored for pre-quantized models, and the T4 has no native bf16, so the loop switches the 4-bit layers to fp16, which matches the float16 dtype Unsloth uses on a T4. On Ampere or newer GPUs (A100, L4, RTX 30 and 40 series) you can drop the loop and load with dtype=torch.bfloat16.
The dtype= argument needs transformers 4.56 or newer (older versions call it torch_dtype).
Option C: Apple Silicon (MPS) or CPU
No bitsandbytes here. This option loads unsloth/llama-3-8b, the unquantized version of the same base, which is not gated (unlike meta-llama/Meta-Llama-3-8B).
pip install -U torch "transformers>=4.56" "peft>=0.18" accelerate
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
base_id = "unsloth/llama-3-8b"
adapter_id = "lukashm/LitLex-Llama-LT-v1"
device = "mps" if torch.backends.mps.is_available() else "cpu"
dtype = torch.float16 if device == "mps" else torch.bfloat16
tokenizer = AutoTokenizer.from_pretrained(adapter_id)
base = AutoModelForCausalLM.from_pretrained(base_id, dtype=dtype, device_map=device)
model = PeftModel.from_pretrained(base, adapter_id)
prompt = """Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{}
### Response:
"""
question = "Kokia bauda gresia už greičio viršijimą daugiau kaip 50 km/h?"
inputs = tokenizer(prompt.format(question), return_tensors="pt").to(device)
output = model.generate(**inputs, max_new_tokens=256, do_sample=False)
answer = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(answer.strip())
- Download: about 16.1 GB for the base plus 671 MB for the adapter.
- Memory: about 18 GB in total. On a Mac, 32 GB of unified memory is the practical minimum, 24 GB is borderline and 16 GB will not fit. On macOS 14 or later,
torch.bfloat16also works on MPS. - CPU works too and needs about the same 18 GB of RAM, but it is very slow.
- The adapter was trained against the 4-bit weights, so answers on this full-precision base can differ slightly from options A and B.
Example outputs
These are the four answers I published in the GitHub README. They were produced with src/test.py, which uses the default sampling settings, so running the same questions again can give different text.
1. Speeding by more than 50 km/h: correct, but incomplete
Q: Kokia bauda gresia už greičio viršijimą daugiau kaip 50 km/h?
A: Pagal ANK 416 str., bauda yra nuo 450 iki 550 eurų vairuotojams ir nuo 450 iki 700 eurų asmenims neturintiems teisės vairuoti.
The ranges match Art. 416 part 6. The answer leaves out that part 7 also makes a license suspension of 1-6 months mandatory. It is exactly the answer of one training pair, whose question is worded almost the same.
2. Neighbors making noise at night: wrong
Q: Ką daryti, jei kaimynai triukšmauja naktį? Kokia bauda?
A: Pagal ANK 299 str. 1 dalį, administracinėn atsakomybėn traukiami asmenys, kurie padarė pakartotinį nusižengimą, turi sumokėti baudą nuo 140 iki 300 eurų.
Art. 299 is about fishery products. The right article is Art. 488 part 1, which covers noise in residential premises in the evening (19:00-22:00) and at night (22:00-07:00): 80-200 EUR for individuals and 200-300 EUR for heads of legal entities. The training data has a correct Art. 488 pair, but this question is worded differently and the model made up an answer.
3. Illegal work: correct
Q: Kokia bauda už nelegalų darbą?
A: Pagal ANK 95 straipsnį, bauda darbdaviui - fiziniam asmeniui yra nuo 2000 iki 5000 eurų, o darbdavio - juridinio asmens vadovui ar kitam atsakingam asmeniui - nuo 1500 iki 5000 eurų.
This matches Art. 95 part 1. The question is identical to one in the training set. The answer does not mention the 5,000-6,000 EUR fine for a repeat offense (part 2).
4. Noise in the evening: wrong
Q: Kokia bauda už triukšmavimą vakaro metu?
A: Pagal Lietuvos Respublikos administracinių nusižengimų kodeksą, triukšmavimas vakaro metu yra numatyta kaip viena iš šiurkštų socių teisės aktų, todėl bauda asmenims nuo 60 iki 140 eurų, o juridinių asmenų vadovams ar kitiems atsakingiems asmenims - nuo 140 iki 300 eurų.
No article, broken Lithuanian and wrong amounts. The correct answer is again Art. 488 part 1: 80-200 EUR and 200-300 EUR. Both ranges are common in the training answers (60-140 EUR in 8 of them, 140-300 EUR in 21), and the exact pair is the answer for Art. 47 part 1 on radiation safety, which is probably where it came from.
So 2 of 4 are right, and both are copies or near copies of training pairs.
How I built it
Data
- I used the consolidated ANK text from the Register of Legal Acts (TAR, via e-seimas.lrs.lt). The file header reads "Suvestinė redakcija nuo 2026-01-12 iki 2026-03-31" (consolidated version valid from 2026-01-12 to 2026-03-31). The latest amendment listed in it is Nr. XV-714 of 2025-12-23. The text is about 1.4 million characters long and is in the GitHub repo as
data/ank_raw.txt. dataset_builder.pycuts the text into chunks of 15,000 characters with no overlap, which gives 94 chunks. The cuts ignore article boundaries, so some articles end up split between two chunks.- Each chunk was sent to GPT-4o through the OpenAI API with a short Lithuanian prompt asking for 3-6 question and answer pairs about offenses and fines, returned as JSON. The temperature was left at the API default.
- This gave 498 pairs (about 5.3 per chunk), saved as
data/ank_dataset.jsonwith the keysInstructionandOutput. Questions are 30-169 characters long (mean 80), answers 33-417 characters (mean 136).
There was no manual review or filtering step. What GPT-4o returned went straight into training.
Training
I used Unsloth so that QLoRA training of an 8B model would fit on a single Tesla T4. The script is src/finetune.py. It uses paths like ../data/ank_dataset.json, as does src/dataset_builder.py, so run both from inside src/.
| Setting | Value |
|---|---|
| LoRA rank / alpha / dropout | 64 / 32 / 0 (scaling 0.5), bias none, no rsLoRA or DoRA |
| Target modules | q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj in all 32 layers |
| Steps | 500 |
| Batch size | 2 per device, gradient accumulation 4, effective batch 8 |
| Epochs | about 8 (500 steps x 8 = 4,000 samples over 498 pairs) |
| Tokens seen | about 503k in total, about 62.6k per epoch |
| Learning rate | 2e-4, 20 warmup steps, then linear decay to 0 |
| Optimizer | adamw_8bit, weight decay 0.01 |
| Max sequence length | 2048 (actual training sequences are 56-245 tokens, median 121) |
| Packing | off |
| Gradient checkpointing | Unsloth |
| Seed | 3407 |
| Precision | Unsloth loaded the base in float16 (dtype=None, and the T4 has no native bf16). The Trainer's fp16/bf16 flag came from torch.cuda.is_bf16_supported() at run time and was not logged |
| Hardware | one NVIDIA Tesla T4 |
| Saved with | peft 0.18.0 |
Each training example is the Alpaca prompt with the question and answer filled in, followed by the EOS token <|end_of_text|>. The loss is computed over the whole sequence, prompt included, so about 21% of the training tokens are the fixed English template. There was no validation split.
Training loss
| Step | Training loss |
|---|---|
| 1 | 2.7105 |
| 10 | 1.4465 |
| 120 | 0.5252 |
| 253 | 0.2463 |
| 350 | 0.1577 |
| 480 | 0.0840 |
| 500 | 0.0897 |
These are single-step values, each from one batch of 8 examples, and they include the prompt tokens. The full log is not in the repo. A loss under 0.1 after 8 epochs on 498 examples mostly shows that the model memorized its training set. It does not say how often the answers are correct.
Training data quality
In October 2026 the dataset was checked against the ANK text: automatic checks over all 498 pairs, plus a closer look at a random sample of 40 pairs. The check scripts are not in the repo. The main findings:
- The example from the prompt leaked into the data. The generation prompt used "Kokia bauda už chuliganišką vairavimą?" with "Pagal ANK 420 str., bauda yra ..." as a format example. That question appears 4 times with 3 different answers: two are the literal placeholder, one says the text is unrelated, and only one is correct (Art. 420 part 2, 450-550 EUR).
- Placeholders and non-answers. At least 5 outputs are placeholders ending in "..." or refusals (rows 188, 215, 375, 376 and 377, counting from 0).
- Wrong article numbers. In long articles, GPT-4o sometimes used a part number as the article number. For example, several questions about waste handling cite "ANK 29" or "ANK 36", which are really parts of Art. 247. A rough check that compares each cited article with the part of the Code that the neighboring pairs come from (the source chunk of each pair was not saved) flags 63 of 414 citations (15.2%) as suspicious.
- Flattened superscripts. The text was copied from a PDF, where an article like 342¹ turns into "3421". 36 answers cite numbers in this form, and the model learned to write them that way.
- Fine ranges. Of 295 answers that cite an article and give a range a script can parse, 261 (88.5%) have every range present in the cited article. Where a specific part is cited, 154 of 164 (93.9%) match that part. Some of the rest merge two parts into one range, for example 400-800 EUR and 800-1,200 EUR became 400-1,200 EUR.
- Spot check. In a random sample of 40 pairs that cite an article, 32 (80%) were fully correct: right article, right fine or fact, and an actual answer to the question. The sample skips the 84 answers that cite no article, and those contain most of the placeholders and meta answers, so the share for the whole set is likely lower.
- Coverage. The pairs follow the Code from start to end, so each topic shows up roughly in proportion to the length of its chapter. About 80% of the questions ask about a fine. Of the 414 answers that cite an article, by the chapter of the first cited article: procedure 16.7%; transport (including air, rail and sea) 15.7%; environment 14.7%; trade, finance and tax 11.4%; public order 3.1%; labor 0.5%; everything else 37.9%. The answers cite 329 different articles, about 42% of the 787 in the Code, and 268 of them are cited only once. The last 31 pairs come from the annex and amendment history at the end of the file and are mostly questions like "what changed in Art. X".
- Number style. 257 answers write amounts in Lithuanian words, as the Code does, and 106 use digits.
An earlier version of this card said the data focused on traffic and public order offenses. That was not accurate.
Limitations
- No evaluation. There is no held-out test set and no benchmark. The only results are the training loss and the four examples above.
- Memorization. The model does best on questions it has seen. Reworded questions often get a confident answer with the wrong article or the wrong amount.
- Wrong citations. It can cite an article that does not match the topic, write superscript articles in the flattened form ("3421" for 342¹), or merge two ranges into one.
- Frozen law version. It reflects the ANK consolidated version valid from 2026-01-12 to 2026-03-31. The Code has been amended since then (a new consolidated version applies from 2026-04-01), so some fines may be out of date.
- Errors in the training data. The pairs were generated by GPT-4o and not reviewed before training (the checks above were done afterwards). Placeholders, duplicates and wrong article numbers are in the training set, and the model learned them too.
- Lithuanian only. All training questions and answers are in Lithuanian.
- Not legal advice. Do not rely on it for real cases. Check the official text on e-seimas.lrs.lt or ask a lawyer. Offering it as a legal service without a license would also break the Llama 3 Acceptable Use Policy, which prohibits the unlicensed practice of law.
What comes next
I'm working on a new version that finds the relevant articles in the official ANK text and cites them in its answers, instead of relying on what the model memorized.
License
- This adapter is fine-tuned from Meta Llama 3 8B, and the repo also includes the Llama 3 tokenizer files. Both are covered by the Meta Llama 3 Community License (a copy is in
LICENSEin this repo, and the original is on GitHub), and use must follow the Llama 3 Acceptable Use Policy. - Meta Llama 3 is licensed under the Meta Llama 3 Community License, Copyright © Meta Platforms, Inc. All Rights Reserved.
- An earlier version of this card listed MIT as the license. That was wrong for the weights. MIT applies only to the source code in the GitHub repo.
- The ANK is a legal act, and legal acts are not protected by copyright in Lithuania (Art. 5(2) of the Law on Copyright and Related Rights). The text used is the consolidated version valid from 2026-01-12 to 2026-03-31, from the Register of Legal Acts (Law No. XII-1869, first published TAR 2015-07-10, i. k. 2015-11216).
- The training pairs were generated with OpenAI's GPT-4o.
Links
- GitHub repo: lukamaga/LitLex-Llama-LT-AI
src/dataset_builder.py: generates the pairs with GPT-4osrc/finetune.py: trainingsrc/test.py: asks the four example questionsdata/: the ANK text and the 498 training pairs
- Base model: unsloth/llama-3-8b-bnb-4bit
Citation
@misc{magalinski2026litlex,
author = {Magalinski, Lukash},
title = {LitLex v1: a QLoRA adapter for questions about the Lithuanian Code of Administrative Offences},
year = {2026},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/lukashm/LitLex-Llama-LT-v1}}
}
- Downloads last month
- 12
Model tree for lukashm/LitLex-Llama-LT-v1
Base model
meta-llama/Meta-Llama-3-8B