tel1980 commited on
Commit
8d00f0b
·
verified ·
1 Parent(s): ddb5329

Upload v1 merged FP16 weights

Browse files

Qwen2.5-Coder-1.5B fine-tuned for Python, SQL and PySpark (FP16 merged)

.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Qwen/Qwen2.5-Coder-1.5B-Instruct
4
+ library_name: transformers
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - code
8
+ - python
9
+ - sql
10
+ - pyspark
11
+ - qlora
12
+ - ollama
13
+ - gguf
14
+ ---
15
+
16
+ # Model Card: qwen-python-slm
17
+
18
+ ## Visão geral
19
+
20
+ `qwen-python-slm` é um modelo de linguagem pequeno (SLM) especializado em gerar código para o ecossistema de **Engenharia de Dados, Data Science, Machine Learning, Deep Learning, LLMs, Agentes de IA, DataOps e MLOps**.
21
+
22
+ O modelo é um ajuste fino (SFT com QLoRA) do [`Qwen/Qwen2.5-Coder-1.5B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct), mantendo a arquitetura de 1,5 bilhão de parâmetros e adicionando adaptadores LoRA treinados para responder a instruções técnicas de dados/IA em **Python**, **SQL** e **PySpark**.
23
+
24
+ - **Tipo de modelo:** Causal LM para geração de código
25
+ - **Idioma:** Português (instruções) + código multilíngue (Python/SQL/PySpark)
26
+ - **Licença:** Apache 2.0
27
+ - **Formatos disponíveis:**
28
+ - Pesos completos (merged, FP16) no Hugging Face Hub
29
+ - GGUF quantizado em Q4_K_M para uso local via Ollama / llama.cpp / Continue.dev
30
+
31
+ ---
32
+
33
+ ## Uso pretendido
34
+
35
+ - Geração de scripts Python para ETL/ELT, análise de dados e ML.
36
+ - Escrita de consultas SQL compatíveis com SQLite/PostgreSQL.
37
+ - Geração de código PySpark para processamento distribuído.
38
+ - Prototipagem de agentes de IA com LangChain, LlamaIndex, CrewAI etc.
39
+ - Automação de pipelines de MLOps/DataOps (Airflow, dbt, MLflow).
40
+ - Uso educacional e produtividade de desenvolvedores de dados.
41
+
42
+ > **Não recomendado para:** produção crítica sem revisão humana; geração de código com dados sensíveis sem validação de segurança; substituição de engenheiros especialistas.
43
+
44
+ ---
45
+
46
+ ## Comandos de linguagem
47
+
48
+ O modelo reconhece prefixos no prompt para forçar a linguagem/domínio desejado:
49
+
50
+ ```text
51
+ /python Código Python genérico
52
+ /sql Consultas SQL
53
+ /pyspark Código PySpark
54
+ /ml Machine Learning (scikit-learn, PyTorch, etc.)
55
+ /llm LLMs e fine-tuning (transformers, peft, vLLM, etc.)
56
+ /agent Agentes de IA (LangChain, LlamaIndex, CrewAI, etc.)
57
+ /dataops Pipelines/DataOps/MLOps (Airflow, dbt, MLflow, etc.)
58
+ ```
59
+
60
+ Exemplo:
61
+
62
+ ```bash
63
+ ollama run tel1980/qwen-python-slm "/sql Liste os 10 produtos mais vendidos no último trimestre."
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Detalhes do treinamento
69
+
70
+ - **Modelo base:** `Qwen/Qwen2.5-Coder-1.5B-Instruct`
71
+ - **Técnica:** Supervised Fine-Tuning (SFT) com QLoRA (4-bit NF4)
72
+ - **Tamanho de contexto:** 1024 tokens
73
+ - **Hardware de treino:** NVIDIA GeForce RTX 5050 (8 GB VRAM)
74
+ - **Hiperparâmetros LoRA:**
75
+ - `r = 16`
76
+ - `alpha = 32`
77
+ - `dropout = 0.05`
78
+ - Módulos alvo: `q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`
79
+ - **Hiperparâmetros de treino:**
80
+ - Batch size efetivo: 16 (1 × 16 gradient accumulation)
81
+ - Learning rate: 2e-4
82
+ - Max steps: 500
83
+ - Warmup steps: 30
84
+ - Otimizador: `paged_adamw_8bit`
85
+ - **Resultado do treino:** ~1h10min de GPU, loss médio 0,578, loss final 0,508
86
+ - **Parâmetros treináveis:** 18,4M (1,18% do total)
87
+
88
+ ---
89
+
90
+ ## Dados de treino
91
+
92
+ Dataset final combinado: **98.180 amostras**.
93
+
94
+ - **Dataset principal:** `iamtarun/python_code_instructions_18k_alpaca` (Python, filtrado por keywords de dados/IA)
95
+ - **Datasets Python extras:** `flytech/python-codes-25k`, `m-a-p/CodeFeedback-Filtered-Instruction` (filtrado para Python, subamostrado para 30k)
96
+ - **Dataset SQL:** `b-mc2/sql-create-context` (subamostrado para 15k)
97
+ - **Dataset PySpark:** curadoria própria de 1.500 amostras no formato Alpaca (`datasets/pyspark_instructions.json`)
98
+ - **Filtro de domínio:** amostras são mantidas apenas se contiverem palavras-chave do ecossistema de dados/IA (pandas, sklearn, PyTorch, Spark, Airflow, MLflow, LangChain etc.)
99
+ - **Prompt de sistema:** engenheiro de dados/ML sênior, especializado em Python/SQL/PySpark para dados e IA.
100
+
101
+ ---
102
+
103
+ ## Métricas de avaliação
104
+
105
+ Avaliação executada com `src/evaluate.py` (Python) e `src/evaluate_extended.py` (SQL e PySpark), 30 amostras por linguagem.
106
+
107
+ > **Ressalva:** as amostras de avaliação vêm dos mesmos datasets usados no treino, então os números tendem a ser otimistas. Servem como sanity check de formato e gramática.
108
+
109
+ | Métrica | Valor |
110
+ |---|---|
111
+ | Taxa de compilação Python válida | 96,67% |
112
+ | Taxa de execução Python sem erros | 83,33% |
113
+ | Taxa de parse SQL válido | 100,00% |
114
+ | Taxa de sintaxe PySpark válida | 100,00% |
115
+ | BLEU médio — Python | 0,175 |
116
+ | BLEU médio — SQL | 0,917 |
117
+ | BLEU médio — PySpark | 0,353 |
118
+
119
+ Observações:
120
+ - Os erros de execução Python foram principalmente ambientais (biblioteca externa ausente, `input()` sem stdin, arquivo local inexistente), não falhas de sintaxe.
121
+ - BLEU alto em SQL reflete o forte padrão do dataset `sql-create-context`; BLEU mede similaridade com a referência, não correção semântica.
122
+
123
+ Futuramente, recomenda-se adicionar **pass@1** em benchmarks como HumanEval, MBPP e Spider/BIRD (SQL), com dados nunca vistos no treino.
124
+
125
+ ---
126
+
127
+ ## Limitações
128
+
129
+ - O modelo foi treinado com recursos limitados (RTX 5050 8 GB, 500 steps), então pode apresentar alucinações ou código não executável.
130
+ - SQL é validado sintaticamente, mas não executado contra um banco real — a semântica depende do schema fornecido.
131
+ - PySpark é tratado como Python; a execução real exige ambiente Spark configurado.
132
+ - O domínio é voltado para dados/IA; código fora desse escopo (frontend, mobile, etc.) pode ter qualidade inferior.
133
+ - O modelo pode reproduzir vieses presentes nos dados de treino.
134
+
135
+ ---
136
+
137
+ ## Como usar
138
+
139
+ ### Ollama (GGUF)
140
+
141
+ ```bash
142
+ ollama run tel1980/qwen-python-slm "/python Crie uma DAG do Airflow que baixe um CSV e salve no S3."
143
+ ```
144
+
145
+ ### Transformers (pesos merged)
146
+
147
+ ```python
148
+ from transformers import AutoModelForCausalLM, AutoTokenizer
149
+
150
+ model_id = "tel1980/qwen-python-slm"
151
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
152
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
153
+
154
+ messages = [
155
+ {"role": "system", "content": "Você é um engenheiro de dados e Machine Learning sênior."},
156
+ {"role": "user", "content": "/sql Liste os clientes com mais de 5 pedidos."},
157
+ ]
158
+ inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to(model.device)
159
+ outputs = model.generate(inputs, max_new_tokens=512, temperature=0.2)
160
+ print(tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True))
161
+ ```
162
+
163
+ ---
164
+
165
+ ## Licença
166
+
167
+ Este modelo é distribuído sob a licença **Apache 2.0**, a mesma do modelo base Qwen2.5-Coder-1.5B-Instruct.
168
+
169
+ ---
170
+
171
+ ## Citação
172
+
173
+ Se você usar este modelo em trabalhos acadêmicos, cite o modelo base:
174
+
175
+ ```bibtex
176
+ @article{qwen2.5,
177
+ title={Qwen2.5 Technical Report},
178
+ author={Qwen Team},
179
+ journal={arXiv preprint arXiv:2409.12186},
180
+ year={2024}
181
+ }
182
+ ```
183
+
184
+ ---
185
+
186
+ ## Links
187
+
188
+ - Código-fonte: `https://github.com/tel1980/SLM_python`
189
+ - Pesos merged (FP16): `https://huggingface.co/tel1980/qwen-python-slm`
190
+ - GGUF quantizado: `https://huggingface.co/tel1980/qwen-python-slm-gguf`
chat_template.jinja ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "dtype": "float16",
8
+ "eos_token_id": 151645,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 1536,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 8960,
13
+ "layer_types": [
14
+ "full_attention",
15
+ "full_attention",
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention"
42
+ ],
43
+ "max_position_embeddings": 32768,
44
+ "max_window_layers": 28,
45
+ "model_type": "qwen2",
46
+ "num_attention_heads": 12,
47
+ "num_hidden_layers": 28,
48
+ "num_key_value_heads": 2,
49
+ "pad_token_id": null,
50
+ "rms_norm_eps": 1e-06,
51
+ "rope_parameters": {
52
+ "rope_theta": 1000000.0,
53
+ "rope_type": "default"
54
+ },
55
+ "sliding_window": null,
56
+ "tie_word_embeddings": true,
57
+ "transformers_version": "5.15.0",
58
+ "use_cache": true,
59
+ "use_sliding_window": false,
60
+ "vocab_size": 151936
61
+ }
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.1,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "5.15.0"
14
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:658e4a00006cf08136d72817ef8faba6ed3b1c32a36733a886620287d998176a
3
+ size 3087466808
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fd169731d2cbde95e10bf356d66d5997fd885dd8dbb6fb4684da3f23b2585d8
3
+ size 11421892
tokenizer_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|im_start|>",
10
+ "<|im_end|>",
11
+ "<|object_ref_start|>",
12
+ "<|object_ref_end|>",
13
+ "<|box_start|>",
14
+ "<|box_end|>",
15
+ "<|quad_start|>",
16
+ "<|quad_end|>",
17
+ "<|vision_start|>",
18
+ "<|vision_end|>",
19
+ "<|vision_pad|>",
20
+ "<|image_pad|>",
21
+ "<|video_pad|>"
22
+ ],
23
+ "is_local": true,
24
+ "local_files_only": false,
25
+ "model_max_length": 32768,
26
+ "pad_token": "<|endoftext|>",
27
+ "split_special_tokens": false,
28
+ "tokenizer_class": "Qwen2Tokenizer",
29
+ "unk_token": null
30
+ }