Amirhossein75 commited on
Commit
536df93
·
2 Parent(s): 2790246 da4913e

Merge remote-tracking branch 'origin/main'

Browse files
Files changed (1) hide show
  1. README.md +264 -0
README.md ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ # For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
3
+ # Doc / guide: https://huggingface.co/docs/hub/model-cards
4
+ {
5
+ "library_name": "peft",
6
+ "pipeline_tag": "text-generation",
7
+ "license": "llama3.2",
8
+ "tags": [
9
+ "LoRA",
10
+ "QLoRA",
11
+ "instruction-tuning",
12
+ "text-classification",
13
+ "peft",
14
+ "transformers",
15
+ "trl",
16
+ "bitsandbytes",
17
+ "base_model:adapter:meta-llama/Llama-3.2-1B"
18
+ ],
19
+ "base_model": "meta-llama/Llama-3.2-1B",
20
+ "datasets": ["real-jiakai/arxiver-with-category"],
21
+ "language": ["en"],
22
+ "widget": [
23
+ {
24
+ "text": "Classify the text into ['cs.CL','cs.CV','cs.LG','hep-ph','quant-ph'] and return the answer as the exact text label.\ntext: Quantum entanglement in photonics\nlabel:"
25
+ },
26
+ {
27
+ "text": "Classify the text into ['cs.CL','cs.CV','cs.LG','hep-ph','quant-ph'] and return the answer as the exact text label.\ntext: Vision transformer achieves state-of-the-art on ImageNet\nlabel:"
28
+ }
29
+ ]
30
+ }
31
+
32
+ ---
33
+
34
+ # Model Card for LLM Instruction‑Tuning for Text Classification (LoRA + QLoRA)
35
+
36
+ <!-- Provide a quick summary of what the model is/does. -->
37
+
38
+ This repository provides code and configuration to fine‑tune a decoder‑only LLM (default: `meta-llama/Llama-3.2-1B`) for **instruction‑style text classification** using **LoRA/QLoRA**. Rather than training a task‑specific classifier head, the project formulates classification as a short instruction → answer generation task and evaluates by **exact string match** against the label. It includes simple training/inference scripts, a 5‑label arXiv‑style demo, and optional Amazon SageMaker entrypoints.
39
+
40
+ ## Model Details
41
+
42
+ ### Model Description
43
+
44
+ <!-- Provide a longer summary of what this model is. -->
45
+
46
+ This project instruction‑tunes a base, decoder‑only LLM with **LoRA adapters** loaded in **4‑bit NF4** precision for memory‑efficient training and inference. Supervised fine‑tuning is performed with TRL’s `SFTTrainer`. Prompts ask the model to “return the answer as the exact text label,” so predictions are decoded as plain text and compared by string match.
47
+
48
+ - **Developed by:** Amirhossein Yousefi (GitHub: `amirhossein-yousefi`)
49
+ - **Model type:** Decoder‑only LLM fine‑tuned with LoRA for single‑label text classification via instruction‑following
50
+ - **Language(s) (NLP):** English by default (demo dataset uses arXiv titles/abstracts); broader multilingual coverage depends on the chosen base model
51
+ - **License:** The repository itself does not include an explicit OSS license; the **base model** `meta-llama/Llama-3.2-1B` is governed by the **Llama 3.2 Community License**. You must accept and comply with Meta’s license to access and use the weights.
52
+ - **Finetuned from model :** `meta-llama/Llama-3.2-1B` (configurable)
53
+
54
+ ### Model Sources
55
+
56
+ <!-- Provide the basic links for the model. -->
57
+
58
+ - **Repository:** https://github.com/amirhossein-yousefi/LLM-Instruction-Tuning-Text-Classification
59
+ - **Demo :** The repo includes an arXiv‑style 5‑label demo and example results; no hosted demo is provided.
60
+
61
+ ## Uses
62
+
63
+ ### Direct Use
64
+
65
+ - Fine‑tune LoRA adapters on your own CSV dataset for **single‑label text classification** (e.g., topic/category detection) using the provided `scripts/train.py`.
66
+ - Run inference/evaluation with `scripts/predict.py` to generate deterministic label strings and compute **accuracy**, **micro/macro F1**, a **classification report**, and a **confusion matrix**.
67
+ - Optional **Amazon SageMaker** utilities let you run managed training and deploy a real‑time endpoint with the LoRA adapters attached at load time.
68
+
69
+ ### Downstream Use
70
+
71
+ - Integrate the trained LoRA adapters into applications where explainable, instruction‑driven classification is helpful (e.g., routing, tagging, moderation).
72
+ - Swap the base model (any compatible decoder‑only LLM on the Hugging Face Hub) and re‑train with the same prompt template.
73
+ - Extend label sets without architectural changes—only prompt/label lists need to be updated.
74
+
75
+ ### Out-of-Scope Use
76
+
77
+ - **CPU‑only** training/inference with this repo as‑is (4‑bit `bitsandbytes` path expects NVIDIA CUDA GPUs).
78
+ - **Multi‑label** classification (comma‑separated outputs) is not implemented out of the box (listed as a roadmap idea).
79
+ - **Open‑domain generation** or safety‑critical decision‑making; this project focuses on label selection with short inputs.
80
+
81
+ ## Bias, Risks, and Limitations
82
+
83
+ - Outputs mirror biases in the **training corpus** you provide and in the **base model**. If your labels or examples are imbalanced or ambiguous, the model may propagate that bias.
84
+ - Exact‑match decoding can be brittle to **tokenization/typo** effects—ensure labels are short, canonical strings and restrict the decoding space.
85
+ - The base Llama 3.2 model has its own safety limitations and license‑based usage constraints (e.g., attribution and acceptable‑use provisions).
86
+ - The demo dataset is limited to **5 arXiv‑style labels** and relatively short academic texts; generalizing beyond this domain requires additional data.
87
+
88
+ ### Recommendations
89
+
90
+ - Curate balanced datasets; consider **stratified splits** and per‑class metrics.
91
+ - Keep **temperature = 0.0** for deterministic label decoding; constrain generation length (e.g., `max_new_tokens=8`).
92
+ - Validate robustness with **label synonyms/aliases** and adversarial cases; consider post‑processing that maps variants to canonical labels.
93
+ - Review and comply with the **Llama 3.2 Community License** (and any other upstream licenses) when distributing adapters/derivatives.
94
+
95
+ ## How to Get Started with the Model
96
+
97
+ **Install & train**
98
+
99
+ ```bash
100
+ python -m venv .venv
101
+ source .venv/bin/activate # Windows: .venv\Scripts\Activate.ps1
102
+ pip install --upgrade pip
103
+ pip install -r requirements.txt
104
+
105
+ # If the base model is gated, export an HF token
106
+ export HF_TOKEN=YOUR_HF_ACCESS_TOKEN
107
+
108
+ # One‑command training on CSVs
109
+ python scripts/train.py --base_path dataset --train_file train.csv --val_file validation.csv --test_file test.csv --label_column label_name --text_fields title abstract --base_model_name meta-llama/Llama-3.2-1B --output_dir llama-3.2-1b-arxiver-lora
110
+ ```
111
+
112
+ **Inference & evaluation**
113
+
114
+ ```bash
115
+ python scripts/predict.py --base_path dataset --test_file test.csv --base_model_name meta-llama/Llama-3.2-1B --output_dir llama-3.2-1b-arxiver-lora --save_csv predictions.csv
116
+ ```
117
+
118
+ **SageMaker **
119
+
120
+ ```bash
121
+ # Train a managed job
122
+ python sagemaker/train_sm.py --source_dir . --dataset_dir dataset --train_file train.csv --val_file validation.csv --test_file test.csv --label_column label_name --text_fields title abstract --base_model_id meta-llama/Llama-3.2-1B --instance_type ml.g5.2xlarge --instance_count 1
123
+
124
+ # Deploy a real‑time endpoint
125
+ python sagemaker/deploy_sm.py --training_job_name <your-job> --base_model_id meta-llama/Llama-3.2-1B --instance_type ml.g5.2xlarge --default_labels_json '["cs.CL","cs.CV","cs.LG","hep-ph","quant-ph"]'
126
+ ```
127
+
128
+ ## Training Details
129
+
130
+ ### Training Data
131
+
132
+ - Expected input: three CSV files under a base path: `train.csv`, `validation.csv`, `test.csv`.
133
+ - Required columns: a **label** column (default `label_name`) and one or more text fields (defaults: `title`, `abstract`). Missing/blank text fields are skipped; text fields are concatenated with punctuation.
134
+ - The repository ships utilities to prepare a **5‑class arXiv‑style demo** (labels: `['cs.CL','cs.CV','cs.LG','hep-ph','quant-ph']`).
135
+
136
+ ### Training Procedure
137
+
138
+ #### Preprocessing
139
+
140
+ - Prompts are constructed as short instruction → answer pairs:
141
+ - **Train:** includes the gold label after `label:`.
142
+ - **Inference:** leaves `label:` empty and decodes the generated label.
143
+
144
+ #### Training Hyperparameters
145
+
146
+ - **Training regime:** mixed precision with `fp16=True`, `tf32=True`; 4‑bit NF4 quantization with bfloat16 compute (QLoRA‑style).
147
+ - **Selected defaults (single‑GPU):**
148
+ - `num_train_epochs=1`
149
+ - `per_device_train_batch_size=8`, `per_device_eval_batch_size=8`
150
+ - `gradient_accumulation_steps=2` (effective 16 per step, per device)
151
+ - `learning_rate=2e-4`, `weight_decay=1e-3`, `warmup_ratio=0.03`
152
+ - `logging_steps=10`, `evaluation_strategy="epoch"`, `save_strategy="epoch"`, `save_total_limit=2`
153
+ - LoRA: `r=2`, `alpha=2`, `dropout=0.0`
154
+ - Quantization: `load_in_4bit=True`, `bnb_4bit_quant_type="nf4"`, `bnb_4bit_compute_dtype="bfloat16"`, `bnb_4bit_use_double_quant=True`
155
+ - Generation (eval): `temperature=0.0`, `max_new_tokens=8`, `do_sample=False`
156
+
157
+ #### Speeds, Sizes, Times
158
+
159
+ - Example environment: Laptop RTX 3080 Ti (16 GB VRAM), CUDA 12.9, PyTorch 2.8.0+cu129.
160
+ - Example run stats: ~6,314 seconds wall‑clock training, with TensorBoard logs under the run directory.
161
+ - Total training FLOPs (example): ~3.69e16 (as reported by the training logs).
162
+
163
+ ## Evaluation
164
+
165
+ ### Testing Data, Factors & Metrics
166
+
167
+ #### Testing Data
168
+
169
+ - The example evaluation uses the provided arXiv‑style 5‑label test split.
170
+
171
+ #### Factors
172
+
173
+ - Per‑class metrics are reported for `cs.CL`, `cs.CV`, `cs.LG`, `hep-ph`, `quant-ph`.
174
+
175
+ #### Metrics
176
+
177
+ - Accuracy, micro F1, macro F1, per‑class precision/recall/F1, and a confusion matrix.
178
+
179
+ ### Results
180
+
181
+ - **Overall:** Accuracy 93.8%, Micro‑F1 0.938, Macro‑F1 0.950.
182
+ - **Per‑class (Precision / Recall / F1 / Support):**
183
+ - `cs.CL`: 0.914 / 0.963 / 0.938 / 432
184
+ - `cs.CV`: 0.935 / 0.923 / 0.929 / 545
185
+ - `cs.LG`: 0.917 / 0.890 / 0.903 / 536
186
+ - `hep-ph`: 0.994 / 0.988 / 0.991 / 164
187
+ - `quant-ph`: 0.986 / 0.990 / 0.988 / 293
188
+
189
+ #### Summary
190
+
191
+ The LoRA‑tuned 1B parameter Llama 3.2 model achieves strong performance on short academic texts while keeping training/inference affordable due to 4‑bit quantization. Performance is consistent across most classes, with particularly high scores for physics categories.
192
+
193
+ ## Model Examination
194
+
195
+ - The repo includes utilities for a **classification report** and **confusion matrix**. Inspect misclassifications to refine label definitions or add examples. Consider probing sensitivity to prompt wording.
196
+
197
+ ## Environmental Impact
198
+
199
+ *(Approximate; depends on your hardware and run length.)*
200
+ Use the [MLCO2 Impact calculator](https://mlco2.github.io/impact#compute) with your GPU model, power draw, and wall‑clock runtime.
201
+
202
+ - **Hardware Type:** Single NVIDIA GPU (example: RTX 3080 Ti Laptop 16 GB)
203
+ - **Hours used:** ~1.75 hours (example)
204
+
205
+ ## Technical Specifications
206
+
207
+ ### Model Architecture and Objective
208
+
209
+ - **Architecture:** Decoder‑only Transformer (Llama 3.2 family when using the default base)
210
+ - **Objective:** Supervised instruction‑tuning for **single‑label classification** via generative decoding with exact‑match evaluation
211
+ - **Context length:** 512 tokens (config default; pass explicitly to trainer to ensure enforcement)
212
+
213
+ ### Compute Infrastructure
214
+
215
+ #### Hardware
216
+
217
+ - NVIDIA CUDA GPU required for 4‑bit `bitsandbytes` training/inference
218
+ (CPU‑only runs are not supported by the included scripts).
219
+
220
+ #### Software
221
+
222
+ - Python ≥ 3.10, PyTorch, `transformers`, `trl`, `peft`, `bitsandbytes`, `accelerate`, and standard scientific Python packages.
223
+ - Optional: Astral’s `uv` for faster, reproducible dependency management (the repo also ships `requirements.txt`).
224
+
225
+ ## Citation
226
+
227
+ If you use this repository, please cite the GitHub project and the base model as appropriate.
228
+
229
+ **BibTeX (project):**
230
+ ```bibtex
231
+ @software{yousefi_2025_llm_instruction_tuning_text_classification,
232
+ author = {Yousefi, Amirhossein},
233
+ title = {LLM Instruction-Tuning for Text Classification (LoRA + QLoRA)},
234
+ year = {2025},
235
+ publisher = {GitHub},
236
+ url = {https://github.com/amirhossein-yousefi/LLM-Instruction-Tuning-Text-Classification}
237
+ }
238
+ ```
239
+
240
+ **APA (project):**
241
+ Yousefi, A. (2025). *LLM Instruction‑Tuning for Text Classification (LoRA + QLoRA)*. GitHub. https://github.com/amirhossein-yousefi/LLM-Instruction-Tuning-Text-Classification
242
+
243
+ **Base model:** Meta AI. (2024). *Llama 3.2‑1B* [Computer software]. Meta. https://huggingface.co/meta-llama/Llama-3.2-1B
244
+
245
+ ## Glossary
246
+
247
+ - **LoRA:** Low‑Rank Adapters for parameter‑efficient fine‑tuning.
248
+ - **QLoRA:** LoRA training with quantized base weights (typically 4‑bit NF4) and higher‑precision compute.
249
+ - **SFT:** Supervised Fine‑Tuning.
250
+ - **Exact‑match decoding:** Evaluates whether the generated label text exactly matches the gold label string.
251
+
252
+ ## More Information
253
+
254
+ - Amazon SageMaker scripts are included for managed training and deployment.
255
+ - Roadmap ideas include multi‑label support and few‑shot exemplars in prompts.
256
+
257
+ ## Model Card Authors
258
+
259
+ - Drafted by: ChatGPT (based on the repository’s README and code structure)
260
+ - Repository author: Amirhossein Yousefi
261
+
262
+ ## Model Card Contact
263
+
264
+ - Open an issue on the GitHub repository for questions or contributions.