Views
No views yet
HuggingFaceH4/Multilingual-Thinking dataset, which contains chain-of-thought examples translated into different languages. This approach aims to equip the model with better analytical and problem-solving skills, particularly in diverse linguistic contexts.reasoning_effort parameter allows users to explicitly control the trade-off between the model's performance and response speed. You can set it to low for fast, direct answers, medium for a balanced approach, or high for complex tasks requiring extensive multi-step reasoning. This flexibility enables the model to adapt to various application requirements.Multilingual-Thinking dataset, the model has learned to apply reasoning processes in different languages. This enhances its utility for global applications where understanding and responding in various languages is essential.1!pip install --upgrade -qqq uv
2!uv pip install -qqq "torch>=2.8.0" "triton>=3.4.0" numpy pillow torchvision bitsandbytes "transformers==4.56.2" "unsloth_zoo[base] @ git+https://github.com/unslothai/unsloth-zoo" "unsloth[base] @ git+https://github.com/unslothai/unsloth" git+https://github.com/triton-lang/triton.git@0add68262ab0a2e33b84524346cb27cbb2787356#subdirectory=python/triton_kernels
3!uv pip install --upgrade --no-deps transformers==4.56.2 tokenizers trl==0.22.2 unsloth unsloth_zooreasoning_effort parameter. This example showcases how to solve a mathematical problem with 'high' reasoning effort in French.1from unsloth import FastLanguageModel
2from transformers import TextStreamer
3
4# Load the fine-tuned model from Hugging Face Hub
5# The 'max_seq_length' determines the maximum token limit for input and output.
6# 'load_in_4bit=True' uses 4-bit quantization for reduced memory usage.
7model, tokenizer = FastLanguageModel.from_pretrained(
8 model_name = "adityatiwari12/gpt_oss_lora", # Your fine-tuned model repository ID
9 max_seq_length = 1024,
10 dtype = None, # Auto detects the optimal data type based on your GPU
11 load_in_4bit = True,
12)
13
14# Define the conversation messages. The 'system' message sets the model's persona and language.
15# The 'user' message is the query for the model to solve.
16messages = [
17 {"role": "system", "content": "reasoning language: French
18
19You are a helpful assistant that can solve mathematical problems."},
20 {"role": "user", "content": "Solve x^5 + 3x^4 - 10 = 3."},
21]
22
23# Apply the chat template and set generation parameters.
24# 'add_generation_prompt=True' adds a prompt to guide the model's response.
25# 'reasoning_effort' is set to 'high' for a more detailed problem-solving approach.
26inputs = tokenizer.apply_chat_template(
27 messages,
28 add_generation_prompt = True,
29 return_tensors = "pt",
30 return_dict = True,
31 reasoning_effort = "high", # Choose 'low', 'medium', or 'high' for different reasoning depths
32).to("cuda")
33
34# Generate the model's response. 'max_new_tokens' limits the output length.
35# 'streamer' enables real-time token generation output.
36_ = model.generate(**inputs, max_new_tokens = 64, streamer = TextStreamer(tokenizer))HuggingFaceH4/Multilingual-Thinking dataset. The training process utilized LoRA adapters for efficiency and Unsloth's train_on_responses_only method. This method ensures that the loss is only computed on the assistant's responses, making the fine-tuning more effective and accurate by focusing on generating correct outputs rather than mimicking the entire conversation flow.1from trl import SFTConfig, SFTTrainer
2from datasets import load_dataset
3from unsloth.chat_templates import standardize_sharegpt, train_on_responses_only
4
5# (Assuming model and tokenizer are already loaded and configured with LoRA adapters)
6# Load and preprocess the dataset from Hugging Face. The 'train' split is used for training.
7dataset = load_dataset("HuggingFaceH4/Multilingual-Thinking", split = "train")
8
9# Define a formatting function to structure the dataset examples into a chat template.
10def formatting_prompts_func(examples):
11 convos = examples["messages"]
12 # Apply the tokenizer's chat template to format conversations, without adding a generation prompt.
13 texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
14 return { "text" : texts, }
15
16# Standardize the dataset format using Unsloth's utility and then map the formatting function.
17dataset = standardize_sharegpt(dataset)
18dataset = dataset.map(formatting_prompts_func, batched = True,)
19
20# Configure and initialize the SFTTrainer for supervised fine-tuning.
21trainer = SFTTrainer(
22 model = model, # The pre-trained model with LoRA adapters
23 tokenizer = tokenizer, # The tokenizer corresponding to the model
24 train_dataset = dataset, # The prepared training dataset
25 args = SFTConfig(
26 per_device_train_batch_size = 1, # Number of samples per training device
27 gradient_accumulation_steps = 4, # Accumulate gradients over multiple steps to simulate a larger batch size
28 warmup_steps = 5, # Number of steps for learning rate warmup
29 max_steps = 30, # Maximum number of training steps (set `num_train_epochs` for full run)
30 learning_rate = 2e-4, # Initial learning rate for the optimizer
31 logging_steps = 1, # Log training metrics every N steps
32 optim = "adamw_8bit", # 8-bit AdamW optimizer for memory efficiency
33 weight_decay = 0.001, # L2 regularization to prevent overfitting
34 lr_scheduler_type = "linear", # Linear learning rate scheduler
35 seed = 3407, # Random seed for reproducibility
36 output_dir = "outputs", # Directory to save checkpoints and logs
37 report_to = "none", # Disable reporting to external services like Weights & Biases
38 ),
39)
40
41# Apply Unsloth's `train_on_responses_only` to mask out instruction tokens.
42# This ensures the model only learns from the assistant's desired responses.
43gpt_oss_kwargs = dict(instruction_part = "<|start|>user<|message|>", response_part = "<|start|>assistant<|channel|>final<|message|>")
44trainer = train_on_responses_only(trainer, **gpt_oss_kwargs)
45
46# Start the training process.
47trainer_stats = trainer.train()1# Save LoRA adapters locally to a specified directory.
2# This creates a 'gpt_oss_lora' directory containing the adapter weights.
3model.save_pretrained("gpt_oss_lora")
4
5# Push the fine-tuned LoRA adapters to your Hugging Face Hub repository.
6# Replace 'YOUR_HF_TOKEN' with your actual Hugging Face write token.
7# model.push_to_hub("adityatiwari12/gpt_oss_lora", token = "YOUR_HF_TOKEN")
8
9# To load the model for inference in a new Colab instance or environment:
10# Ensure Unsloth is installed and then load the model and tokenizer directly.
11# The 'model_name' should be your Hugging Face repository ID or the local directory name.
12# from unsloth import FastLanguageModel
13# model, tokenizer = FastLanguageModel.from_pretrained(
14# model_name = "adityatiwari12/gpt_oss_lora", # Your Hugging Face model repository or local path
15# max_seq_length = 1024,
16# dtype = None,
17# load_in_4bit = True,
18# )