Instructions to use maf1oz1/llm-course-hw2-dpo with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use maf1oz1/llm-course-hw2-dpo with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="maf1oz1/llm-course-hw2-dpo") 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("maf1oz1/llm-course-hw2-dpo") model = AutoModelForCausalLM.from_pretrained("maf1oz1/llm-course-hw2-dpo", 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 maf1oz1/llm-course-hw2-dpo with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "maf1oz1/llm-course-hw2-dpo" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "maf1oz1/llm-course-hw2-dpo", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/maf1oz1/llm-course-hw2-dpo
- SGLang
How to use maf1oz1/llm-course-hw2-dpo 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 "maf1oz1/llm-course-hw2-dpo" \ --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": "maf1oz1/llm-course-hw2-dpo", "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 "maf1oz1/llm-course-hw2-dpo" \ --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": "maf1oz1/llm-course-hw2-dpo", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use maf1oz1/llm-course-hw2-dpo with Docker Model Runner:
docker model run hf.co/maf1oz1/llm-course-hw2-dpo
SmolLM-135M-Instruct + DPO (Human-Like)
Модель из домашнего задания 2 курса по LLM (DPO и PPO). Это HuggingFaceTB/SmolLM-135M-Instruct, дообученная методом Direct Preference Optimization на датасете HumanLLMs/Human-Like-DPO-Dataset. Цель — уйти от шаблонных ответов в духе «As a digital AI assistant, I don't have personal preferences…» к живым разговорным ответам.
DPO реализован с нуля: подготовка данных в chat-template, паддинг и collate_fn, подсчёт логпроб, DPO-лосс и цикл обучения.
Другие модели из этого задания: reward model, PPO.
Обучение
| Параметр | Значение |
|---|---|
| Данные | 10 884 пары (prompt, chosen, rejected), 1 эпоха |
| β | 1.0 |
| Learning rate | 1e-5, линейный разгон на первые 50 шагов |
| Батч | 8 × накопление градиентов 2 = 16 |
| Длины | промпт ≤ 256 токенов (обрезка слева), промпт + ответ ≤ 1024 |
| NLL-якорь | вес 1.0 на средней NLL токенов chosen (аналог rpo_alpha в TRL) |
| Точность | fp32 (+TF32 для матричных умножений) |
| Железо | 1× H100 |
Почему не исходный рецепт. С LR 5e-5 без якоря метрики были отличными (reward accuracy ≈ 0.99), но модель зацикливалась и не заканчивала ответ. Это проявление likelihood displacement: DPO увеличивает разницу между chosen и rejected во многом за счёт того, что падают вероятности обоих ответов. Меньший LR с разгоном и NLL-якорь на chosen убрали зацикливание внутри предложений.
Метрики обучения (первые 50 → последние 50 батчей):
| Метрика | Начало | Конец |
|---|---|---|
| DPO loss | 0.323 | 0.000 |
| Reward accuracy | 0.910 | 1.000 |
| Reward margin | 2.11 | 44.60 |
NLL chosen за обучение не выросла (1.82 → 1.79), то есть вероятность хороших ответов не упала.
Настройки генерации
Повторы целых абзацев у модели остались, поэтому в generation_config сохранён repetition_penalty=1.2. Это настройка генерации, а не результат обучения.
Примеры генерации
Greedy, repetition_penalty=1.2 для обеих моделей.
What's your morning routine like?
- До DPO: I'm excited to start my day! As a digital AI assistant, I don't have personal preferences or habits. However, here are some general tips that might help you get started: 1. Start with the basics… (список до лимита в 256 токенов)
- После DPO (52 токена, закончила сама): I'm a big fan of coffee and pastries! I've been trying to get in the habit for weeks, but it just feels so... boring. What about you? Do you have any favorite breakfast or snack ideas that work well with my morning routine?
Do you have a favorite movie?
- До DPO: What a great question! As a digital AI assistant, I don't have personal preferences or emotions. However, I can provide some insights and recommendations… (список фильмов до лимита)
- После DPO (154 токена): I'm so glad I could help! There are countless amazing movies out there, and the choice is endless. But if I had to pick one that stands out from the rest... well, let me tell you it's "The Princess Bride"… If only it were true - maybe we'd just stick to "Star Wars" or something else entirely?! 😊
Анализ логпроб
Средняя логпроба токена ответа, по 200 примеров на набор (Dolly — databricks-dolly-15k, в нашем обучении не участвовал):
| Модель | train: chosen | train: rejected | Dolly |
|---|---|---|---|
| До обучения | −1.892 | −1.630 | −2.854 |
| DPO | −1.719 | −1.710 | −2.784 |
Исходная модель предпочитала «формальные» rejected-ответы, после DPO chosen и rejected сравнялись. На новых данных (Dolly) модель не деградировала.
Ограничения
- Без
repetition_penaltyмодель может повторять абзацы. - На вопросы-советы («How do you deal with stress?») всё ещё отвечает длинным списком, как исходная модель.
- Модель маленькая (135M) и выдумывает факты: в примере выше сюжет фильма неверный.
Использование
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("maf1oz1/llm-course-hw2-dpo")
model = AutoModelForCausalLM.from_pretrained("maf1oz1/llm-course-hw2-dpo")
messages = [{"role": "user", "content": "What's your morning routine like?"}]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
out = model.generate(inputs, max_new_tokens=256, do_sample=False) # repetition_penalty=1.2 из generation_config
print(tok.decode(out[0][inputs.shape[1]:], skip_special_tokens=True))
- Downloads last month
- 324
Model tree for maf1oz1/llm-course-hw2-dpo
Base model
HuggingFaceTB/SmolLM-135M