Full SFT Customization

View as Markdown

Run in Google Colab

Full SFT Customization

Learn how to fine-tune all model weights using supervised fine-tuning (SFT) to customize LLM behavior for your specific tasks.

About

Supervised Fine-Tuning (SFT) customizes model behavior, injects new knowledge, and optimizes performance for specific domains and tasks. Full SFT modifies all model weights during training, providing maximum customization flexibility.

What you can achieve with SFT:

  • 🎯 Specialize for domains: Fine-tune models on legal texts, medical records, or financial data
  • 💡 Inject knowledge: Add new information not present in the base model
  • 📈 Improve accuracy: Optimize for specific tasks like sentiment analysis, summarization, or code generation

SFT vs LoRA: Understanding the Trade-offs

Full SFT trains all model parameters (for example, all 70 billion weights in Llama 70B):

  • ✅ Maximum model adaptation and knowledge injection
  • ✅ Can fundamentally change model behavior
  • ✅ Best for significant domain shifts or specialized tasks
  • ❌ Requires substantial GPU resources (4-8x more than LoRA)
  • ❌ Produces full model weights (~140GB for Llama 70B)
  • ❌ Longer training time

LoRA trains only ~1% of weights by adding thin matrices to existing weights:

  • ✅ 75-95% less memory required
  • ✅ Faster training (2-4x speedup)
  • ✅ Produces small adapter files (~100-500MB)
  • ✅ Multiple adapters can share one base model
  • ❌ Limited adaptation capability compared to full fine-tuning

When to choose Full SFT:

  • Training small models (1B-8B) where resource cost is manageable
  • Need fundamental behavior changes (for example, medical diagnosis, legal reasoning)
  • Injecting substantial new knowledge not in the base model

When to choose LoRA: Refer to the LoRA tutorial for most use cases, especially with large models (70B+) or limited GPU resources.

Prerequisites

Before starting this tutorial, ensure you have:

  1. Completed the Quickstart to install and deploy NeMo Platform locally
  2. Installed the Python SDK (PyPI wrapper: pip install "nemo-platform[all]"; source checkout: run make bootstrap from the repository root)

Quick Start

1. Initialize SDK

The SDK needs to know your NeMo Platform server URL. By default, http://localhost:8080 is used in accordance with the Quickstart guide. If NeMo Platform is running at a custom location, you can override the URL by setting the NMP_BASE_URL environment variable:

1export NMP_BASE_URL=<YOUR_NMP_BASE_URL>
1import json
2import os
3from nemo_platform import NeMoPlatform, ConflictError
4
5NMP_BASE_URL = os.environ.get("NMP_BASE_URL", "http://localhost:8080")
6client = NeMoPlatform(
7 base_url=NMP_BASE_URL,
8 workspace="default"
9)

2. Prepare Dataset

Create your data in JSONL format—one JSON object per line. The platform auto-detects your data format. Supported dataset formats are listed below.

Flexible Data Setup:

  • No validation file? The platform automatically creates a 10% validation split
  • Multiple files? Upload to training/ or validation/ subdirectories—they will be automatically merged
  • Format detection: Your data format is auto-detected at training time

In this tutorial the following dataset directory structure will be used:

my_dataset
`-- training.jsonl
`-- validation.jsonl

Simple Prompt/Completion Format

The simplest format with input prompt and expected completion:

  • prompt: The input prompt for the model
  • completion: The expected output response
1{"prompt": "Write an email to confirm our hotel reservation.", "completion": "Dear Hotel Team, I am writing to confirm our reservation for two guests..."}

Chat Format (for conversational models)

For multi-turn conversations, use the messages format:

  • messages: List of message objects with role and content fields
  • Roles: system, user, assistant
1{"messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is AI?"}, {"role": "assistant", "content": "AI is..."}]}

Custom Format (specify columns in job)

You can use custom field names and map them during job creation:

  • Define your own field names
  • Map them to prompt/completion in the job configuration
1{"question": "What is 2+2?", "answer": "4"}

3. Create Dataset FileSet and Upload Training Data

Install huggingface datasets package to download public rajpurkar/squad dataset if it is not installed in your Python environment:

