Download self_improve.py from unixdevil/social-media-post: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/datasets/unixdevil/social-media-post/resolve/main/self_improve.py
- Command line
-
hf download hf://datasets/unixdevil/social-media-post/self_improve.py
-
curl -L -o self_improve.py https://huggingface.co/datasets/unixdevil/social-media-post/resolve/main/self_improve.py
2.47 kB
| from datasets import load_dataset | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| import torch | |
| import json | |
| from tqdm import tqdm | |
| MODEL_NAME = "chat_model" # your fine-tuned model | |
| INPUT_FILE = "chatml_dataset.jsonl" | |
| OUTPUT_FILE = "augmented_dataset.jsonl" | |
| # ========================= | |
| # Load model | |
| # ========================= | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| torch_dtype=torch.float16, | |
| device_map="auto" | |
| ) | |
| # ========================= | |
| # Prompt builder | |
| # ========================= | |
| def build_prompt(messages): | |
| text = "" | |
| for msg in messages: | |
| if msg["role"] == "system": | |
| text += f"[SYSTEM] {msg['content']}\n" | |
| elif msg["role"] == "user": | |
| text += f"[USER] {msg['content']}\n" | |
| elif msg["role"] == "assistant": | |
| text += f"[ASSISTANT] {msg['content']}\n" | |
| return text | |
| # ========================= | |
| # Variation prompts | |
| # ========================= | |
| VARIATIONS = [ | |
| "Rewrite this to be more engaging.", | |
| "Make it shorter and punchier.", | |
| "Adapt this for TikTok audience.", | |
| "Make it more emotional and persuasive.", | |
| ] | |
| # ========================= | |
| # Generate | |
| # ========================= | |
| dataset = load_dataset("json", data_files=INPUT_FILE, split="train") | |
| with open(OUTPUT_FILE, "w") as f: | |
| for row in tqdm(dataset): | |
| base_messages = row["messages"] | |
| # write original | |
| f.write(json.dumps(row) + "\n") | |
| for variation in VARIATIONS: | |
| new_messages = base_messages.copy() | |
| new_messages.append({ | |
| "role": "user", | |
| "content": variation | |
| }) | |
| prompt = build_prompt(new_messages) | |
| inputs = tokenizer(prompt, return_tensors="pt").to(model.device) | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=150, | |
| temperature=0.8, | |
| top_p=0.9, | |
| do_sample=True | |
| ) | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # Extract only last assistant reply (simple cut) | |
| response = response.split("[ASSISTANT]")[-1].strip() | |
| new_messages.append({ | |
| "role": "assistant", | |
| "content": response | |
| }) | |
| f.write(json.dumps({"messages": new_messages}) + "\n") | |
| print("✅ Augmented dataset ready") | |