Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit
Llama-3.1-Nemotron-Nano-8B-v1 to bnb 4bit
tobit4
Use System Ubuntu 22.04
install Software
pip transformers bitsandbytes accelerate
to bnb 4bit
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
import bitsandbytes as bnb
# Define the model name and path
model_name = "nvidia/Llama-3.1-Nemotron-Nano-8B-v1"
# Configure quantization parameters
quantization_config = BitsAndBytesConfig(
load_in_4bit=True, # Load the model weights in 4-bit precision
bnb_4bit_compute_dtype=torch.bfloat16, # Use bfloat16 for computation
bnb_4bit_quant_type="nf4", # Use "nf4" quantization type
bnb_4bit_use_double_quant=True, # Enable double quantization
llm_int8_skip_modules=[ # Specify modules to skip during quantization
"lm_head",
"multi_modal_projector",
"merger",
"modality_projection",
"model.layers.1.mlp"
],
)
# Load the pre-trained model with the specified quantization configuration
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=quantization_config,
device_map="auto" # Automatically allocate devices
)
# Load the tokenizer associated with the model
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Save the quantized model and tokenizer to a specified directory
model.save_pretrained("Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit")
tokenizer.save_pretrained("Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit")
Chat Test
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
# Configure quantization parameters
quantization_config = BitsAndBytesConfig(
load_in_4bit=True, # Load the model weights in 4-bit precision
bnb_4bit_compute_dtype=torch.bfloat16, # Use bfloat16 for computation
bnb_4bit_quant_type="nf4", # Use "nf4" quantization type
bnb_4bit_use_double_quant=True, # Enable double quantization
)
# Define the model name and path for the quantized model
model_name = "./Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit"
# Load the quantized model with the specified configuration
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=quantization_config,
device_map="auto" # Automatically allocate devices
)
# Load the tokenizer associated with the model
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Determine the device where the model is located
device = model.device
# Prepare input text and move it to the same device as the model
input_text = "Once upon a time"
inputs = tokenizer(input_text, return_tensors="pt").to(device)
# Perform inference
with torch.no_grad():
outputs = model.generate(**inputs, max_length=50)
# Decode the generated text
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
unsloth Train examples
python3 -m venv Llama-3.1-Nemotron-Nano-Train
source Llama-3.1-Nemotron-Nano-Train/bin/activate
pip install unsloth
from unsloth import FastLanguageModel
import torch
# Define model parameters
max_seq_length = 2048 # Maximum sequence length for the model
dtype = None # Automatically detect data type; use Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4-bit quantization to reduce memory usage
# Load the pre-trained model and tokenizer
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="aifeifei798/Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit", # Local path to the model
max_seq_length=max_seq_length,
dtype=dtype,
load_in_4bit=load_in_4bit,
# token="hf_...", # Use a token if using gated models like meta-llama/Llama-2-7b-hf
)
# Apply PEFT (Parameter-Efficient Fine-Tuning) to the model
model = FastLanguageModel.get_peft_model(
model,
r=16, # Rank for LoRA (Low-Rank Adaptation); choose any number > 0
target_modules=[ # Target modules for LoRA
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
],
lora_alpha=16, # Scaling factor for LoRA
lora_dropout=0, # Dropout rate for LoRA
bias="none", # Bias setting for LoRA
use_gradient_checkpointing="unsloth", # Use gradient checkpointing for memory efficiency
random_state=3407,
use_rslora=False, # Option to use rank-stabilized LoRA
loftq_config=None, # Configuration for LoftQ
)
from datasets import load_dataset
# Define a function to format prompts
def formatting_prompts_func(examples):
texts = []
inputs = examples["input"]
outputs = examples["output"]
for input, output in zip(inputs, outputs):
text = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
detailed thinking on<|eot_id|><|start_header_id|>user<|end_header_id|>
{input}<|eot_id|><|start_header_id|>assistant<|end_header_id|>{output}<|eot_id|>"""
texts.append(text)
return {"text": texts}
# Load the dataset
dataset = load_dataset("aifeifei798/Chinese-DeepSeek-R1-Distill-data-110k-alpaca", split="train")
# Apply the formatting function to the dataset
dataset = dataset.map(formatting_prompts_func, batched=True)
print(dataset[0]) # Print the first example to verify formatting
from trl import SFTTrainer
from transformers import TrainingArguments, DataCollatorForSeq2Seq
from unsloth import is_bfloat16_supported
# Initialize the trainer for supervised fine-tuning
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
dataset_text_field="text",
max_seq_length=max_seq_length,
dataset_num_proc=16,
packing=False, # Disable packing for potentially faster training with short sequences
args=TrainingArguments(
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
warmup_steps=5,
max_steps=30, # Set the number of training steps, The recommended number of training steps is approximately 15,000.
learning_rate=2e-4,
fp16=not is_bfloat16_supported(), # Use FP16 if BF16 is not supported
bf16=is_bfloat16_supported(), # Use BF16 if supported
logging_steps=1,
optim="adamw_8bit", # Use 8-bit AdamW optimizer
weight_decay=0.01,
lr_scheduler_type="linear",
seed=3407,
output_dir="outputs",
report_to="none", # Disable reporting to external services
save_steps=5, # Save the model every 5 steps
save_total_limit=10 # Keep only the last 10 checkpoints
# load_best_model_at_end=False, # Ensure this is False to resume training
),
)
# Train the model
trainer_stats = trainer.train()
# Define the path to the latest checkpoint directory
# checkpoint_path = "outputs/checkpoint-XXXX" # Replace XXXX with the latest checkpoint step
# trainer.train(resume_from_checkpoint=checkpoint_path)
# Save the fine-tuned model and tokenizer
model.save_pretrained("Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit-lora")
tokenizer.save_pretrained("Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit-lora")
# Save the merged model and tokenizer
model.save_pretrained_merged("Llama-3.1-Nemotron-Nano-8B-v1-bnb-Chinese", tokenizer)
bit4 model
Llama-3.1-Nemotron-Nano-8B-v1-bnb-4bit
Llama-3.1-Nemotron-Nano-8B-v1
Model Overview
Llama-3.1-Nemotron-Nano-8B-v1 is a large language model (LLM) which is a derivative of Meta Llama-3.1-8B-Instruct (AKA the reference model). It is a reasoning model that is post trained for reasoning, human chat preferences, and tasks, such as RAG and tool calling.
Llama-3.1-Nemotron-Nano-8B-v1 is a model which offers a great tradeoff between model accuracy and efficiency. It is created from Llama 3.1 8B Instruct and offers improvements in model accuracy. The model fits on a single RTX GPU and can be used locally. The model supports a context length of 128K.
This model underwent a multi-phase post-training process to enhance both its reasoning and non-reasoning capabilities. This includes a supervised fine-tuning stage for Math, Code, Reasoning, and Tool Calling as well as multiple reinforcement learning (RL) stages using REINFORCE (RLOO) and Online Reward-aware Preference Optimization (RPO) algorithms for both chat and instruction-following. The final model checkpoint is obtained after merging the final SFT and Online RPO checkpoints. Improved using Qwen.
This model is part of the Llama Nemotron Collection. You can find the other model(s) in this family here: Llama-3.3-Nemotron-Super-49B-v1
This model is ready for commercial use.
License/Terms of Use
GOVERNING TERMS: Your use of this model is governed by the NVIDIA Open Model License. Additional Information: Llama 3.1 Community License Agreement. Built with Llama.
Model Developer: NVIDIA
Model Dates: Trained between August 2024 and March 2025
Data Freshness: The pretraining data has a cutoff of 2023 per Meta Llama 3.1 8B
Use Case:
Developers designing AI Agent systems, chatbots, RAG systems, and other AI-powered applications. Also suitable for typical instruction-following tasks. Balance of model accuracy and compute efficiency (the model fits on a single RTX GPU and can be used locally).
Release Date:
3/18/2025
References
Model Architecture
Architecture Type: Dense decoder-only Transformer model
Network Architecture: Llama 3.1 8B Instruct
Intended use
Llama-3.1-Nemotron-Nano-8B-v1 is a general purpose reasoning and chat model intended to be used in English and coding languages. Other non-English languages (German, French, Italian, Portuguese, Hindi, Spanish, and Thai) are also supported.
Input:
- Input Type: Text
- Input Format: String
- Input Parameters: One-Dimensional (1D)
- Other Properties Related to Input: Context length up to 131,072 tokens
Output:
- Output Type: Text
- Output Format: String
- Output Parameters: One-Dimensional (1D)
- Other Properties Related to Output: Context length up to 131,072 tokens
Model Version:
1.0 (3/18/2025)
Software Integration
- Runtime Engine: NeMo 24.12
- Recommended Hardware Microarchitecture Compatibility:
- NVIDIA Hopper
- NVIDIA Ampere
Quick Start and Usage Recommendations:
- Reasoning mode (ON/OFF) is controlled via the system prompt, which must be set as shown in the example below. All instructions should be contained within the user prompt
- We recommend setting temperature to
0.6
, and Top P to0.95
for Reasoning ON mode - We recommend using greedy decoding for Reasoning OFF mode
- We have provided a list of prompts to use for evaluation for each benchmark where a specific template is required
You can try this model out through the preview API, using this link: Llama-3.1-Nemotron-Nano-8B-v1.
See the snippet below for usage with Hugging Face Transformers library. Reasoning mode (ON/OFF) is controlled via system prompt. Please see the example below.
Our code requires the transformers package version to be 4.44.2
or higher.
Example of “Reasoning On:”
import torch
import transformers
model_id = "nvidia/Llama-3.1-Nemotron-Nano-8B-v1"
model_kwargs = {"torch_dtype": torch.bfloat16, "device_map": "auto"}
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token_id = tokenizer.eos_token_id
pipeline = transformers.pipeline(
"text-generation",
model=model_id,
tokenizer=tokenizer,
max_new_tokens=32768,
temperature=0.6,
top_p=0.95,
**model_kwargs
)
# Thinking can be "on" or "off"
thinking = "on"
print(pipeline([{"role": "system", "content": f"detailed thinking {thinking}"}, {"role": "user", "content": "Solve x*(sin(x)+2)=0"}]))
Example of “Reasoning Off:”
import torch
import transformers
model_id = "nvidia/Llama-3.1-Nemotron-Nano-8B-v1"
model_kwargs = {"torch_dtype": torch.bfloat16, "device_map": "auto"}
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token_id = tokenizer.eos_token_id
pipeline = transformers.pipeline(
"text-generation",
model=model_id,
tokenizer=tokenizer,
max_new_tokens=32768,
do_sample=False,
**model_kwargs
)
# Thinking can be "on" or "off"
thinking = "off"
print(pipeline([{"role": "system", "content": f"detailed thinking {thinking}"}, {"role": "user", "content": "Solve x*(sin(x)+2)=0"}]))
For some prompts, even though thinking is disabled, the model emergently prefers to think before responding. But if desired, the users can prevent it by pre-filling the assistant response.
import torch
import transformers
model_id = "nvidia/Llama-3.1-Nemotron-Nano-8B-v1"
model_kwargs = {"torch_dtype": torch.bfloat16, "device_map": "auto"}
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token_id = tokenizer.eos_token_id
# Thinking can be "on" or "off"
thinking = "off"
pipeline = transformers.pipeline(
"text-generation",
model=model_id,
tokenizer=tokenizer,
max_new_tokens=32768,
do_sample=False,
**model_kwargs
)
print(pipeline([{"role": "system", "content": f"detailed thinking {thinking}"}, {"role": "user", "content": "Solve x*(sin(x)+2)=0"}, {"role":"assistant", "content":"<think>\n</think>"}]))
Inference:
Engine: Transformers Test Hardware:
- BF16:
- 1x RTX 50 Series GPUs
- 1x RTX 40 Series GPUs
- 1x RTX 30 Series GPUs
- 1x H100-80GB GPU
- 1x A100-80GB GPU
Preferred/Supported] Operating System(s): Linux
Training Datasets
A large variety of training data was used for the post-training pipeline, including manually annotated data and synthetic data.
The data for the multi-stage post-training phases for improvements in Code, Math, and Reasoning is a compilation of SFT and RL data that supports improvements of math, code, general reasoning, and instruction following capabilities of the original Llama instruct model.
Prompts have been sourced from either public and open corpus or synthetically generated. Responses were synthetically generated by a variety of models, with some prompts containing responses for both Reasoning On and Off modes, to train the model to distinguish between two modes.
Data Collection for Training Datasets:
- Hybrid: Automated, Human, Synthetic
Data Labeling for Training Datasets:
- N/A
Evaluation Datasets
We used the datasets listed below to evaluate Llama-3.1-Nemotron-Nano-8B-v1.
Data Collection for Evaluation Datasets: Hybrid: Human/Synthetic
Data Labeling for Evaluation Datasets: Hybrid: Human/Synthetic/Automatic
Evaluation Results
These results contain both “Reasoning On”, and “Reasoning Off”. We recommend using temperature=0.6
, top_p=0.95
for “Reasoning On” mode, and greedy decoding for “Reasoning Off” mode. All evaluations are done with 32k sequence length. We run the benchmarks up to 16 times and average the scores to be more accurate.
NOTE: Where applicable, a Prompt Template will be provided. While completing benchmarks, please ensure that you are parsing for the correct output format as per the provided prompt in order to reproduce the benchmarks seen below.
MT-Bench
Reasoning Mode | Score |
---|---|
Reasoning Off | 7.9 |
Reasoning On | 8.1 |
MATH500
Reasoning Mode | pass@1 |
---|---|
Reasoning Off | 36.6% |
Reasoning On | 95.4% |
User Prompt Template:
"Below is a math question. I want you to reason through the steps and then give a final answer. Your final answer should be in \boxed{}.\nQuestion: {question}"
AIME25
Reasoning Mode | pass@1 |
---|---|
Reasoning Off | 0% |
Reasoning On | 47.1% |
User Prompt Template:
"Below is a math question. I want you to reason through the steps and then give a final answer. Your final answer should be in \boxed{}.\nQuestion: {question}"
GPQA-D
Reasoning Mode | pass@1 |
---|---|
Reasoning Off | 39.4% |
Reasoning On | 54.1% |
User Prompt Template:
"What is the correct answer to this question: {question}\nChoices:\nA. {option_A}\nB. {option_B}\nC. {option_C}\nD. {option_D}\nLet's think step by step, and put the final answer (should be a single letter A, B, C, or D) into a \boxed{}"
IFEval Average
Reasoning Mode | Strict:Prompt | Strict:Instruction |
---|---|---|
Reasoning Off | 74.7% | 82.1% |
Reasoning On | 71.9% | 79.3% |
BFCL v2 Live
Reasoning Mode | Score |
---|---|
Reasoning Off | 63.9% |
Reasoning On | 63.6% |
User Prompt Template:
<AVAILABLE_TOOLS>{functions}</AVAILABLE_TOOLS>
{user_prompt}
MBPP 0-shot
Reasoning Mode | pass@1 |
---|---|
Reasoning Off | 66.1% |
Reasoning On | 84.6% |
User Prompt Template:
You are an exceptionally intelligent coding assistant that consistently delivers accurate and reliable responses to user instructions.
@@ Instruction
Here is the given problem and test examples:
{prompt}
Please use the python programming language to solve this problem.
Please make sure that your code includes the functions from the test samples and that the input and output formats of these functions match the test samples.
Please return all completed codes in one code block.
This code block should be in the following format:
```python
# Your codes here
```
Ethical Considerations:
NVIDIA believes Trustworthy AI is a shared responsibility and we have established policies and practices to enable development for a wide array of AI applications. When downloaded or used in accordance with our terms of service, developers should work with their internal model team to ensure this model meets requirements for the relevant industry and use case and addresses unforeseen product misuse.
For more detailed information on ethical considerations for this model, please see the Model Card++ Explainability, Bias, Safety & Security, and Privacy Subcards.
Please report security vulnerabilities or NVIDIA AI Concerns here.
- Downloads last month
- 2