1pip install datasets

Download rajpurkar/squad Dataset

SQuAD (Stanford Question Answering Dataset) is a reading comprehension dataset consisting of questions posed on Wikipedia articles, where the answer is a segment of text from the corresponding passage.

1from pathlib import Path
2from datasets import load_dataset, DatasetDict
3import json
4
5# Load the SQuAD dataset from Hugging Face
6print("Loading dataset rajpurkar/squad")
7raw_dataset = load_dataset("rajpurkar/squad")
8if not isinstance(raw_dataset, DatasetDict):
9 raise ValueError("Dataset does not contain expected splits")
10
11print("Loaded dataset")
12
13# Configuration
14VALIDATION_PROPORTION = 0.05
15SEED = 1234
16
17# For the purpose of this tutorial, we'll use a subset of the dataset
18# The larger the datasets, the better the model will perform but longer the training will take
19training_size = 3000
20validation_size = 300
21DATASET_PATH = Path("sft-dataset").absolute()
22
23# Create directory if it doesn't exist
24os.makedirs(DATASET_PATH, exist_ok=True)
25
26# Get the train split and create a validation split from it
27train_set = raw_dataset.get('train')
28split_dataset = train_set.train_test_split(test_size=VALIDATION_PROPORTION, seed=SEED)
29
30# Select subsets for the tutorial
31train_ds = split_dataset['train'].select(range(min(training_size, len(split_dataset['train']))))
32validation_ds = split_dataset['test'].select(range(min(validation_size, len(split_dataset['test']))))
33
34# Convert SQuAD format to prompt/completion format and save to JSONL
35def convert_squad_to_sft_format(example):
36 """Convert SQuAD format to prompt/completion format for SFT training."""
37 prompt = f"Context: {example['context']} Question: {example['question']} Answer:"
38 completion = example["answers"]["text"][0] # Take the first answer
39 return {"prompt": prompt, "completion": completion}
40
41# Save training data
42with open(f"{DATASET_PATH}/training.jsonl", "w", encoding="utf-8") as f:
43 for example in train_ds:
44 converted = convert_squad_to_sft_format(example)
45 f.write(json.dumps(converted) + "\n")
46
47# Save validation data
48with open(f"{DATASET_PATH}/validation.jsonl", "w", encoding="utf-8") as f:
49 for example in validation_ds:
50 converted = convert_squad_to_sft_format(example)
51 f.write(json.dumps(converted) + "\n")
52
53print(f"Saved training.jsonl with {len(train_ds)} rows")
54print(f"Saved validation.jsonl with {len(validation_ds)} rows")
55
56# Show a sample from the training data
57print("\nSample from training data:")
58with open(f"{DATASET_PATH}/training.jsonl", 'r') as f:
59 first_line = f.readline()
60 sample = json.loads(first_line)
61 print(f"Prompt: {sample['prompt'][:200]}...")
62 print(f"Completion: {sample['completion']}")
1# Create fileset to store SFT training data
2DATASET_NAME = "sft-dataset"
3
4try:
5 client.files.filesets.create(
6 workspace="default",
7 name=DATASET_NAME,
8 description="SFT training data"
9 )
10 print(f"Created fileset: {DATASET_NAME}")
11except ConflictError:
12 print(f"Fileset '{DATASET_NAME}' already exists, continuing...")
13
14# Upload training data files individually to ensure correct structure
15client.files.upload(
16 local_path=f"{DATASET_PATH}/", # Trailing slash uploads directory contents to fileset root
17 remote_path="",
18 fileset=DATASET_NAME,
19 workspace="default"
20)
21
22# Validate training data is uploaded correctly
23print("Training data:")
24print(json.dumps([f.model_dump() for f in client.files.list(fileset=DATASET_NAME, workspace="default").data], indent=2))

4. Secrets Setup

