Text Generation
Transformers
Safetensors
qwen3
ml-intern
Generated from Trainer
trl
hf_jobs
sft
conversational
python
drawing
svg
matplotlib
text-generation-inference
Instructions to use Malajusa/qwen3-1.7b-python-drawing with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Malajusa/qwen3-1.7b-python-drawing with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Malajusa/qwen3-1.7b-python-drawing") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Malajusa/qwen3-1.7b-python-drawing") model = AutoModelForCausalLM.from_pretrained("Malajusa/qwen3-1.7b-python-drawing", device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Malajusa/qwen3-1.7b-python-drawing with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Malajusa/qwen3-1.7b-python-drawing" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Malajusa/qwen3-1.7b-python-drawing", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Malajusa/qwen3-1.7b-python-drawing
- SGLang
How to use Malajusa/qwen3-1.7b-python-drawing with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Malajusa/qwen3-1.7b-python-drawing" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Malajusa/qwen3-1.7b-python-drawing", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Malajusa/qwen3-1.7b-python-drawing" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Malajusa/qwen3-1.7b-python-drawing", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Malajusa/qwen3-1.7b-python-drawing with Docker Model Runner:
docker model run hf.co/Malajusa/qwen3-1.7b-python-drawing
Download train_sft_a100.py from Malajusa/qwen3-1.7b-python-drawing: direct link, hf CLI and curl.
- Browser
- Download file 6.88 kB
-
https://huggingface.co/Malajusa/qwen3-1.7b-python-drawing/resolve/main/train_sft_a100.py
- Command line
-
hf download hf://Malajusa/qwen3-1.7b-python-drawing/train_sft_a100.py
-
curl -L -o train_sft_a100.py https://huggingface.co/Malajusa/qwen3-1.7b-python-drawing/resolve/main/train_sft_a100.py
6.88 kB
| # Full-parameter SFT of Qwen3-1.7B on Malajusa/qwen3-1.7b-python-drawing-sft | |
| # Conversational prompt-completion format: prompts masked, completion-only loss. | |
| # Reference: TRL v1.18.2 examples/sft_agent_traces/sft.py and sft_config.py. | |
| import json | |
| import os | |
| import time | |
| import pyarrow.parquet as pq | |
| import torch | |
| import trackio | |
| from datasets import Dataset | |
| from huggingface_hub import hf_hub_download | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TrainerCallback | |
| from trl import SFTConfig, SFTTrainer | |
| MODEL_ID = "Qwen/Qwen3-1.7B" | |
| DATASET_REPO = "Malajusa/qwen3-1.7b-python-drawing-sft" | |
| HUB_MODEL_ID = "Malajusa/qwen3-1.7b-python-drawing" | |
| TRACKIO_SPACE_ID = "Malajusa/qwen3-python-drawing-sft-trackio" | |
| TRACKIO_PROJECT = "qwen3-python-drawing-sft" | |
| MAX_LENGTH = 2048 | |
| SMOKE_STEPS = int(os.environ.get("SMOKE_STEPS", "0")) | |
| USE_ACTIVATION_CHECKPOINTING = os.environ.get("ACTIVATION_CHECKPOINTING", "0") == "1" | |
| OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "/data/out") | |
| TRACKIO_READY = False | |
| def load_split(split: str) -> Dataset: | |
| path = hf_hub_download( | |
| DATASET_REPO, filename=f"data/{split}.parquet", repo_type="dataset" | |
| ) | |
| table = pq.read_table(path) | |
| rows = { | |
| "prompt": [json.loads(m) for m in table.column("prompt").to_pylist()], | |
| "completion": [json.loads(m) for m in table.column("completion").to_pylist()], | |
| } | |
| assert all( | |
| isinstance(p, list) and p and p[0].get("role") == "system" | |
| for p in rows["prompt"] | |
| ), "prompt must be a message list starting with system" | |
| assert all( | |
| isinstance(c, list) and c and c[-1].get("role") == "assistant" | |
| for c in rows["completion"] | |
| ), "completion must be a message list ending with assistant" | |
| return Dataset.from_dict(rows) | |
| class MetricsCallback(TrainerCallback): | |
| def on_train_begin(self, args, state, control, **kwargs): | |
| self.started_at = time.monotonic() | |
| if torch.cuda.is_available(): | |
| torch.cuda.reset_peak_memory_stats() | |
| def on_log(self, args, state, control, logs=None, **kwargs): | |
| global TRACKIO_READY | |
| if not logs: | |
| return | |
| elapsed = max(time.monotonic() - self.started_at, 1e-9) | |
| metrics = { | |
| k: v for k, v in logs.items() if isinstance(v, (int, float)) | |
| } | |
| metrics["steps_per_second"] = state.global_step / elapsed | |
| if torch.cuda.is_available(): | |
| metrics["peak_memory_allocated_gb"] = ( | |
| torch.cuda.max_memory_allocated() / 2**30 | |
| ) | |
| metrics["peak_memory_reserved_gb"] = ( | |
| torch.cuda.max_memory_reserved() / 2**30 | |
| ) | |
| print( | |
| f"METRICS step={state.global_step} " | |
| f"steps_per_second={metrics['steps_per_second']:.5f} " | |
| f"peak_allocated_gib={metrics.get('peak_memory_allocated_gb', 0):.2f} " | |
| f"peak_reserved_gib={metrics.get('peak_memory_reserved_gb', 0):.2f} " | |
| f"logs={logs}", | |
| flush=True, | |
| ) | |
| if TRACKIO_READY: | |
| try: | |
| trackio.log(metrics, step=state.global_step) | |
| except Exception as exc: | |
| print(f"trackio.log failed ({exc}); disabling tracking", flush=True) | |
| TRACKIO_READY = False | |
| def main(): | |
| assert torch.cuda.is_available(), "CUDA GPU required" | |
| print( | |
| f"torch={torch.__version__} cuda={torch.version.cuda} " | |
| f"gpu={torch.cuda.get_device_name(0)} " | |
| f"memory_gib={torch.cuda.get_device_properties(0).total_memory / 2**30:.1f}", | |
| flush=True, | |
| ) | |
| train_ds = load_split("train") | |
| eval_ds = load_split("eval").select(range(32)) | |
| assert len(train_ds) == 51496 and len(eval_ds) == 32 | |
| print(f"train {len(train_ds)} rows, eval {len(eval_ds)} rows", flush=True) | |
| tok = AutoTokenizer.from_pretrained(MODEL_ID) | |
| sample_text = tok.apply_chat_template( | |
| train_ds[0]["prompt"] + train_ds[0]["completion"], tokenize=False | |
| ) | |
| assert sample_text and tok(sample_text)["input_ids"] | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_ID, dtype="bfloat16", attn_implementation="sdpa" | |
| ) | |
| model.config.use_cache = False | |
| total_params = sum(p.numel() for p in model.parameters()) | |
| trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) | |
| assert total_params == trainable_params and trainable_params > 1_000_000_000 | |
| print(f"full-parameter training: {trainable_params:,} trainable parameters", flush=True) | |
| cfg = SFTConfig( | |
| output_dir=OUTPUT_DIR, | |
| run_name=os.environ.get("RUN_NAME", "qwen3-1.7b-python-drawing-a100"), | |
| bf16=True, | |
| max_length=MAX_LENGTH, | |
| packing=False, | |
| completion_only_loss=True, | |
| per_device_train_batch_size=8, | |
| per_device_eval_batch_size=1, | |
| gradient_accumulation_steps=2, | |
| learning_rate=1e-5, | |
| lr_scheduler_type="cosine", | |
| warmup_steps=0 if SMOKE_STEPS else 100, | |
| num_train_epochs=1, | |
| activation_checkpointing=USE_ACTIVATION_CHECKPOINTING, | |
| eval_strategy="no" if SMOKE_STEPS else "steps", | |
| eval_steps=100, | |
| logging_steps=2 if SMOKE_STEPS else 10, | |
| save_strategy="no" if SMOKE_STEPS else "steps", | |
| save_steps=250, | |
| save_total_limit=2, | |
| dataset_num_proc=8, | |
| report_to="none", | |
| push_to_hub=bool(int(os.environ.get("PUSH_TO_HUB", "0"))), | |
| hub_strategy="end", | |
| hub_model_id=HUB_MODEL_ID, | |
| hub_token=os.environ.get("HF_TOKEN"), | |
| max_steps=SMOKE_STEPS or -1, | |
| seed=42, | |
| ) | |
| print( | |
| f"activation_checkpointing={USE_ACTIVATION_CHECKPOINTING} " | |
| f"config_activation_checkpointing={getattr(cfg, 'activation_checkpointing', None)} " | |
| f"config_gradient_checkpointing={getattr(cfg, 'gradient_checkpointing', None)}", | |
| flush=True, | |
| ) | |
| global TRACKIO_READY | |
| try: | |
| trackio.init(project=TRACKIO_PROJECT, space_id=TRACKIO_SPACE_ID) | |
| TRACKIO_READY = True | |
| print(f"trackio initialized: {TRACKIO_SPACE_ID}", flush=True) | |
| except Exception as exc: | |
| print(f"trackio.init failed ({exc}); logging disabled", flush=True) | |
| trainer = SFTTrainer( | |
| model=model, | |
| args=cfg, | |
| train_dataset=train_ds, | |
| eval_dataset=None if SMOKE_STEPS else eval_ds, | |
| processing_class=tok, | |
| callbacks=[MetricsCallback()], | |
| ) | |
| trainer.train() | |
| if SMOKE_STEPS: | |
| print("SMOKE DONE", flush=True) | |
| if TRACKIO_READY: | |
| trackio.finish() | |
| return | |
| trainer.save_model(os.path.join(OUTPUT_DIR, "final")) | |
| if cfg.push_to_hub: | |
| trainer.push_to_hub(dataset_name=DATASET_REPO) | |
| print(f"pushed to https://huggingface.co/{HUB_MODEL_ID}", flush=True) | |
| if TRACKIO_READY: | |
| trackio.finish() | |
| if __name__ == "__main__": | |
| main() | |