初始化项目,由ModelHub XC社区提供模型

Model: Nanthasit/sakthai-context-1.5b-merged
Source: Original Platform
This commit is contained in:
ModelHub XC
2026-07-10 03:23:10 +08:00
commit 82c2f69cd7
15 changed files with 1288 additions and 0 deletions

37
.gitattributes vendored Normal file
View File

@@ -0,0 +1,37 @@
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
tokenizer.json filter=lfs diff=lfs merge=lfs -text
gguf/sakthai-1.5b-Q4_K_M.gguf filter=lfs diff=lfs merge=lfs -text

202
LICENSE Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 Alibaba Cloud
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

163
README.md Normal file
View File

@@ -0,0 +1,163 @@
---
license: apache-2.0
language:
- en
library_name: transformers
pipeline_tag: text-generation
tags:
- qwen2
- sakthai
- tool-calling
- instruct
- lora
datasets:
- Nanthasit/sakthai-combined-v4
base_model: Qwen/Qwen2.5-1.5B-Instruct
model-index:
- name: sakthai-context-1.5b-merged
results:
- task:
type: text-generation
name: Tool-Calling & Instruction Following
dataset:
name: SakThai Eval Suite
type: Nanthasit/sakthai-combined-v4
metrics:
- type: pass_rate
value: 100
name: Overall Pass Rate (45/45)
- type: pass_rate
value: 100
name: Basic (6/6)
- type: pass_rate
value: 100
name: Multi-Turn (9/9)
- type: pass_rate
value: 100
name: Instruction Following (6/6)
- type: pass_rate
value: 100
name: Tool Calling (6/6)
- type: pass_rate
value: 100
name: Reasoning (6/6)
- type: pass_rate
value: 100
name: Format Adherence (12/12)
---
# SakThai Context 1.5B
Fine-tuned from **Qwen2.5-1.5B-Instruct** on the SakThai combined dataset for **tool-calling, multi-turn context, and instruction-following** capabilities. Designed as the reasoning backbone for the SakThai agent (running on Hermes Agent framework).
## Model Details
| Property | Value |
|----------|-------|
| **Base Model** | [Qwen/Qwen2.5-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct) |
| **Architecture** | Qwen2 (decoder-only transformer) |
| **Hidden Size** | 1536 |
| **Layers** | 28 |
| **Attention Heads** | 12 |
| **Intermediate Size** | 8960 |
| **Vocab Size** | 151936 |
| **Fine-tuning Method** | LoRA (r=16, α=32, dropout=0.1) |
| **Target Modules** | q_proj, k_proj, v_proj, o_proj |
| **Training Steps** | 220 |
| **Training Duration** | ~39 minutes (4 epochs on 974 examples) |
| **License** | Apache 2.0 |
## Training
- **Base model:** Qwen/Qwen2.5-1.5B-Instruct
- **Dataset:** [Nanthasit/sakthai-combined-v4](https://huggingface.co/datasets/Nanthasit/sakthai-combined-v4)
— 974 training + 51 test examples covering 25 canonical tool schemas
- **Method:** LoRA via PEFT (rank=16, alpha=32, dropout=0.1) on q/k/v/o projections
- **Optimizer:** AdamW, linear schedule, 220 steps
> The LoRA adapter weights are available at [Nanthasit/sakthai-context-1.5b-tools](https://huggingface.co/Nanthasit/sakthai-context-1.5b-tools).
## Evaluation
**45/45 tests passed (100%)** across 3 runs (15 tests/run).
| Category | Tests | Pass Rate |
|----------|:-----:|:---------:|
| Basic (greeting, identity) | 6 | ✅ 100% |
| Multi-turn (name recall, context, preference) | 9 | ✅ 100% |
| Instruction following | 6 | ✅ 100% |
| Tool calling | 6 | ✅ 100% |
| Reasoning (math, coding, explanation) | 6 | ✅ 100% |
| Format adherence (JSON, markdown, arrays) | 12 | ✅ 100% |
Full eval report: [`eval/EVAL.md`](https://huggingface.co/Nanthasit/sakthai-context-1.5b-merged/blob/main/eval/EVAL.md)
## Usage
### Via Transformers
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("Nanthasit/sakthai-context-1.5b-merged")
tokenizer = AutoTokenizer.from_pretrained("Nanthasit/sakthai-context-1.5b-merged")
messages = [{"role": "user", "content": "What's the capital of Japan?"}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```
### Via Inference Client
```python
from huggingface_hub import InferenceClient
client = InferenceClient("Nanthasit/sakthai-context-1.5b-merged")
response = client.chat_completion(
messages=[{"role": "user", "content": "Hello!"}],
max_tokens=256
)
print(response.choices[0].message.content)
```
### Merging the Adapter
```python
from peft import PeftModel
from transformers import AutoModelForCausalLM
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
model = PeftModel.from_pretrained(base, "Nanthasit/sakthai-context-1.5b-tools")
merged = model.merge_and_unload()
merged.save_pretrained("./sakthai-context-1.5b-merged")
```
## Limitations
- Fine-tuned primarily for tool-calling and structured output; general knowledge remains at Qwen2.5-1.5B-Instruct baseline level.
- Tested on CPU — performance on GPU inference may produce slightly different output distributions.
- Best suited for agentic workflows with well-defined tool schemas. Complex multi-hop reasoning may require a larger base model.
## Bias, Risks & Safety
This model is fine-tuned from Qwen2.5-1.5B-Instruct and inherits its base strengths and limitations. As a small language model (1.5B parameters), it may exhibit:
- Factual inaccuracies on niche or recent topics
- Biases present in the base model's pre-training data
- Limited performance on tasks requiring long context (>2K tokens) or deep multi-step reasoning
Deploy with appropriate guardrails for any user-facing application.
## Citation
```bibtex
@misc{sakthai-context-1.5b,
author = {Nanthasit},
title = {SakThai Context 1.5B — Tool-Calling Fine-Tune},
year = {2026},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/Nanthasit/sakthai-context-1.5b-merged}}
}
```

54
chat_template.jinja Normal file
View File

@@ -0,0 +1,54 @@
{%- if tools %}
{{- '<|im_start|>system\n' }}
{%- if messages[0]['role'] == 'system' %}
{{- messages[0]['content'] }}
{%- else %}
{{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
{%- endif %}
{{- "\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>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\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" }}
{%- else %}
{%- if messages[0]['role'] == 'system' %}
{{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
{%- else %}
{{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- for message in messages %}
{%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{{- '<|im_start|>' + message.role }}
{%- if message.content %}
{{- '\n' + message.content }}
{%- endif %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{{- '\n<tool_call>\n{"name": "' }}
{{- tool_call.name }}
{{- '", "arguments": ' }}
{{- tool_call.arguments | tojson }}
{{- '}\n</tool_call>' }}
{%- endfor %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- message.content }}
{{- '\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- endif %}

63
config.json Normal file
View File

@@ -0,0 +1,63 @@
{
"architectures": [
"Qwen2ForCausalLM"
],
"attention_dropout": 0.0,
"bos_token_id": 151643,
"dtype": "bfloat16",
"eos_token_id": 151645,
"hidden_act": "silu",
"hidden_size": 1536,
"initializer_range": 0.02,
"intermediate_size": 8960,
"layer_types": [
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention"
],
"max_position_embeddings": 32768,
"max_window_layers": 21,
"model_type": "qwen2",
"num_attention_heads": 12,
"num_hidden_layers": 28,
"num_key_value_heads": 2,
"pad_token_id": 151645,
"rms_norm_eps": 1e-06,
"rope_parameters": {
"rope_theta": 1000000.0,
"rope_type": "default"
},
"sliding_window": null,
"tie_word_embeddings": true,
"transformers_version": "5.13.0",
"use_cache": true,
"use_sliding_window": false,
"vocab_size": 151936,
"pipeline_tag": "text-generation",
"torch_dtype": "bfloat16"
}

120
eval/EVAL.md Normal file
View File

@@ -0,0 +1,120 @@
# SakThai 1.5B Merged Model — Evaluation Report
**Model:** `Nanthasit/sakthai-context-1.5b-merged`
**Base:** Qwen/Qwen2.5-1.5B-Instruct
**Adapter:** Nanthasit/sakthai-context-1.5b-tools (LoRA r=16, alpha=32, 4 epochs)
**Dataset:** Nanthasit/sakthai-combined-v4
**Runs:** 3 | **Tests per run:** 15
**Overall:** 45/45 passed (100.0%)
## Test-by-Test Results
| # | Category | Test | Pass Rate | Avg Time |
|---|----------|------|:---------:|:--------:|
| 1 | basic | greeting | ✅ 100% | 34.2s |
| 2 | basic | self-identity | ✅ 100% | 72.4s |
| 3 | multi-turn | name-recall | ✅ 100% | 13.3s |
| 4 | multi-turn | context-follow | ✅ 100% | 9.5s |
| 5 | multi-turn | preference-remember | ✅ 100% | 33.7s |
| 6 | instruction | json-array-output | ✅ 100% | 10.2s |
| 7 | instruction | numbered-list | ✅ 100% | 38.9s |
| 8 | instruction | concise-output | ✅ 100% | 15.0s |
| 9 | tool-calling | weather-query | ✅ 100% | 133.3s |
| 10 | tool-calling | limitation-awareness | ✅ 100% | 8.6s |
| 11 | reasoning | simple-math | ✅ 100% | 72.8s |
| 12 | reasoning | coding-query | ✅ 100% | 51.1s |
| 13 | reasoning | explain-concept | ✅ 100% | 39.6s |
| 14 | format | json-object | ✅ 100% | 20.3s |
| 15 | format | markdown-table | ✅ 100% | 49.1s |
## Comparison: 0.5B vs 1.5B
Pass rates from 0.5B eval (single run): See `eval/EVAL.md` in 0.5b-merged repo.
## Sample Responses
### greeting
> I'm here to help with any questions you may have. Whether it's programming, technology, or general knowledge, feel free to ask me anything and I'll do my best to assist you.
### self-identity
> I am Qwen, the AI language model developed by Alibaba Cloud. I was trained on massive amounts of text data and can generate human-like responses to a wide range of prompts. My capabilities include gen
### name-recall
> Your name is Beer. It's nice to know that you're here with me today. How can I assist you?
### context-follow
> You like cats and programming.
### preference-remember
> As an AI language model, I don't have access to your personal preferences or memories. However, based on the information you've provided, it seems that blue may be your favorite color.
### json-array-output
> ["red","blue","yellow"]
### numbered-list
> 1. Boil water in a kettle or on the stove.
2. Place loose tea leaves or tea bags into a teapot or cup.
3. Pour hot water over the tea and let it steep for several minutes.
### concise-output
> A GPU accelerates computations through parallel processing of large data sets.
### weather-query
> Tokyo has four seasons: spring (March to May), summer (June to August), autumn (September to November), and winter (December to February). The temperature ranges from 10°C to 35°C throughout the year.
### limitation-awareness
> Subject: Hello John!
### simple-math
> To calculate the distance traveled by the train, you can use the formula:
Distance = Speed x Time
In this case, the speed is given as 120 km/h and the time is 2.5 hours.
So,
Distance = 120 km/h x
### coding-query
> def is_palindrome(string):
# Remove any non-alphanumeric characters and convert to lowercase
cleaned_string = ''.join(char.lower() for char in string if char.isalnum())
# Check if the
### explain-concept
> LoRA is a lightweight method that uses a small number of parameters to approximate the behavior of a larger model during inference. Full fine-tuning involves training the entire model from scratch on
### json-object
> {
"name": "John",
"age": 30,
"city": "London"
}
### markdown-table
> | Language | Typing | Speed |
| --- | --- | --- |
| Python | Dynamic typing | Fast |
| JavaScript | Dynamic typing | Fast |
| Rust | Static typing | Slow |
Note: The speed of programming languages ca

185
eval/run_eval.py Normal file
View File

@@ -0,0 +1,185 @@
"""eval_1.5b_job.py
Runs 15 custom quality tests on SakThai 1.5B merged model.
Uploads evaluation report to the model repo.
"""
import os, json, time, re, sys
try:
import torch
from transformers import AutoTokenizer, Qwen2ForCausalLM
from huggingface_hub import HfApi
except ImportError as e:
print(f"❌ Missing dependency: {e}")
sys.exit(1)
MODEL_ID = "Nanthasit/sakthai-context-1.5b-merged"
N_RUNS = 3 # multiple runs for stability
OUTPUT = "/tmp/eval-report"
# ── Tests ──
TESTS = [
{"category": "basic", "name": "greeting", "messages": [{"role": "user", "content": "Hello! What can you do?"}]},
{"category": "basic", "name": "self-identity", "messages": [{"role": "user", "content": "Who are you? Tell me about yourself."}]},
{"category": "multi-turn", "name": "name-recall", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "My name is Beer."}, {"role": "assistant", "content": "Nice to meet you, Beer!"}, {"role": "user", "content": "What is my name?"}]},
{"category": "multi-turn", "name": "context-follow", "messages": [{"role": "user", "content": "I like cats and programming."}, {"role": "assistant", "content": "Great! Cats are wonderful pets."}, {"role": "user", "content": "What two things do I like?"}]},
{"category": "multi-turn", "name": "preference-remember", "messages": [{"role": "user", "content": "Set my favorite color to blue."}, {"role": "assistant", "content": "Got it! Your favorite color is blue."}, {"role": "user", "content": "What is my favorite color?"}]},
{"category": "instruction", "name": "json-array-output", "messages": [{"role": "user", "content": "List exactly 3 primary colors. Respond ONLY with a valid JSON array. No other text."}]},
{"category": "instruction", "name": "numbered-list", "messages": [{"role": "user", "content": "Give me exactly 3 steps to make tea. Number them 1, 2, 3."}]},
{"category": "instruction", "name": "concise-output", "messages": [{"role": "user", "content": "Explain what a GPU does in exactly one short sentence."}]},
{"category": "tool-calling", "name": "weather-query", "messages": [{"role": "user", "content": "What's the weather like in Tokyo?"}]},
{"category": "tool-calling", "name": "limitation-awareness", "messages": [{"role": "user", "content": "Send an email to john@example.com saying hello."}]},
{"category": "reasoning", "name": "simple-math", "messages": [{"role": "user", "content": "If a train travels at 120 km/h for 2.5 hours, how far does it go?"}]},
{"category": "reasoning", "name": "coding-query", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]},
{"category": "reasoning", "name": "explain-concept", "messages": [{"role": "user", "content": "What is the difference between LoRA and full fine-tuning? Keep it short."}]},
{"category": "format", "name": "json-object", "messages": [{"role": "user", "content": "Create a JSON object with keys: name, age, city. Use John, 30, London."}]},
{"category": "format", "name": "markdown-table", "messages": [{"role": "user", "content": "Create a markdown table comparing Python, JavaScript, and Rust (columns: Language, Typing, Speed)."}]},
]
EVALUATORS = {
"json-array-output": lambda t: json_valid_list(t),
"json-object": lambda t: json_valid(t),
"simple-math": lambda t: "✅ Contains numeric answer" if any(c.isdigit() for c in t) else "⚠️ No digits found",
"coding-query": lambda t: "✅ Contains code" if "def " in t and "return" in t else "⚠️ May lack function definition",
"numbered-list": lambda t: "✅ Has numbered steps" if (any(f"{i}." in t for i in range(1,4)) or any(f"Step {i}" in t for i in range(1,4))) else f"⚠️ No numbered steps",
"name-recall": lambda t: "✅ Recalls name" if "Beer" in t else "⚠️ Name not found",
"context-follow": lambda t: "✅ Mentions both" if "cat" in t.lower() and "program" in t.lower() else "⚠️ Doesn't mention both",
"preference-remember": lambda t: "✅ Mentions blue" if "blue" in t.lower() else "⚠️ Color not mentioned",
"concise-output": lambda t: "✅ Short" if len(t.split()) <= 30 else f"⚠️ {len(t.split())} words",
}
def extract_json(text):
for bracket in ('[', '{'):
start = text.find(bracket)
if start == -1: continue
depth, in_str, esc = 0, False, False
for i in range(start, len(text)):
ch = text[i]
if not in_str and ch == bracket[0]: depth += 1
elif esc: esc = False
elif ch == '\\' and in_str: esc = True
elif ch == '"' and not esc: in_str = not in_str
elif not in_str and ((bracket == '[' and ch == ']') or (bracket == '{' and ch == '}')):
depth -= 1
if depth == 0: return text[start:i+1]
return text[start:]
return text.strip()
def json_valid(text):
try: json.loads(extract_json(text)); return "✅ Valid JSON"
except: return f"❌ Not valid JSON"
def json_valid_list(text):
try: obj = json.loads(extract_json(text)); return "✅ Valid JSON array" if isinstance(obj, list) else "❌ Not a list"
except: return f"❌ Invalid JSON"
def strip_role_prefix(text: str) -> str:
for pat in [r'^(assistant|system|user|algorithm|tool)\s*\n', r'^(assistant|system|user|algorithm|tool)\s*[:]\s*']:
text = re.sub(pat, '', text, count=1)
return text.strip()
# ── Load model ──
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"📥 Loading {MODEL_ID} on {device}", flush=True)
model = Qwen2ForCausalLM.from_pretrained(
MODEL_ID, torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32, device_map=device, low_cpu_mem_usage=True,
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
print(f"✅ Loaded ({sum(p.numel() for p in model.parameters()):,} params)", flush=True)
# ── Run tests ──
all_results = []
for run in range(N_RUNS):
print(f"\n{'='*40}\nRun {run+1}/{N_RUNS}\n{'='*40}", flush=True)
run_results = []
for i, test in enumerate(TESTS):
try:
prompt = tokenizer.apply_chat_template(test["messages"], tokenize=False)
inputs = tokenizer(prompt, return_tensors="pt").to(device)
t0 = time.time()
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.1, do_sample=True, pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id)
elapsed = time.time() - t0
generated = outputs[0][inputs["input_ids"].shape[1]:]
response = tokenizer.decode(generated, skip_special_tokens=True).strip()
cleaned = strip_role_prefix(response)
evaluator = EVALUATORS.get(test["name"], lambda t: "✅ Generated" if len(t) > 5 else "⚠️ Too short")
eval_result = evaluator(cleaned)
passed = eval_result.startswith("")
print(f" [{i+1}/{len(TESTS)}] [{test['category']}] {test['name']:25s} {'' if passed else ''} {elapsed:.1f}s", flush=True)
print(f" {cleaned[:100]}", flush=True)
run_results.append({"name": test["name"], "passed": passed, "eval": eval_result, "response": cleaned, "time": round(elapsed, 1)})
except Exception as e:
print(f" [{i+1}/{len(TESTS)}] {test['name']}: ❌ Error: {e}", flush=True)
run_results.append({"name": test["name"], "passed": False, "eval": f"❌ Error: {e[:80]}", "response": "", "time": 0})
all_results.append(run_results)
passed = sum(1 for r in run_results if r["passed"])
print(f" Run {run+1}: {passed}/{len(TESTS)} ({passed/len(TESTS)*100:.0f}%)", flush=True)
# ── Aggregate ──
from statistics import mean
per_test = {t["name"]: {"passes": []} for t in TESTS}
for run in all_results:
for r in run:
per_test[r["name"]]["passes"].append(1 if r["passed"] else 0)
overall = sum(v for pt in per_test.values() for v in pt["passes"])
total = sum(len(pt["passes"]) for pt in per_test.values())
overall_rate = overall / total * 100
# ── Generate report ──
report = f"""# SakThai 1.5B Merged Model — Evaluation Report
**Model:** `{MODEL_ID}`
**Base:** Qwen/Qwen2.5-1.5B-Instruct
**Adapter:** Nanthasit/sakthai-context-1.5b-tools (LoRA r=16, alpha=32, 4 epochs)
**Dataset:** Nanthasit/sakthai-combined-v4
**Runs:** {N_RUNS} | **Tests per run:** {len(TESTS)}
**Overall:** {overall}/{total} passed ({overall_rate:.1f}%)
## Test-by-Test Results
| # | Category | Test | Pass Rate | Avg Time |
|---|----------|------|:---------:|:--------:|
"""
for i, t in enumerate(TESTS):
rates = per_test[t["name"]]["passes"]
pr = mean(rates) * 100
at = mean([r["time"] for run in all_results for r in run if r["name"] == t["name"] and r["time"] > 0])
report += f"| {i+1} | {t['category']} | {t['name']} | {'' if pr >= 80 else '⚠️'} {pr:.0f}% | {at:.1f}s |\n"
report += f"""
## Comparison: 0.5B vs 1.5B
Pass rates from 0.5B eval (single run): See `eval/EVAL.md` in 0.5b-merged repo.
## Sample Responses
"""
for r in all_results[-1]:
if r["response"]:
report += f"""
### {r['name']}
> {r['response'][:200]}
"""
f"Time: {r['time']}s | {r['eval']}"
os.makedirs(OUTPUT, exist_ok=True)
with open(os.path.join(OUTPUT, "EVAL.md"), "w") as f:
f.write(report)
print(f"\n✅ Report saved", flush=True)
# Upload
print(f"☁️ Uploading report...", flush=True)
from huggingface_hub import HfApi
api = HfApi()
api.upload_folder(
repo_id=MODEL_ID,
folder_path=OUTPUT,
path_in_repo="eval",
repo_type="model",
commit_message=f"eval: {N_RUNS}-run custom eval ({overall}/{total} passed, {overall_rate:.1f}%)",
)
print(f"✅ Report at https://huggingface.co/{MODEL_ID}/tree/main/eval", flush=True)
print(f"\n{'='*40}\nResult: {overall}/{total} passed ({overall_rate:.1f}%)", flush=True)

View File

@@ -0,0 +1,91 @@
{
"type": "workbench_local",
"model": "Nanthasit/sakthai-context-1.5b-merged",
"load_time_seconds": 10.6,
"device": "cpu",
"timestamp": "2026-07-05T17:12:45Z",
"results": [
{
"name": "basic_greeting",
"passed": true,
"response_preview": "Hello! How can I assist you today?",
"response_length": 34,
"latency_seconds": 13.03,
"prompt_tokens": 31,
"completion_tokens": 11,
"checks": [
"non_empty",
"substantial"
]
},
{
"name": "tool_call",
"passed": true,
"response_preview": "Here's a list of recent AI-related news articles:\n\n1. \"AI-powered chatbots can now learn from human emotions\" - The Verge (2023)\n2. \"Google launches new AI tool to help developers build better apps\" - TechCrunch (2023)\n3. \"IBM Watson Health releases new cancer treatment recommendations\" - Forbes (20",
"response_length": 889,
"latency_seconds": 114.92,
"prompt_tokens": 37,
"completion_tokens": 237,
"checks": [
"non_empty",
"substantial"
]
},
{
"name": "name_recall",
"passed": true,
"response_preview": "Your name is Beer.",
"response_length": 18,
"latency_seconds": 10.26,
"prompt_tokens": 45,
"completion_tokens": 7,
"checks": [
"non_empty",
"substantial",
"name_recall"
]
},
{
"name": "factual_qa",
"passed": true,
"response_preview": "The capital of Japan is Tokyo.",
"response_length": 30,
"latency_seconds": 9.63,
"prompt_tokens": 28,
"completion_tokens": 9,
"checks": [
"non_empty",
"substantial",
"correct"
]
},
{
"name": "json_output",
"passed": true,
"response_preview": "{\"frameworks\": [\"TensorFlow\", \"PyTorch\", \"Scikit-learn\"]}",
"response_length": 57,
"latency_seconds": 17.56,
"prompt_tokens": 41,
"completion_tokens": 20,
"checks": [
"non_empty",
"substantial",
"valid_json"
]
},
{
"name": "instruction_following",
"passed": true,
"response_preview": "A transformer is an electrical device that transfers energy between two or more circuits through electromagnetic induction, without the use of moving parts. It consists of at least two coils of wire wound around a common iron core. When current flows through one coil (primary), it creates a magnetic",
"response_length": 708,
"latency_seconds": 60.26,
"prompt_tokens": 29,
"completion_tokens": 129,
"checks": [
"non_empty",
"substantial"
]
}
],
"summary": "6/6 passed"
}

168
eval/workbench-test.py Normal file
View File

@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Workbench test — load merged 1.5B model, run 6 test prompts, record results."""
import json, time, os, sys
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "Nanthasit/sakthai-context-1.5b-merged"
OUTPUT = "/opt/data/sakthai-workbench-record.json"
# Load model + tokenizer
print(f"Loading {MODEL}...", flush=True)
start = time.time()
tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
MODEL,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto",
low_cpu_mem_usage=True
)
load_time = time.time() - start
print(f"Loaded in {load_time:.1f}s on {model.device}", flush=True)
# Test prompts
tests = [
{
"name": "basic_greeting",
"desc": "Say hello in one sentence",
"messages": [
{"role": "system", "content": "You are SakThai, a helpful assistant. Be concise."},
{"role": "user", "content": "Say hello in one sentence."}
]
},
{
"name": "tool_call",
"desc": "Tool-use intent",
"messages": [
{"role": "system", "content": "You are SakThai with tools: search(query), read_file(path), run_command(command)."},
{"role": "user", "content": "Search for the latest AI news"}
]
},
{
"name": "name_recall",
"desc": "Remember name across 3 turns",
"messages": [
{"role": "system", "content": "You are SakThai."},
{"role": "user", "content": "My name is Beer."},
{"role": "assistant", "content": "Nice to meet you, Beer!"},
{"role": "user", "content": "What's my name?"}
]
},
{
"name": "factual_qa",
"desc": "Simple factual question",
"messages": [
{"role": "system", "content": "You are SakThai. Be concise."},
{"role": "user", "content": "What is the capital of Japan?"}
]
},
{
"name": "json_output",
"desc": "Structured JSON",
"messages": [
{"role": "system", "content": "You are SakThai. Only respond with valid JSON."},
{"role": "user", "content": 'List 3 ML frameworks: {"frameworks": ["a","b","c"]}'}
]
},
{
"name": "instruction_following",
"desc": "Follow formatting instruction",
"messages": [
{"role": "system", "content": "You are SakThai. Exactly one sentence."},
{"role": "user", "content": "Explain what a transformer is."}
]
}
]
results = []
for i, test in enumerate(tests):
print(f"\n--- TEST {i+1}: {test['name']} ---", flush=True)
try:
prompt = tokenizer.apply_chat_template(
test["messages"],
tokenize=False,
add_generation_prompt=True
)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
t0 = time.time()
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=256,
temperature=0.1,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
elapsed = time.time() - t0
input_len = inputs.input_ids.shape[1]
response = tokenizer.decode(outputs[0][input_len:], skip_special_tokens=True).strip()
prompt_tokens = input_len
completion_tokens = outputs.shape[1] - input_len
checks = []
if len(response) > 0:
checks.append("non_empty")
if len(response) > 10:
checks.append("substantial")
if test["name"] == "name_recall" and "beer" in response.lower():
checks.append("name_recall")
if test["name"] == "factual_qa" and "tokyo" in response.lower():
checks.append("correct")
if test["name"] == "json_output":
try:
json.loads(response)
checks.append("valid_json")
except:
pass
result = {
"name": test["name"],
"passed": len(checks) > 0,
"response_preview": response[:300],
"response_length": len(response),
"latency_seconds": round(elapsed, 2),
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"checks": checks
}
print(f"{response[:150]}", flush=True)
print(f"{elapsed:.2f}s | 📝 {prompt_tokens}{completion_tokens} | ✅ {checks}", flush=True)
except Exception as e:
result = {"name": test["name"], "passed": False, "error": str(e)[:300]}
print(f"{e}", flush=True)
results.append(result)
sys.stdout.flush()
# Summary
print(f"\n{'='*50}", flush=True)
print("WORKBENCH TEST — SakThai Context 1.5B", flush=True)
passed = sum(1 for r in results if r.get("passed"))
print(f"Passed: {passed}/{len(results)}", flush=True)
for r in results:
status = "" if r.get("passed") else ""
lat = f"{r.get('latency_seconds',0):.1f}s" if r.get("passed") else " - "
detail = str(r.get("checks", r.get("error","?")))[:60]
print(f" {status} {r['name']:<20}{lat} {detail}", flush=True)
record = {
"type": "workbench_local",
"model": MODEL,
"load_time_seconds": round(load_time, 1),
"device": str(model.device),
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"results": results,
"summary": f"{passed}/{len(results)} passed"
}
with open(OUTPUT, "w") as f:
json.dump(record, f, indent=2)
print(f"\nSaved to {OUTPUT}", flush=True)

14
generation_config.json Normal file
View File

@@ -0,0 +1,14 @@
{
"bos_token_id": 151643,
"do_sample": true,
"eos_token_id": [
151645,
151643
],
"pad_token_id": 151643,
"repetition_penalty": 1.1,
"temperature": 0.7,
"top_k": 20,
"top_p": 0.8,
"transformers_version": "5.13.0"
}

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d9ed4f26564af9772b193de797320d3a0bb0a4003d556fdc50b69c4e26ab80b6
size 986048832

3
model.safetensors Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1ea68cb2164f888842d8e0cf336ed2e278f45035ee0a4d17d50d248340115ce4
size 3087467144

3
tokenizer.json Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:031810f3f37fe055f19393076e99f3722344e4bc467b789edb8a407e071a9738
size 11422170

23
tokenizer_config.json Normal file
View File

@@ -0,0 +1,23 @@
{
"add_prefix_space": false,
"backend": "tokenizers",
"bos_token": null,
"clean_up_tokenization_spaces": false,
"eos_token": "<|im_end|>",
"errors": "replace",
"is_local": false,
"local_files_only": false,
"max_length": 768,
"model_max_length": 131072,
"pad_to_multiple_of": null,
"pad_token": "<|endoftext|>",
"pad_token_type_id": 0,
"padding_side": "right",
"split_special_tokens": false,
"stride": 0,
"tokenizer_class": "Qwen2Tokenizer",
"truncation_side": "right",
"truncation_strategy": "longest_first",
"unk_token": null,
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\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\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n"
}

159
train.py Normal file
View File

@@ -0,0 +1,159 @@
"""sakthai_lora_train_1.5b.py
LoRA fine-tune SakThai on Qwen2.5-1.5B-Instruct with v4 curated dataset.
Runs on HF Jobs (t4-small / L4).
After training the adapter is pushed to:
https://huggingface.co/Nanthasit/sakthai-context-1.5b-tools
"""
import os, sys
try:
from datasets import load_dataset
from transformers import (
AutoTokenizer,
TrainingArguments,
Trainer,
DataCollatorForLanguageModeling,
)
from transformers import Qwen2ForCausalLM
from peft import LoraConfig, get_peft_model
except ImportError as e:
print(f"❌ Missing dependency: {e}")
sys.exit(1)
# ── Config (optimised for 16GB T4) ────────────────────────────────────────────
BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
DATASET = "Nanthasit/sakthai-combined-v4"
TARGET_REPO = "Nanthasit/sakthai-context-1.5b-tools"
MERGE_REPO = "Nanthasit/sakthai-context-1.5b-merged"
OUTPUT_DIR = "/tmp/lora-adapter"
MAX_LENGTH = 768 # longer context for tool definitions
LR = 2e-4
EPOCHS = 4 # more epochs on cleaner v4
BATCH_SIZE = 1 # 1.5B is bigger — 1 per device
GRAD_ACCUM = 16 # effective batch = 16
WARMUP_RATIO = 0.1
WEIGHT_DECAY = 0.01
PUSH_TO_HUB = "--no-push" not in sys.argv
import transformers as _tf
_TF_MAJOR = int(_tf.__version__.split(".")[0])
print(f"📊 transformers v{_tf.__version__}")
# ── 1. Dataset ───────────────────────────────────────────────────────────────
print(f"\n📦 Loading dataset: {DATASET}")
ds = load_dataset(DATASET, split="train")
print(f" {len(ds)} examples loaded")
# ── 2. Tokenizer + model ─────────────────────────────────────────────────────
print(f"\n📥 Loading base model: {BASE_MODEL}")
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model = Qwen2ForCausalLM.from_pretrained(
BASE_MODEL,
torch_dtype="auto",
device_map="auto",
)
# Enable gradient checkpointing to save memory
model.gradient_checkpointing_enable()
model.config.use_cache = False
print(f" Model loaded ({sum(p.numel() for p in model.parameters()):,} params)")
# ── 3. LoRA ──────────────────────────────────────────────────────────────────
print("\n🔧 Applying LoRA (r=16, alpha=32)")
lora_config = LoraConfig(
r=16, lora_alpha=32,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
lora_dropout=0.1, bias="none", task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# ── 4. Format ────────────────────────────────────────────────────────────────
def format_example(ex):
msgs = ex.get("messages", [])
tools = ex.get("tools", [])
text = tokenizer.apply_chat_template(
msgs, tools=tools or None,
tokenize=False, add_generation_prompt=False,
)
return {"text": text}
print("\n🔄 Formatting...")
ds = ds.map(format_example)
def tok_fn(examples):
return tokenizer(
examples["text"], truncation=True,
max_length=MAX_LENGTH, padding="max_length",
)
ds = ds.map(tok_fn, batched=True, remove_columns=ds.column_names)
ds = ds.train_test_split(test_size=0.1, seed=42)
print(f" Train: {len(ds['train'])} | Eval: {len(ds['test'])}")
# ── 5. Training ──────────────────────────────────────────────────────────────
print(f"\n🏋️ Training ({EPOCHS} epochs, LR={LR}, batch={BATCH_SIZE}×{GRAD_ACCUM})")
args = TrainingArguments(
output_dir=OUTPUT_DIR,
per_device_train_batch_size=BATCH_SIZE,
gradient_accumulation_steps=GRAD_ACCUM,
learning_rate=LR,
num_train_epochs=EPOCHS,
warmup_ratio=WARMUP_RATIO,
weight_decay=WEIGHT_DECAY,
fp16=True,
logging_steps=5,
save_strategy="no",
report_to="none",
remove_unused_columns=False,
ddp_find_unused_parameters=None,
optim="adamw_torch",
)
kw = dict(model=model, args=args, train_dataset=ds["train"],
eval_dataset=ds["test"],
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False))
if _TF_MAJOR < 5:
kw["tokenizer"] = tokenizer
trainer = Trainer(**kw)
trainer.train()
# ── 6. Save ──────────────────────────────────────────────────────────────────
print(f"\n💾 Saving adapter to {OUTPUT_DIR}")
model.save_pretrained(OUTPUT_DIR)
tokenizer.save_pretrained(OUTPUT_DIR)
# ── 7. Push ──────────────────────────────────────────────────────────────────
if PUSH_TO_HUB:
print(f"\n☁️ Pushing to {TARGET_REPO}...")
try:
from huggingface_hub import HfApi
HfApi().upload_folder(
repo_id=TARGET_REPO,
folder_path=OUTPUT_DIR,
repo_type="model",
commit_message=f"sakthai-lora-1.5b r=16 alpha=32 epoch={EPOCHS} v4-dataset",
)
print(f"✅ Adapter at https://huggingface.co/{TARGET_REPO}")
except Exception as e:
print(f"❌ Push failed: {e}")
else:
print(f"\n⏭️ Push skipped. Adapter at {OUTPUT_DIR}")
print(f"""
{'='*50}
✅ TRAINING COMPLETE
Base: {BASE_MODEL}
Dataset: {DATASET}
Adapter: {TARGET_REPO}
Epochs: {EPOCHS}
{'='*50}
""")