If you plan to use NGC or HuggingFace models, you will need to configure authentication:

  • NGC models (ngc:// URIs): Requires NGC API key
  • HuggingFace models (hf:// URIs): Requires HF token for gated/private models

Configure these as secrets in your platform. Refer to Managing Secrets for detailed instructions.

Get your credentials to access base models:


Quick Setup Example

In this tutorial we are going to work with meta-llama/Llama-3.2-1B-Instruct model from HuggingFace. Ensure that you have sufficient permissions to download the model. If you cannot access the files on the meta-llama/Llama-3.2-1B-Instruct Hugging Face page, request access.

HuggingFace Authentication:

  • For gated models (Llama, Gemma), you must provide a HuggingFace token via the token_secret parameter
  • Get your token from HuggingFace Settings (requires Read access)
  • Accept the model’s terms on the HuggingFace model page before using it. Example: meta-llama/Llama-3.2-1B-Instruct
  • For public models, you can omit the token_secret parameter when creating a fileset for model in the next step
1# Export the HF_TOKEN and NGC_API_KEY environment variables if they are not already set
2HF_TOKEN = os.getenv("HF_TOKEN")
3NGC_API_KEY = os.getenv("NGC_API_KEY")
4
5
6def create_or_get_secret(name: str, value: str | None, label: str):
7 if not value:
8 raise ValueError(f"{label} is not set")
9 try:
10 secret = client.secrets.create(
11 name=name,
12 workspace="default",
13 value=value,
14 )
15 print(f"Created secret: {name}")
16 return secret
17 except ConflictError:
18 print(f"Secret '{name}' already exists, continuing...")
19 return client.secrets.retrieve(name=name, workspace="default")
20
21
22# Create HuggingFace token secret
23hf_secret = create_or_get_secret("hf-token", HF_TOKEN, "HF_TOKEN")
24print("HF_TOKEN secret:")
25print(hf_secret.model_dump_json(indent=2))
26
27# Create NGC API key secret
28# Uncomment the line below if you have NGC API Key and want to finetune NGC models
29# ngc_api_key = create_or_get_secret("ngc-api-key", NGC_API_KEY, "NGC_API_KEY")

5. Create Base Model FileSet and Model Entity

Create a fileset pointing to meta-llama/Llama-3.2-1B-Instruct model in HuggingFace that we will train with SFT. Then create a Model Entity that references this fileset. Model downloading will take place at training time.

Note: for public models, you can omit the token_secret parameter when creating a model fileset.

1import time
2
3# Create a fileset pointing to the desired HuggingFace model
4from nemo_platform.types.files import HuggingfaceStorageConfigParam
5
6HF_REPO_ID = "meta-llama/Llama-3.2-1B-Instruct"
7MODEL_NAME = "llama-3-2-1b-base"
8
9# Ensure you have a HuggingFace token secret created
10try:
11 base_model_fs = client.files.filesets.create(
12 workspace="default",
13 name=MODEL_NAME,
14 description="Llama 3.2 1B base model from HuggingFace",
15 storage=HuggingfaceStorageConfigParam(
16 type="huggingface",
17 # repo_id is the full model name from Hugging Face
18 repo_id=HF_REPO_ID,
19 repo_type="model",
20 # we use the secret created in the previous step
21 token_secret=hf_secret.name
22 )
23 )
24 print(f"Created base model fileset: {MODEL_NAME}")
25except ConflictError:
26 print(f"Base model fileset already exists. Skipping creation.")
27 base_model_fs = client.files.filesets.retrieve(
28 workspace="default",
29 name=MODEL_NAME,
30 )
31
32# Create the Model Entity representation.
33try:
34 base_model = client.models.create(
35 workspace="default",
36 name=MODEL_NAME,
37 fileset=f"default/{MODEL_NAME}",
38 )
39 print(f"Created Model Entity: {MODEL_NAME}")
40except ConflictError:
41 print(f"Base model already exists. Updating fileset if different.")
42 base_model = client.models.update(
43 workspace="default",
44 name=MODEL_NAME,
45 fileset=f"default/{MODEL_NAME}",
46 )
47
48print(f"\nBase model fileset: fileset://default/{base_model.name}")
49print("Base model fileset files list:")
50print(json.dumps([f.model_dump() for f in client.files.list(fileset=MODEL_NAME, workspace="default").data], indent=2))
51
52# Wait for ModelSpec to be populated from the checkpoint
53print("\nWaiting for ModelSpec to be populated...")
54SPEC_TIMEOUT_SECONDS = 120
55spec_start = time.time()
56while not base_model.spec:
57 if time.time() - spec_start > SPEC_TIMEOUT_SECONDS:
58 raise TimeoutError(f"ModelSpec not populated within {SPEC_TIMEOUT_SECONDS} seconds")
59 time.sleep(2)
60 base_model = client.models.retrieve(
61 workspace="default",
62 name=MODEL_NAME,
63 )
64
65print(f"ModelSpec populated: {base_model.spec}")

6. Create SFT Finetuning Job

Create a customization job to fine-tune all model weights using the Automodel backend and AutomodelJobInput.

GPU Requirements:

  • 1B models: 1 GPU (24GB+ VRAM)
  • 3B models: 1-2 GPUs
  • 8B models: 2-4 GPUs
  • 70B models: 8+ GPUs

Adjust num_gpus_per_node based on your model size.

1import uuid
2from nemo_automodel_plugin.schema import AutomodelJobInput
3
4job_suffix = uuid.uuid4().hex[:4]
5
6JOB_NAME = f"my-sft-job-{job_suffix}"
7OUTPUT_NAME = f"sft-model-{job_suffix}"
8
9spec = AutomodelJobInput(
10 model=f"default/{base_model.name}",
11 dataset={"training": f"default/{DATASET_NAME}"},
12 training={
13 "training_type": "sft",
14 "finetuning_type": "all_weights",
15 "max_seq_length": 2048,
16 },
17 schedule={"epochs": 2},
18 batch={"global_batch_size": 64, "micro_batch_size": 1},
19 optimizer={"learning_rate": 5e-5},
20 parallelism={
21 "num_gpus_per_node": 1,
22 "num_nodes": 1,
23 "tensor_parallel_size": 1,
24 "pipeline_parallel_size": 1,
25 },
26 output={"name": OUTPUT_NAME},
27)
28
29job = client.customization.automodel.jobs.create(
30 spec=spec, workspace="default", name=JOB_NAME
31)
32
33print(f"Submitted job: {job.job.name}")
34print(f"Output model: {OUTPUT_NAME}")

7. Track Training Progress

1import time
2from IPython.display import clear_output
3
4# Poll job status every 10 seconds until completed
5while True:
6 status = client.jobs.get_status(
7 name=job.job.name,
8 workspace="default"
9 )
10
11 clear_output(wait=True)
12 print(f"Job Status: {status.model_dump_json(indent=2)}")
13
14 # Extract training progress from nested steps structure
15 step: int | None = None
16 max_steps: int | None = None
17 training_phase: str | None = None
18
19 for job_step in status.steps or []:
20 if job_step.name == "training":
21 for task in job_step.tasks or []:
22 task_details = task.status_details or {}
23 step = task_details.get("step")
24 max_steps = task_details.get("max_steps")
25 training_phase = task_details.get("phase")
26 break
27 break
28
29 if step is not None and max_steps is not None:
30 progress_pct = (step / max_steps) * 100
31 print(f"Training Progress: Step {step}/{max_steps} ({progress_pct:.1f}%)")
32 if training_phase:
33 print(f"Training Phase: {training_phase}")
34 else:
35 print("Training step not started yet or progress info not available")
36
37 # Exit loop when job reaches a terminal status
38 if status.status in ("completed", "failed", "cancelled", "error"):
39 print(f"\nJob finished with status: {status.status}")
40 break
41
42 time.sleep(10)
43
44if status.status != "completed":
45 raise RuntimeError(f"Training job finished with status: {status.status}")

Interpreting SFT Training Metrics:

Monitor the relationship between training and validation loss curves:

ScenarioInterpretationAction
Both decreasing togetherModel is learning wellContinue training
Training decreases, validation flat/increasingOverfittingReduce epochs, add data
Both flat/not decreasingUnderfittingIncrease LR, check data
Sudden spikesTraining instabilityLower learning rate

Note: Training metrics measure optimization progress, not final model quality. Always evaluate the deployed model on your specific use case.

(ft-deploy-full-weight-model)=

8. Deploy Fine-Tuned Model

After training completes, deploy using the Deployment Management Service:

1# Validate model entity exists
2model_entity = client.models.retrieve(workspace='default', name=OUTPUT_NAME)
3print(model_entity.model_dump_json(indent=2))
1# Create deployment config
2deploy_suffix = uuid.uuid4().hex[:4]
3DEPLOYMENT_CONFIG_NAME = f"sft-model-deployment-cfg-{deploy_suffix}"
4DEPLOYMENT_NAME = f"sft-model-deployment-{deploy_suffix}"
5
6deployment_config = client.inference.deployment_configs.create(
7 workspace="default",
8 name=DEPLOYMENT_CONFIG_NAME,
9 engine="vllm",
10 model_spec={
11 "model_namespace": "default",
12 "model_name": OUTPUT_NAME,
13 },
14 executor_config={
15 "gpu": 1,
16 "image_name": "vllm/vllm-openai",
17 "image_tag": "v0.22.1",
18 },
19)
20
21# Deploy model using deployment_config created above
22deployment = client.inference.deployments.create(
23 workspace="default",
24 name=DEPLOYMENT_NAME,
25 config=deployment_config.name
26)
27
28
29# Check deployment status
30deployment_status = client.inference.deployments.retrieve(
31 name=deployment.name,
32 workspace="default"
33)
34
35print(f"Deployment name: {deployment.name}")
36print(f"Deployment status: {deployment_status.status}")

The deployment service automatically:

  • Downloads model weights from the Files service
  • Provisions storage (PVC) for the weights
  • Configures and starts the vLLM container

Multi-GPU Deployment:

For larger models requiring multiple GPUs, increase gpu in executor_config. vLLM computes tensor parallelism from the GPU count and model architecture:

1deployment_config = client.inference.deployment_configs.create(
2 workspace="default",
3 name="sft-model-config-multigpu",
4 engine="vllm",
5 model_spec={
6 "model_namespace": "default",
7 "model_name": OUTPUT_NAME,
8 },
9 executor_config={
10 "gpu": 2,
11 "image_name": "vllm/vllm-openai",
12 "image_tag": "v0.22.1",
13 },
14)

Single-Node Constraint: Model deployments are limited to a single node. The maximum gpu value depends on the total GPUs available on a single node in your cluster. Multi-node deployments are not supported.

Track Deployment Status

1import time
2from IPython.display import clear_output
3
4# Poll deployment status every 15 seconds until ready
5TIMEOUT_MINUTES = 30
6start_time = time.time()
7timeout_seconds = TIMEOUT_MINUTES * 60
8
9print(f"Monitoring deployment '{deployment.name}'...")
10print(f"Timeout: {TIMEOUT_MINUTES} minutes\n")
11
12while True:
13 deployment_status = client.inference.deployments.retrieve(
14 name=deployment.name,
15 workspace="default"
16 )
17
18 elapsed = time.time() - start_time
19 elapsed_min = int(elapsed // 60)
20 elapsed_sec = int(elapsed % 60)
21
22 clear_output(wait=True)
23 print(f"Deployment: {deployment.name}")
24 print(f"Status: {deployment_status.status}")
25 print(f"Elapsed time: {elapsed_min}m {elapsed_sec}s")
26
27 # Check if deployment is ready
28 if deployment_status.status == "READY":
29 print("\nDeployment is ready!")
30 if not client.models.wait_for_gateway(deployment.name, workspace="default", timeout=60):
31 raise RuntimeError("Inference gateway did not become ready")
32 break
33
34 # Check for failure states
35 if deployment_status.status in ("FAILED", "ERROR", "TERMINATED", "LOST"):
36 raise RuntimeError(f"Deployment failed with status: {deployment_status.status}")
37
38 # Check timeout
39 if elapsed > timeout_seconds:
40 raise TimeoutError(f"Deployment timeout after {TIMEOUT_MINUTES} minutes")
41
42 time.sleep(15)

9. Evaluate Your Model

After training, evaluate whether your model meets your requirements:

Quick Manual Evaluation

1# Wait for deployment to be ready, then test
2# Test the fine-tuned model with a question answering prompt
3context = "The Apollo 11 mission was the first manned mission to land on the Moon. It was launched on July 16, 1969, and Neil Armstrong became the first person to walk on the lunar surface on July 20, 1969. Buzz Aldrin joined him shortly after, while Michael Collins remained in lunar orbit."
4question = "Who was the first person to walk on the Moon?"
5
6prompt = f"Context: {context} Question: {question} Answer:"
7
8response = client.inference.gateway.provider.post(
9 "v1/completions",
10 name=deployment.name,
11 workspace="default",
12 body={
13 "model": f"default/{OUTPUT_NAME}",
14 "prompt": prompt,
15 "temperature": 0,
16 "max_tokens": 128
17 }
18)
19
20print("=" * 60)
21print("MODEL EVALUATION")
22print("=" * 60)
23print(f"Question: {question}")
24print(f"Expected: Neil Armstrong")
25print(f"Model output: {response['choices'][0]['text']}")

Evaluation Best Practices

Manual Evaluation (Recommended)

  • Test with real-world examples from your use case
  • Compare responses to base model and expected outputs
  • Verify the model exhibits desired behavior changes
  • Check edge cases and error handling

What to look for:

  • ✅ Model follows your desired output format
  • ✅ Applies domain knowledge correctly
  • ✅ Maintains general language capabilities
  • ✅ Avoids unwanted behaviors or biases
  • ❌ Doesn’t hallucinate facts not in training data
  • ❌ Doesn’t produce repetitive or nonsensical outputs

Hyperparameters

For detailed information on all available hyperparameters, recommended values, and tuning guidance, refer to the Hyperparameter Reference.


Troubleshooting

Job fails during model download:

  • Verify authentication secrets are configured (refer to Managing Secrets)
  • For gated HuggingFace models (Llama, Gemma), accept the license on the model page (for example, meta-llama/Llama-3.2-1B-Instruct)
  • Confirm the model fileset uses token_secret=hf_secret.name for gated models
  • Check AutomodelJobInput references use the workspace/name format: model=f"default/{MODEL_NAME}" and dataset={"training": f"default/{DATASET_NAME}"} (for example, default/llama-3-2-1b-base, default/sft-dataset)
  • Verify the model entity points at the fileset: fileset=f"default/{MODEL_NAME}"
  • Check job status: client.jobs.get_status(name=job.job.name, workspace="default")

Job fails with OOM (Out of Memory) error:

  1. First try: Reduce global_batch_size from 64 to 32 or 16 in batch={...}
  2. Still OOM: Keep micro_batch_size at 1 (already the minimum in this tutorial)
  3. Still OOM: Reduce max_seq_length from 2048 to 1024 or 512 in training={...}
  4. Last resort: Increase num_gpus_per_node and tensor_parallel_size in parallelism={...}

Loss curves not decreasing (underfitting):

  • Increase training duration: raise epochs from 2 to 3-5 in schedule={...}
  • Adjust learning rate: try 1e-4 or 1e-5 instead of the default 5e-5 in optimizer={...}
  • Check data quality: Verify formatting, remove duplicates, ensure diversity

Training loss decreases but validation loss increases (overfitting):

  • Reduce epochs from 2 to 1 in schedule={...}
  • Lower learning_rate from 5e-5 to 2e-5 or 1e-5 in optimizer={...}
  • Increase dataset size and diversity
  • Verify train/validation split has no data leakage

Model output quality is poor despite good training metrics:

  • Training metrics optimize for loss, not your actual task—evaluate on real use cases
  • Review data quality, format, and diversity—metrics can be misleading with poor data
  • Try a different base model size or architecture
  • Adjust learning_rate and global_batch_size
  • Compare to baseline: Test base model to ensure fine-tuning improved performance

Deployment fails:

  • Verify output model exists: client.models.retrieve(name=OUTPUT_NAME, workspace="default")
  • Check deployment logs: client.inference.deployments.get_logs(name=deployment.name, workspace="default")
  • Ensure sufficient GPU resources for executor_config={"gpu": 1, ...}
  • Verify the deployment config matches this tutorial: engine="vllm" with vllm/vllm-openai:v0.22.1

Next Steps