How to Fine-Tune Qwen2.5 with LoRA and Publish Your Model on Hugging Face: A Step-by-Step Guide
From the publisher’s feed, collected in the ZeroLabs newsroom.
Building a fashion attribute extractor with teacher-generated data, a 0.5B student model, and Google Colab.Fine-tuning a language model sounds complicated until you break the process into smaller steps.I recently worked on an experiment to fine-tune Qwen2.5–0.5B-Instruct for fashion attribute extraction. The objective was to take an ordinary clothing description and return structured information such as material, fit, pattern, sleeve length, and neckline.Instead of manually creating every training label, I used a larger model, Qwen2.5–7B-Instruct, to generate candidate responses. I reviewed and corrected the resulting dataset, trained the smaller model using LoRA, evaluated it against the original model, and published the adapter on Hugging Face.In this tutorial, I’ll explain the process in the order I’d recommend following it from a fresh Google Colab notebook.Source code: GitHub notebookPublished model: Fashion Attribute Extractor on Hugging FaceThe GitHub notebook records my actual experiment, including debugging, repeated executions, and recovery checkpoints. The steps below reorganize that work into a cleaner learning path. Some data-cleaning and annotation rules are simplified, so a fresh run will not necessarily reproduce the exact same dataset or scores.What are we building?Consider this product description:Relaxed-fit cotton hoodie with long sleeves, a drawstring hood, and a printed graphic on the front.We want the model to return:{ "category": "hoodie", "color": null, "material": "cotton", "fit": "relaxed-fit", "pattern": "printed", "sleeve_length": "long", "neckline": null}Why is this useful?A fashion e-commerce platform could use structured attributes for catalog enrichment, product filters, product search, and recommendation pipelines.The task is deliberately narrow. We’re not training a general-purpose fashion assistant. We’re teaching a small model to follow one specific extraction format.The seven output fields will be:category, color, material, fit, pattern, sleeve_length, and neckline.Each field must contain a string or null.We’ll provide the catalog category in the input, so category extraction here means preserving the supplied category, not independently identifying the garment.Step 1: Create a Google Colab notebook and enable a GPUOpen Google Colab and create a new notebook.From the menu, select:Runtime → Change runtime type → T4 GPU, if available.Then verify that PyTorch can access the GPU.import torchprint("PyTorch:", torch.__version__)print("CUDA available:", torch.cuda.is_available())if torch.cuda.is_available(): print("GPU:", torch.cuda.get_device_name(0))Expected output resembles:CUDA available: TrueGPU: Tesla T4I used a Tesla T4 with approximately 14.56 GB of GPU memory.A GPU is important here because we’ll load a 7B teacher model for annotation and train a 0.5B student.Google Colab runtime availability can vary.Step 2: Install the required Python packagesRun this in a new Colab cell:%pip install -q -U \ transformers \ datasets \ accelerate \ peft \ bitsandbytes \ huggingface_hub \ scikit-learnHere’s what each package does:The original notebook also used TRL, pandas, and PyArrow during preparation. The streamlined training path below uses Transformers’ Trainer directly.After installation, restart the Colab runtime if prompted.For reference, some important package versions in my successful experiment were:transformers 5.20.2datasets 5.0.1peft 0.21.2accelerate 1.15.0bitsandbytes 0.50.2If you’re reproducing the original notebook exactly, pin the versions recorded in it rather than relying on future package defaults.Step 3: Connect Google Drive to save your workColab sessions can disconnect or reset. I saved intermediate datasets, model checkpoints, and evaluation files in Google Drive.from google.colab import drivefrom pathlib import Pathdrive.mount("/content/drive")BASE_DIR = Path( "/content/drive/MyDrive/fashion-distillation")BASE_DIR.mkdir(parents=True, exist_ok=True)for folder in ["data", "labels", "student", "evaluation"]: (BASE_DIR / folder).mkdir(exist_ok=True)print("Project directory:", BASE_DIR)This step is optional, but I recommend it for experiments involving multiple data-generation and training stages.The expensive part is not always training. In my case, generating and reviewing teacher labels took substantial effort, so preserving that work was important.Step 4: Load the fashion datasetI used the H&M product dataset available on Hugging Face:Qdrant/hm_ecommerce_productsThe dataset includes product names, descriptions, and catalog metadata.We’ll start by streaming it so we don’t need to load the entire dataset into memory.from datasets import load_datasetdataset = load_dataset( "Qdrant/hm_ecommerce_products", split="train", streaming=True)for i, product in enumerate(dataset): print("Name:", product.get("prod_name")) print("Description:", product.get("detail_desc")) print("Category:", product.get("product_type_name")) print("---") if i == 4: breakA description might look like:Jersey top with narrow shoulder straps.With a catalog category:Vest topAt this stage, we’re only inspecting the dataset structure.This is worth doing before writing the training pipeline because the original dataset has more fields than our extraction task needs.Step 5: Clean and filter the product descriptionsRaw catalog data is rarely ready for fine-tuning.Possible problems include missing descriptions, repeated records, inconsistent categories, and products outside the task scope.I selected an initial subset of 5,000 records and applied several filtering stages.For a simplified starting point, we can retain garment records with nonempty descriptions and valid categories.from datasets import load_datasetstream = load_dataset( "Qdrant/hm_ecommerce_products", split="train", streaming=True)garment_categories = { "Blazer", "Blouse", "Cardigan", "Coat", "Dress", "Garment Set", "Hoodie", "Jacket", "Leggings/Tights", "Outdoor Waistcoat", "Outdoor trousers", "Polo shirt", "Shirt", "Shorts", "Skirt", "Sweater", "T-shirt", "Tailored Waistcoat", "Top", "Trousers", "Vest top"}products = []seen = set()for i, item in enumerate(stream): if i >= 5000: break description = (item.get("detail_desc") or "").strip() category = (item.get("product_type_name") or "").strip() if not description or category not in garment_categories: continue key = (category.lower(), " ".join(description.lower().split())) if key in seen: continue seen.add(key) products.append({ "input": description, "category": category })print("Filtered products:", len(products))print(products[:2])This is a simplified filter. My original experiment used additional duplicate/conflict checks and garment-specific cleaning.The original cleaned dataset contained 1,422 garment descriptions across 21 categories.The sample code above may produce a different count because it doesn’t implement every original cleaning rule.Step 6: Split the dataset before generating labelsWe need separate training and evaluation data.The reason is straightforward: if we evaluate the model on examples it has already seen during training, we may overestimate how well it generalizes.Use a reproducible split:from sklearn.model_selection import train_test_splittrain_pool, temp_pool = train_test_split( products, test_size=0.20, random_state=42, shuffle=True)validation_pool, test_pool = train_test_split( temp_pool, test_size=0.50, random_state=42)print("Training pool:", len(train_pool))print("Validation pool:", len(validation_pool))print("Test pool:", len(test_pool))This creates an approximately 80/10/10 split.My original experiment used the following counts after its full cleaning process:These larger pools were not all used for supervised student training.I generated teacher labels for an initial subset of 500 training-pool examples. After exclusions and review, 485 labeled examples remained.Those 485 examples were then divided into 436 student-training examples and 49 internal-validation examples.I kept the original outer test pool separate for the final exploratory evaluation.Step 7: Define the extraction schemaBefore asking a teacher model to generate labels, we need to decide exactly what a valid output looks like.ATTRIBUTES = [ "category", "color", "material", "fit", "pattern", "sleeve_length", "neckline"]system_prompt = """You extract structured fashion attributes from product descriptions.Return exactly one JSON object containing:category, color, material, fit, pattern,sleeve_length, neckline.Rules:- Every key must be present.- Values must be strings or null.- Use the supplied catalog category for category.- Do not invent attributes not supported by the description.- Use null when an attribute is not established.- Identify the primary garment material, not only its lining or trim.- Do not confuse waist style with overall fit.- Do not treat the presence of a hood as a neckline shape.- Return JSON only, without markdown fences or explanations."""This is a shortened, tutorial-friendly prompt. The original experiment used a longer category-aware instruction prompt, so the generated labels may differ.For strict reproduction, use the original prompt saved in the experiment’s teacher_config.json.Why does the prompt matter?Because our objective is not simply to extract plausible information. We want consistent decisions across thousands of descriptions.For example, if the description mentions a printed graphic but no color, pattern may be printed, while color should remain null.Step 8: Load the 7B teacher modelNow we’ll generate candidate training labels.The teacher model is:Qwen/Qwen2.5-7B-InstructLoading a 7B model directly in FP16 can exceed the available GPU memory on a T4. For this step, I used 4-bit quantization.import torchfrom transformers import ( AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig)teacher_id = "Qwen/Qwen2.5-7B-Instruct"quant_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)teacher_tokenizer = AutoTokenizer.from_pretrained( teacher_id)teacher_model = AutoModelForCausalLM.from_pretrained( teacher_id, quantization_config=quant_config, device_map="auto")teacher_model.eval()print("Teacher loaded")The quantized model is used for inference to generate labels. We’re not fine-tuning the teacher.Step 9: Generate structured training labelsWe’ll write a helper function that sends a product description to the teacher and parses its response.import jsondef generate_teacher_label(product): messages = [ { "role": "system", "content": system_prompt }, { "role": "user", "content": ( f"CATALOG_CATEGORY: {product['category']}\n" f"DESCRIPTION: {product['input']}" ) } ] inputs = teacher_tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ).to(teacher_model.device) with torch.inference_mode(): generated = teacher_model.generate( **inputs, max_new_tokens=200, do_sample=False, pad_token_id=teacher_tokenizer.eos_token_id ) response = teacher_tokenizer.decode( generated[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True ).strip() return json.loads(response)Test it on one record:example = { "category": "Hoodie", "input": ( "Relaxed-fit cotton hoodie with long sleeves " "and a printed graphic." )}label = generate_teacher_label(example)print(json.dumps(label, indent=2))This code assumes the teacher returns valid JSON. For a real labeling pipeline, catch parsing failures and retry or flag those records for review.In my experiment, I processed teacher predictions in batches, saved progress to Drive, and reviewed questionable labels.This is a stage where I would avoid generating thousands of labels in a single uninterrupted Colab loop. Saving after each batch protects against session disconnections.Step 10: Validate and review the teacher labelsA larger teacher model doesn’t guarantee correct training labels.Before fine-tuning the student, we need to check that the response follows the expected schema.def valid_label(label, category): if not isinstance(label, dict): return False if set(label.keys()) != set(ATTRIBUTES): return False if not all( value is None or isinstance(value, str) for value in label.values() ): return False return ( label["category"].strip().lower() == category.strip().lower() )Now generate a small labeled sample:labeled_records = []failed_records = []for product in train_pool[:20]: try: label = generate_teacher_label(product) if not valid_label(label, product["category"]): failed_records.append(product) continue labeled_records.append({ "input": product["input"], "catalog_category": product["category"], "attributes": label }) except Exception as error: failed_records.append({ **product, "error": str(error) })print("Valid labels:", len(labeled_records))print("Failed labels:", len(failed_records))Use the same pattern for subsequent batches, writing each result to a JSONL file as you proceed.Do not treat schema validity as proof of label correctness.A model may produce perfectly valid JSON with an incorrect material or an unsupported fit.During my experiment, I found issues involving material composition, category consistency, sleeve length, and patterns.I corrected these before training.The final student-training data contained 436 examples.For readers following the tutorial, I recommend reviewing the generated labels before moving forward. The original project’s corrected label files are referenced in the notebook, but were saved in Google Drive rather than embedded as a public, ready-to-run dataset.Step 11: Format the reviewed records as conversationsQwen2.5-Instruct uses a chat template.Each supervised training record should contain a system message, user message, and the desired assistant response.Assuming reviewed_records contains your checked annotations:def format_training_example(record): return { "messages": [ { "role": "system", "content": system_prompt }, { "role": "user", "content": ( f"CATALOG_CATEGORY: {record['catalog_category']}\n" f"DESCRIPTION: {record['input']}" ) }, { "role": "assistant", "content": json.dumps( record["attributes"], ensure_ascii=False ) } ] }In the original experiment, I saved this message format in two JSONL files:student/train.jsonlstudent/validation.jsonlContaining 436 and 49 records respectively.A fresh tutorial run should create these files from its own reviewed labels.For example:from sklearn.model_selection import train_test_split# Replace with the full manually reviewed label collection.reviewed_records = labeled_recordsstudent_train, student_val = train_test_split( reviewed_records, test_size=0.10, random_state=42, shuffle=True)train_messages = [ format_training_example(record) for record in student_train]val_messages = [ format_training_example(record) for record in student_val]def save_jsonl(path, rows): with open(path, "w", encoding="utf-8") as f: for row in rows: f.write(json.dumps(row, ensure_ascii=False) + "\n")save_jsonl(BASE_DIR / "student/train.jsonl", train_messages)save_jsonl(BASE_DIR / "student/validation.jsonl", val_messages)This example uses the current in-memory labeled sample. To reproduce a meaningful fine-tuning run, expand and review the label set first.Step 12: Unload the teacher and load the 0.5B studentThe teacher is no longer needed once we’ve finished preparing labels.Release GPU memory:import gcimport torchdel teacher_modelgc.collect()torch.cuda.empty_cache()Depending on Colab’s memory state, restarting the runtime may be the cleanest way to release the teacher completely.Now load the student.from transformers import AutoTokenizer, AutoModelForCausalLMstudent_id = "Qwen/Qwen2.5-0.5B-Instruct"student_tokenizer = AutoTokenizer.from_pretrained( student_id)student_tokenizer.pad_token = student_tokenizer.eos_tokenstudent_tokenizer.padding_side = "right"student_model = AutoModelForCausalLM.from_pretrained( student_id, torch_dtype=torch.float16).to("cuda")print("Student loaded")Notice the difference in how the two models were loaded.The teacher used 4-bit quantization.The student was trained with an FP16 base model and LoRA adapters.This means the student-training method in this experiment was LoRA, not QLoRA.Step 13: Attach LoRA adaptersLoRA stands for Low-Rank Adaptation.Instead of updating every weight in the base model, it introduces smaller trainable matrices into selected layers.The original model weights remain frozen.from peft import LoraConfig, get_peft_modellora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, target_modules=[ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ], task_type="CAUSAL_LM")student_model = get_peft_model( student_model, lora_config)student_model.print_trainable_parameters()My experiment had approximately 8.8 million trainable parameters, or about 1.75% of the adapted model.A small fraction of the model’s parameters was updated, while the base weights stayed frozen.Step 14: Tokenize the dataset and mask the promptThis is one of the most important steps in the entire experiment.We want the model to learn the assistant’s JSON response.We don’t need it to learn to reproduce the system instructions and user description.In causal language modeling, loss positions labeled -100 are ignored.We’ll mask the system and user tokens, leaving the assistant response available for training.First, load our saved conversations:from datasets import Datasetdef read_jsonl(path): with open(path, encoding="utf-8") as f: return [ json.loads(line) for line in f if line.strip() ]train_data = Dataset.from_list( read_jsonl(BASE_DIR / "student/train.jsonl"))val_data = Dataset.from_list( read_jsonl(BASE_DIR / "student/validation.jsonl"))Then tokenize the examples:MAX_LENGTH = 1536def tokenize_for_sft(example): messages = example["messages"] prompt_ids = student_tokenizer.apply_chat_template( messages[:2], tokenize=True, add_generation_prompt=True, return_dict=True )["input_ids"] full_ids = student_tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=False, return_dict=True )["input_ids"] assert full_ids[:len(prompt_ids)] == prompt_ids if len(full_ids) > MAX_LENGTH: raise ValueError("Sequence exceeds maximum length") labels = ( [-100] * len(prompt_ids) + full_ids[len(prompt_ids):] ) return { "input_ids": full_ids, "attention_mask": [1] * len(full_ids), "labels": labels }tokenized_train = train_data.map( tokenize_for_sft, remove_columns=train_data.column_names)tokenized_val = val_data.map( tokenize_for_sft, remove_columns=val_data.column_names)The assertion checks that the prompt tokens are an exact prefix of the complete conversation.This matters because incorrect token boundaries can cause the training loss to include unwanted prompt tokens or omit part of the answer.The original notebook included an explicit token-boundary inspection before training.Step 15: Prepare a custom data collatorTraining examples have different token lengths.A data collator pads them into batches.We’ll pad input IDs with the tokenizer’s pad token, attention masks with zero, and labels with -100.import torchfrom torch.nn.utils.rnn import pad_sequencedef sft_data_collator(features): return { "input_ids": pad_sequence( [ torch.tensor(x["input_ids"], dtype=torch.long) for x in features ], batch_first=True, padding_value=student_tokenizer.pad_token_id ), "attention_mask": pad_sequence( [ torch.tensor(x["attention_mask"], dtype=torch.long) for x in features ], batch_first=True, padding_value=0 ), "labels": pad_sequence( [ torch.tensor(x["labels"], dtype=torch.long) for x in features ], batch_first=True, padding_value=-100 ) }Why -100 for label padding?Because padding tokens are not part of the correct response. They should not contribute to the training loss.Step 16: Configure the training processNow we can configure Hugging Face’s Trainer.from transformers import TrainingArguments, Trainerstudent_model.gradient_checkpointing_enable()student_model.enable_input_require_grads()student_model.config.use_cache = Falsetraining_args = TrainingArguments( output_dir=str(BASE_DIR / "student/checkpoints"), num_train_epochs=3, per_device_train_batch_size=2, per_device_eval_batch_size=2, gradient_accumulation_steps=4, learning_rate=1e-4, weight_decay=0.01, warmup_steps=0.05, lr_scheduler_type="cosine", optim="adamw_torch", fp16=True, gradient_checkpointing=True, max_grad_norm=1.0, eval_strategy="epoch", save_strategy="epoch", logging_steps=10, save_total_limit=3, report_to="none", remove_unused_columns=False, seed=42)trainer = Trainer( model=student_model, args=training_args, train_dataset=tokenized_train, eval_dataset=tokenized_val, data_collator=sft_data_collator)Some settings worth understanding:Epochs: One epoch means the model processes the training dataset once. I used three epochs as an initial training budget.Batch size: A small batch size helps fit training into limited GPU memory.Gradient accumulation: Accumulating gradients across four batches gives an effective batch size of eight examples for weight updates.Learning rate: Controls the size of parameter updates.Gradient checkpointing: Reduces memory usage by recomputing some intermediate activations during backward propagation.Evaluation each epoch: Lets us inspect validation loss before deciding whether additional training is worthwhile.The warmup_steps=0.05 configuration was accepted by the Transformers version used in my original run as a fractional warm-up setting. If you're using a different version, verify its expected type and warm-up behavior.Step 17: Start fine-tuningOnce everything is configured:train_result = trainer.train()print(train_result)In my run, training completed in approximately 12 minutes on a Tesla T4.The recorded losses were:The training loss decreased across all three epochs.Validation loss reached its minimum at epoch 2 and rose slightly at epoch 3.I published the epoch-3 adapter, but this doesn’t establish that epoch 3 was the optimal checkpoint. Comparing checkpoint behavior and using early stopping would be useful in a follow-up experiment.Step 18: Save the LoRA adapterAfter training, save the model.adapter_dir = BASE_DIR / "student/fashion_lora_adapter"student_model.save_pretrained(str(adapter_dir))student_tokenizer.save_pretrained(str(adapter_dir))print("Adapter saved:", adapter_dir)You should find files similar to:fashion_lora_adapter/├── adapter_config.json├── adapter_model.safetensors├── tokenizer.json├── tokenizer_config.json└── chat_template.jinjaThe adapter is much smaller than a complete model checkpoint because it contains the learned LoRA weights, not another full copy of the base model.Step 19: Evaluate the fine-tuned modelA lower training loss does not necessarily mean the model produces useful responses.For this task, I wanted to measure three things:Whether responses were valid JSON.Whether they followed the required seven-field schema.Whether the extracted values matched reference attributes.For prediction, use the same chat instructions as training and deterministic decoding.student_model.eval()student_model.config.use_cache = Truedef predict_attributes(category, description): messages = [ { "role": "system", "content": system_prompt }, { "role": "user", "content": ( f"CATALOG_CATEGORY: {category}\n" f"DESCRIPTION: {description}" ) } ] inputs = student_tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ).to(student_model.device) with torch.inference_mode(): outputs = student_model.generate( **inputs, max_new_tokens=200, do_sample=False, pad_token_id=student_tokenizer.eos_token_id ) response = student_tokenizer.decode( outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True ).strip() return responseExample:response = predict_attributes( "Hoodie", "Relaxed-fit cotton hoodie with long sleeves " "and a printed graphic.")print(response)For a real evaluation, repeat this over a held-out dataset and compare each parsed response with reviewed reference labels.The exact-match metric should count malformed outputs as incorrect, rather than silently discarding them.Step 20: Compare with the original base modelFine-tuning is only meaningful if we can compare the model against its original behavior.PEFT (Parameter-Efficient Fine-Tuning) allows temporary disabling of the LoRA adapter.with student_model.disable_adapter(): base_response = predict_attributes( "Hoodie", "Relaxed-fit cotton hoodie with long sleeves " "and a printed graphic." )fine_tuned_response = predict_attributes( "Hoodie", "Relaxed-fit cotton hoodie with long sleeves " "and a printed graphic.")print("BASE MODEL:")print(base_response)print("\nFINE-TUNED MODEL:")print(fine_tuned_response)In the actual experiment, I evaluated both models over the same independent 20-product sample and saved every prediction for error analysis.These were the results:An attribute match meant that the predicted string or null exactly matched the reference value. Invalid-schema responses received zero field-match credit.These were exploratory results from 20 previously unseen product descriptions with provisional, description-grounded reference annotations. They are not independently verified production accuracy estimates.What did the model still get wrong?Across the 140 attribute comparisons, the fine-tuned model had 21 mismatches:For example, the model sometimes predicted jersey when the reference was cotton blend jersey.Other differences were primarily wording variations, such as print versus printed.The experiment improved task-specific reliability, but it also revealed why extraction evaluation needs careful label definitions and normalization.One other result surprised me: inference latency increased after fine-tuning. That reinforces the need to measure speed instead of assuming that specialization automatically makes inference faster.Step 21: Log in to Hugging FaceNow that we’ve saved the adapter, we can publish it.Create a Hugging Face account and a token with the appropriate write permissions.In Colab:from huggingface_hub import loginlogin()Colab will prompt for your token.Avoid hardcoding your Hugging Face token in a notebook that you plan to push to a public GitHub repository.Step 22: Create a Hugging Face model repositoryfrom huggingface_hub import HfApiapi = HfApi()repo_id = ( "YOUR_USERNAME/" "qwen2.5-0.5b-fashion-attribute-extractor")api.create_repo( repo_id=repo_id, repo_type="model", private=False, exist_ok=True)Replace YOUR_USERNAME with your own Hugging Face username.This creates the repository where the adapter will be hosted.Step 23: Create a model cardBefore uploading, add a README.md to the adapter folder.A model card should explain what someone is downloading and how it was trained.At minimum, include:Base model and teacher modelTask and expected input/output formatTraining method and datasetEvaluation metrics and limitationsDependencies and loading instructionsIntended useFor example:from pathlib import Pathreadme_path = Path(adapter_dir) / "README.md"model_card = """---base_model: Qwen/Qwen2.5-0.5B-Instructlibrary_name: peftpipeline_tag: text-generation---# Qwen2.5-0.5B Fashion Attribute ExtractorLoRA adapter for structured fashion attribute extraction.## TrainingTeacher: Qwen2.5-7B-InstructStudent: Qwen2.5-0.5B-InstructMethod: Supervised fine-tuning on teacher-generated labels## OutputJSON with category, color, material, fit,pattern, sleeve_length, and neckline.## LimitationsReview predictions before using them in production."""readme_path.write_text(model_card, encoding="utf-8")For an actual release, expand this template with your measured results and evaluation methodology.The model card is what visitors see when they open the repository on Hugging Face.Step 24: Upload the adapterNow upload the adapter directory.api.upload_folder( folder_path=str(adapter_dir), repo_id=repo_id, repo_type="model", commit_message="Publish fashion extraction LoRA adapter")print(f"https://huggingface.co/{repo_id}")This publishes the saved adapter files and README.I published my adapter here:minhack/qwen2.5–0.5b-fashion-attribute-extractorThe repository contains the adapter weights, PEFT configuration, tokenizer files, chat template, and model card.Step 25: Load the model back from Hugging FaceThe final step is to test whether the published adapter works independently of the original training session.import torchfrom transformers import ( AutoTokenizer, AutoModelForCausalLM)from peft import PeftModelbase_id = "Qwen/Qwen2.5-0.5B-Instruct"adapter_id = ( "minhack/" "qwen2.5-0.5b-fashion-attribute-extractor")tokenizer = AutoTokenizer.from_pretrained(base_id)base = AutoModelForCausalLM.from_pretrained( base_id, torch_dtype=torch.float16).to("cuda")model = PeftModel.from_pretrained( base, adapter_id)model.eval()The critical line is:model = PeftModel.from_pretrained(base, adapter_id)It attaches the trained adapter to the base Qwen model.You can then run inference using the chat template and system instructions defined earlier.In my final verification, the published adapter successfully generated structured JSON for a hoodie description:{ "category": "hoodie", "color": null, "material": "cotton", "fit": "relaxed-fit", "pattern": "printed", "sleeve_length": "long", "neckline": null}That confirmed that the published adapter could be downloaded and used separately from the training environment.What We learned from the experimentThis experiment wasn’t about proving that a 0.5B model is generally equivalent to a 7B model.It was about finding out whether a small model could become reliable at a narrow task using examples generated by a more capable teacher.A few lessons stood out.Dataset quality matters. Generating labels is only one part of the work. Reviewing them and defining consistent annotation rules is equally important.Structured output can be learned. The fine-tuned model was substantially more consistent about returning the required JSON format.Exact-match scores require interpretation. Semantic equivalents, partial material extraction, and genuine errors should not all be treated as the same type of mistake.Lower parameter count doesn’t guarantee lower latency. The fine-tuned model took longer to generate responses in my test setup.Publishing an adapter is different from publishing a full model. LoRA makes it possible to distribute task-specific weights while reusing an existing base model.A note on terminologyThis experiment used a 7B model to generate training labels for a 0.5B model.It is reasonable to describe this as response-based knowledge distillation, implemented through supervised fine-tuning.However, it’s not the same as classical logit-based distillation, where the student learns from the teacher’s probability distribution.We used the teacher’s generated JSON responses as training targets.ConclusionThe process can be summarised as:Dataset → Clean and split → Generate teacher labels → Review labels → Format conversations → Attach LoRA → Fine-tune student → Evaluate → Save adapter → Publish on Hugging FaceThe most important part isn’t the number of training epochs or the size of the adapter. It’s making sure the task, target outputs, data quality, and evaluation criteria are well defined.CONNECT @ LinkedIn , SynthloomHow to Fine-Tune Qwen2.5 with LoRA and Publish Your Model on Hugging Face: A Step-by-Step Guide was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.