Text Generation
PEFT
Safetensors
English
pyspark
apache-spark
qwen2.5-coder
qlora
lora
code-generation
data-engineering
fine-tuned
Instructions to use AaronTekle/PySparkQwen with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use AaronTekle/PySparkQwen with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-Coder-1.5B-Instruct") model = PeftModel.from_pretrained(base_model, "AaronTekle/PySparkQwen") - Notebooks
- Google Colab
- Kaggle
Update README.md
Browse files
README.md
CHANGED
|
@@ -1,37 +1,18 @@
|
|
| 1 |
-
---
|
| 2 |
-
language:
|
| 3 |
-
- en
|
| 4 |
-
base_model:
|
| 5 |
-
- Qwen/Qwen3-1.7B
|
| 6 |
-
pipeline_tag: text-generation
|
| 7 |
-
library_name: peft
|
| 8 |
-
tags:
|
| 9 |
-
- pyspark
|
| 10 |
-
- apache-spark
|
| 11 |
-
- qwen3
|
| 12 |
-
- qlora
|
| 13 |
-
- lora
|
| 14 |
-
- code-generation
|
| 15 |
-
- fine-tuned
|
| 16 |
-
- qwen
|
| 17 |
-
---
|
| 18 |
-
# PySparkQwen (PySparkQwen-QLoRA, [Qwen/Qwen3-1.7B](https://huggingface.co/Qwen/Qwen3-1.7B) )
|
| 19 |
|
| 20 |
-
QLoRA fine-tuning of [**Qwen/
|
| 21 |
|
| 22 |
-
PySparkQwen is a
|
| 23 |
|
| 24 |
-
|
| 25 |
|
| 26 |
-
- PySpark
|
| 27 |
-
-
|
| 28 |
|
| 29 |
-
the model then generates the relevant Spark/PySpark code
|
| 30 |
|
| 31 |
-
**Training
|
| 32 |
|
| 33 |
-
|
| 34 |
-
## Example (Dataset Context)
|
| 35 |
|
| 36 |
**DataFrame context:**
|
| 37 |
|
|
@@ -40,11 +21,11 @@ DataFrame: orders
|
|
| 40 |
Columns: customer_id (string), order_id (string), amount (double)
|
| 41 |
```
|
| 42 |
|
| 43 |
-
**
|
| 44 |
-
|
| 45 |
Calculate total revenue per customer and return the five customers with the highest revenue.
|
| 46 |
-
|
| 47 |
-
**
|
| 48 |
|
| 49 |
```python
|
| 50 |
from pyspark.sql import functions as F
|
|
@@ -57,32 +38,7 @@ result = (
|
|
| 57 |
)
|
| 58 |
```
|
| 59 |
|
| 60 |
-
##
|
| 61 |
-
|
| 62 |
-
QLoRA combines low-rank adaptation (LoRA) with a quantized, frozen pretrained model. Only the added adapter parameters are updated during training, reducing memory requirements compared with full fine-tuning.
|
| 63 |
-
|
| 64 |
-
base model was loaded in 4-bit NF4 with double quantization. LoRA adapters were trained on attention and feed-forward projection layers:
|
| 65 |
-
|
| 66 |
-
`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`.
|
| 67 |
-
|
| 68 |
-
**17,432,576 of 1,738,007,552 parameters were trainable (1.0030%).** The reported total includes the adapter parameters.
|
| 69 |
-
|
| 70 |
-
| LoRA setting | Value |
|
| 71 |
-
|---|---|
|
| 72 |
-
| Task type | Causal language modeling |
|
| 73 |
-
| Base quantization | 4-bit NF4 with double quantization |
|
| 74 |
-
|
| 75 |
-
## Model
|
| 76 |
-
|
| 77 |
-
| Component | Value |
|
| 78 |
-
|---|---|
|
| 79 |
-
| Base model | `Qwen/Qwen3-1.7B` |
|
| 80 |
-
| Fine-tuning | PEFT QLoRA, TRL `SFTTrainer` |
|
| 81 |
-
| Libraries | Transformers, PEFT, TRL, bitsandbytes, PyTorch |
|
| 82 |
-
| Training output | PEFT LoRA adapter |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
## Dataset (Local Generated Synthetic Spark Dataset)
|
| 86 |
|
| 87 |
|
| 88 |
| Dataset statistic | Count |
|
|
@@ -91,94 +47,71 @@ base model was loaded in 4-bit NF4 with double quantization. LoRA adapters were
|
|
| 91 |
| Training examples | 600 |
|
| 92 |
| Validation examples | 150 |
|
| 93 |
| Held-out test examples | 150 |
|
| 94 |
-
|
|
| 95 |
| Algorithm families | 180 |
|
| 96 |
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
note: All 900 reference snippets passed Python AST syntax parsing. (means that your dataset is structurally clean and ready for analysis, and or model training (without needing syntax-level preprocessing)
|
| 115 |
-
## Training
|
| 116 |
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
| Epoch | Step | Training loss | Validation loss |
|
| 121 |
-
|---|---:|---:|---:|
|
| 122 |
-
| 1 | 75 | 0.1145 | 0.5008 |
|
| 123 |
-
| 2 | 150 | 0.0213 | 0.5720 |
|
| 124 |
-
| 3 | 225 | 0.0098 | 0.6047 |
|
| 125 |
|
| 126 |
|
| 127 |
## Model Evaluation
|
| 128 |
|
| 129 |
-
|
| 130 |
-
- [**greedy decoding**](https://machinelearningmastery.com/decoding-strategies-and-output-control/): deterministic text generation strategy in ML where a model picks the single token with the highest predicted probability at each step of an autoregressive sequence (model that predicts the next element in a sequence by conditioning on its own past outputs or lagged values)
|
| 131 |
-
- **note:** greedy decoding called "greedy" because it always grabs the immediate best option (the token with the highest probability) at every single step without caring about the long-term consequence for the rest of the sentence
|
| 132 |
-
- **immediate local gain:** at each step, the language model looks at all possible next words and "greedily" picks the single highest-scoring one
|
| 133 |
-
- **no long-term planning:** greedy decoding algorithms never look ahead or evaluates whether choosing that local favorite will trap the model in a repetitive loop, a dead end, or a awkward phrasing two or three words later
|
| 134 |
-
- **myopic behavior:** just like a greedy person who only thinks about right now rather than the future, the algorithm maximizes step-by-step payoff at the expense of the global (whole-sentence) quality.
|
| 135 |
|
| 136 |
-
**
|
| 137 |
|
| 138 |
-
|
| 139 |
-
- **Mean Character-Sequence:** AVG similarity score computed across a set of textual information when each is compared character-by-character against a ground-truth reference sequence
|
| 140 |
|
| 141 |
-
| Metric | Base
|
| 142 |
|---|---:|---:|
|
| 143 |
-
|
|
| 144 |
-
|
|
|
|
|
| 145 |
|
| 146 |
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
- **
|
| 150 |
-
- Training used 600 synthetic examples from 120 algorithm families; the model has not been validated on production tasks
|
| 151 |
-
- Held out test tasks come from the same synthetic generation method as the training data, even though algorithm families are separated by split
|
| 152 |
-
- Delta Lake operations, streaming jobs, cloud connectors, and distributed execution require compatible runtime configuration and should be validated before use
|
| 153 |
|
| 154 |
## Example Import (PEFT)
|
| 155 |
|
| 156 |
-
**Note 1:** Example prompt requires a compatible CUDA GPU, PyTorch, Transformers, PEFT, Accelerate, and bitsandbytes. For larger GPUs, loading the unquantized base model is also possible
|
| 157 |
-
|
| 158 |
-
**Note 2:** this model uses an adapter, not the full Qwen3 base model
|
| 159 |
|
| 160 |
```python
|
| 161 |
import torch
|
| 162 |
from peft import PeftModel
|
| 163 |
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 164 |
|
| 165 |
-
#
|
| 166 |
-
base_id = "Qwen/
|
| 167 |
-
adapter_id = "
|
| 168 |
|
| 169 |
-
# Load original Qwen3 tokenizer
|
| 170 |
tokenizer = AutoTokenizer.from_pretrained(base_id)
|
| 171 |
-
|
| 172 |
if tokenizer.pad_token is None:
|
| 173 |
tokenizer.pad_token = tokenizer.eos_token
|
| 174 |
|
| 175 |
-
#
|
| 176 |
compute_dtype = (
|
| 177 |
-
torch.bfloat16
|
| 178 |
-
if torch.cuda.is_bf16_supported()
|
| 179 |
-
else torch.float16
|
| 180 |
)
|
| 181 |
-
|
| 182 |
quantization = BitsAndBytesConfig(
|
| 183 |
load_in_4bit=True,
|
| 184 |
bnb_4bit_quant_type="nf4",
|
|
@@ -186,61 +119,39 @@ quantization = BitsAndBytesConfig(
|
|
| 186 |
bnb_4bit_compute_dtype=compute_dtype,
|
| 187 |
)
|
| 188 |
|
| 189 |
-
# Load base Qwen3 model
|
| 190 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 191 |
base_id,
|
| 192 |
quantization_config=quantization,
|
| 193 |
device_map="auto",
|
| 194 |
)
|
| 195 |
-
|
| 196 |
-
# Load fine-tuned SparkQwen adapter
|
| 197 |
-
model = PeftModel.from_pretrained(
|
| 198 |
-
base_model,
|
| 199 |
-
adapter_id,
|
| 200 |
-
)
|
| 201 |
model.eval()
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
"DataFrame orders: customer_id string, "
|
| 206 |
-
"order_id string, amount double"
|
| 207 |
-
)
|
| 208 |
-
|
| 209 |
-
question = (
|
| 210 |
-
"Calculate total revenue per customer "
|
| 211 |
-
"and show the top five customers."
|
| 212 |
-
)
|
| 213 |
|
| 214 |
-
# Define coding assistant behavior
|
| 215 |
system_prompt = (
|
| 216 |
"You are a PySpark data engineering coding assistant. "
|
| 217 |
-
"Return executable PySpark code with necessary imports. "
|
| 218 |
"Prefer Spark DataFrame APIs over pandas and RDDs. "
|
| 219 |
"Use the provided schemas and names without inventing tables or columns. "
|
|
|
|
| 220 |
)
|
| 221 |
-
|
| 222 |
messages = [
|
| 223 |
{"role": "system", "content": system_prompt},
|
| 224 |
-
{
|
| 225 |
-
"role": "user",
|
| 226 |
-
"content": f"{question}\n\nContext / schema:\n{context}",
|
| 227 |
-
},
|
| 228 |
]
|
| 229 |
|
| 230 |
-
#
|
| 231 |
prompt = tokenizer.apply_chat_template(
|
| 232 |
messages,
|
| 233 |
tokenize=False,
|
| 234 |
add_generation_prompt=True,
|
| 235 |
-
|
|
|
|
|
|
|
| 236 |
)
|
| 237 |
|
| 238 |
-
inputs = tokenizer(
|
| 239 |
-
prompt,
|
| 240 |
-
return_tensors="pt",
|
| 241 |
-
).to(model.get_input_embeddings().weight.device)
|
| 242 |
-
|
| 243 |
-
# Generate PySpark code
|
| 244 |
with torch.inference_mode():
|
| 245 |
output_ids = model.generate(
|
| 246 |
**inputs,
|
|
@@ -250,21 +161,18 @@ with torch.inference_mode():
|
|
| 250 |
eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>"),
|
| 251 |
)
|
| 252 |
|
| 253 |
-
|
| 254 |
-
generated_code = tokenizer.decode(
|
| 255 |
-
output_ids[0][inputs["input_ids"].shape[-1]:],
|
| 256 |
-
skip_special_tokens=True,
|
| 257 |
-
).strip()
|
| 258 |
-
|
| 259 |
-
print("Generated PySpark Code:")
|
| 260 |
print(generated_code)
|
| 261 |
```
|
| 262 |
|
|
|
|
| 263 |
## References
|
| 264 |
|
| 265 |
-
- [Qwen Team.
|
| 266 |
-
- [
|
| 267 |
-
- [Hu
|
| 268 |
-
- [Dettmers
|
| 269 |
-
- [Hugging Face.
|
| 270 |
-
- [Hugging Face. PEFT LoRA](https://huggingface.co/docs/peft/en/package_reference/lora)
|
|
|
|
|
|
| 1 |
+
# PySparkQwen: [**Qwen/Qwen2.5-Coder-1.5B-Instruct**](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct) Fine-Tuning with QLoRA
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
QLoRA fine-tuning of [**Qwen/Qwen2.5-Coder-1.5B-Instruct**](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct) for PySpark code generation.
|
| 4 |
|
| 5 |
+
**PySparkQwen** is a PySpark coding model, that is used for data engineering tasks, including DataFrame transformations, joins, Spark SQL, structured streaming, Delta Lake, performance optimization, MLlib, and distributed processing.
|
| 6 |
|
| 7 |
+
**Given:**
|
| 8 |
|
| 9 |
+
- PySpark task (prompt)
|
| 10 |
+
- Available DataFrame or table schemas, column names, and any relevant runtime constraints.
|
| 11 |
|
|
|
|
| 12 |
|
| 13 |
+
**Training note:** The base model was loaded with 4-bit NF4 quantization and adapted locally using parameter-efficient LoRA weights. This repository uses a **PEFT adapter**, not a standalone copy of the base model.
|
| 14 |
|
| 15 |
+
## Example
|
|
|
|
| 16 |
|
| 17 |
**DataFrame context:**
|
| 18 |
|
|
|
|
| 21 |
Columns: customer_id (string), order_id (string), amount (double)
|
| 22 |
```
|
| 23 |
|
| 24 |
+
**Prompt:**
|
| 25 |
+
```text
|
| 26 |
Calculate total revenue per customer and return the five customers with the highest revenue.
|
| 27 |
+
```
|
| 28 |
+
**Expected Model Output:**
|
| 29 |
|
| 30 |
```python
|
| 31 |
from pyspark.sql import functions as F
|
|
|
|
| 38 |
)
|
| 39 |
```
|
| 40 |
|
| 41 |
+
## Dataset: Synthetic PySpark Code Tasks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
| Dataset statistic | Count |
|
|
|
|
| 47 |
| Training examples | 600 |
|
| 48 |
| Validation examples | 150 |
|
| 49 |
| Held-out test examples | 150 |
|
| 50 |
+
| Task categories | 15 |
|
| 51 |
| Algorithm families | 180 |
|
| 52 |
|
| 53 |
+
Dataset is **balanced across 15 task categories**, with **60 examples per category** (40 training, 10 validation, and 10 test). It covers:
|
| 54 |
|
| 55 |
+
1. DataFrame creation and transformations
|
| 56 |
+
2. Data ingestion and file formats
|
| 57 |
+
3. Data cleaning and preprocessing
|
| 58 |
+
4. Filtering, sorting, and aggregation
|
| 59 |
+
5. Joins and window functions
|
| 60 |
+
6. Spark SQL
|
| 61 |
+
7. UDFs and Pandas UDFs
|
| 62 |
+
8. Structured Streaming
|
| 63 |
+
9. Performance optimization and caching
|
| 64 |
+
10. Partitioning and repartitioning
|
| 65 |
+
11. Machine learning with MLlib
|
| 66 |
+
12. Nested and complex data types
|
| 67 |
+
13. Error handling and debugging
|
| 68 |
+
14. Delta Lake operations
|
| 69 |
+
15. Distributed computing and cluster execution
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
|
| 72 |
+
All 900 reference snippets passed Python `ast.parse` syntax checks.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
## Model Evaluation
|
| 76 |
|
| 77 |
+
The original Qwen2.5-Coder model and the fine-tuned adapter were evaluated on the same **150 held-out synthetic tasks**, using the same prompt construction and greedy decoding (`do_sample=False`) with an output limit of 384 new tokens.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
**Greedy decoding** selects the highest-probability next token at each step, making this comparison deterministic under the same runtime conditions. It does not search for the globally best full program.
|
| 80 |
|
| 81 |
+
### Held-out Test Set (150 Examples)
|
|
|
|
| 82 |
|
| 83 |
+
| Metric | Base Qwen2.5-Coder-1.5B-Instruct | Fine-tuned PySparkQwen-Coder |
|
| 84 |
|---|---:|---:|
|
| 85 |
+
| Evaluated examples | 150 | 150 |
|
| 86 |
+
| Python AST-valid outputs | 90.00% (135/150) | **98.67% (148/150)** |
|
| 87 |
+
| Mean character-sequence similarity to reference | 0.1168 | **0.6621** |
|
| 88 |
|
| 89 |
|
| 90 |
+
## Model Limitations
|
| 91 |
|
| 92 |
+
- **Missing context:** In rare cases (without context): The model may invent columns, tables, file paths, or dependencies if the task or schema is incomplete.
|
| 93 |
+
- **Review before use:** Generated code should be reviewed and tested in a controlled Spark environment before running against production data.
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
## Example Import (PEFT)
|
| 96 |
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
```python
|
| 99 |
import torch
|
| 100 |
from peft import PeftModel
|
| 101 |
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 102 |
|
| 103 |
+
# The original Coder model and your separately uploaded adapter.
|
| 104 |
+
base_id = "Qwen/Qwen2.5-Coder-1.5B-Instruct"
|
| 105 |
+
adapter_id = "YOUR_USERNAME/YOUR_CODER_ADAPTER_REPO"
|
| 106 |
|
|
|
|
| 107 |
tokenizer = AutoTokenizer.from_pretrained(base_id)
|
|
|
|
| 108 |
if tokenizer.pad_token is None:
|
| 109 |
tokenizer.pad_token = tokenizer.eos_token
|
| 110 |
|
| 111 |
+
# Quantize the frozen base model for lower GPU memory use.
|
| 112 |
compute_dtype = (
|
| 113 |
+
torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
|
|
|
|
|
|
| 114 |
)
|
|
|
|
| 115 |
quantization = BitsAndBytesConfig(
|
| 116 |
load_in_4bit=True,
|
| 117 |
bnb_4bit_quant_type="nf4",
|
|
|
|
| 119 |
bnb_4bit_compute_dtype=compute_dtype,
|
| 120 |
)
|
| 121 |
|
|
|
|
| 122 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 123 |
base_id,
|
| 124 |
quantization_config=quantization,
|
| 125 |
device_map="auto",
|
| 126 |
)
|
| 127 |
+
model = PeftModel.from_pretrained(base_model, adapter_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
model.eval()
|
| 129 |
|
| 130 |
+
context = "DataFrame orders: customer_id string, order_id string, amount double"
|
| 131 |
+
question = "Calculate total revenue per customer and show the top five customers."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
|
|
|
| 133 |
system_prompt = (
|
| 134 |
"You are a PySpark data engineering coding assistant. "
|
| 135 |
+
"Return only executable Python/PySpark code with necessary imports. "
|
| 136 |
"Prefer Spark DataFrame APIs over pandas and RDDs. "
|
| 137 |
"Use the provided schemas and names without inventing tables or columns. "
|
| 138 |
+
"Do not add Markdown fences or prose."
|
| 139 |
)
|
|
|
|
| 140 |
messages = [
|
| 141 |
{"role": "system", "content": system_prompt},
|
| 142 |
+
{"role": "user", "content": f"{question}\n\nContext / schema:\n{context}"},
|
|
|
|
|
|
|
|
|
|
| 143 |
]
|
| 144 |
|
| 145 |
+
# Qwen2.5-Coder's native instruct template does not use Qwen3 thinking mode.
|
| 146 |
prompt = tokenizer.apply_chat_template(
|
| 147 |
messages,
|
| 148 |
tokenize=False,
|
| 149 |
add_generation_prompt=True,
|
| 150 |
+
)
|
| 151 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(
|
| 152 |
+
model.get_input_embeddings().weight.device
|
| 153 |
)
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
with torch.inference_mode():
|
| 156 |
output_ids = model.generate(
|
| 157 |
**inputs,
|
|
|
|
| 161 |
eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>"),
|
| 162 |
)
|
| 163 |
|
| 164 |
+
new_tokens = output_ids[0][inputs["input_ids"].shape[-1]:]
|
| 165 |
+
generated_code = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
print(generated_code)
|
| 167 |
```
|
| 168 |
|
| 169 |
+
|
| 170 |
## References
|
| 171 |
|
| 172 |
+
- [Qwen Team. Qwen2.5-Coder-1.5B-Instruct Model Card](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct)
|
| 173 |
+
- [Hui et al. Qwen2.5-Coder Technical Report (2024)](https://arxiv.org/abs/2409.12186)
|
| 174 |
+
- [Hu et al. LoRA: Low-Rank Adaptation of Large Language Models (2021)](https://arxiv.org/abs/2106.09685)
|
| 175 |
+
- [Dettmers et al. QLoRA: Efficient Finetuning of Quantized LLMs (2023)](https://arxiv.org/abs/2305.14314)
|
| 176 |
+
- [Hugging Face. TRL SFTTrainer](https://huggingface.co/docs/trl/sft_trainer)
|
| 177 |
+
- [Hugging Face. PEFT LoRA](https://huggingface.co/docs/peft/en/package_reference/lora)
|
| 178 |
+
- [Hugging Face. PEFT Adapters in Transformers](https://huggingface.co/docs/transformers/peft)
|