Skip to content

Commit 1790609

Browse files
committed
newLP
1 parent 730cbf4 commit 1790609

11 files changed

Lines changed: 1102 additions & 0 deletions

File tree

22.6 KB
Loading
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
title: Fine-tuning Large Language Models (LLMs) on Arm Powered Mobile Devices with ExecuTorch
3+
minutes_to_complete: 60
4+
5+
who_is_this_for: This learning path provides an introduction for developers and data scientists new to fine-tuning large language models (LLMs) and looking to develop a fine-tuned LLM for mobile applications. Fine-tuning involves adapting a pre-trained LLM to specific tasks or domains by training it on domain-specific data and optimizing its responses for accuracy and relevance. For mobile applications, fine-tuning enables personalized interactions, enhanced query handling, and improved contextual understanding, making AI-driven features more effective. This session will cover key concepts, techniques, tools, and best practices, ensuring a structured approach to building a fine-tuned LLM that aligns with real-world mobile application requirements.Mobile application with Llama, KleidiAI, ExecuTorch, and XNNPACK.
6+
7+
learning_objectives:
8+
- Learn the basics of large language models (LLMs) and how fine-tuning enhances model performance for specific use cases focusing on mobile applications.
9+
- Understand full fine-tuning, parameter-efficient fine-tuning (e.g., LoRA, QLoRA, PEFT), instruction-tuning and fine-tuning benchmarking.
10+
- Learn when to use different fine-tuning approaches based on model size, task complexity, and computational constraints.
11+
- Learn how to curate, clean, and preprocess domain-specific datasets for optimal fine-tuning.
12+
- Understand dataset formats, tokenization, and annotation techniques for improving model learning.
13+
- Implementing Fine-Tuning with Popular Frameworks like Hugging Face Transformers and PyTorch for LLM fine-tuning.
14+
- Learn how to deploy and fine-tune the model in the mobile device.
15+
- Compile a Large Language Model (LLM) using ExecuTorch.
16+
- Describe techniques for running large language models in an mobile environment.
17+
18+
prerequisites:
19+
- Basic Understanding of Machine Learning & Deep Learning (Familiarity with concepts like supervised learning, neural networks, transfer learning and Understanding of model training, validation, & overfitting concepts).
20+
- Familiarity with Deep Learning Frameworks (Experience with PyTorch for building, training neural networks and Knowledge of Hugging Face Transformers for working with pre-trained LLMs.
21+
- An Arm-powered smartphone with the i8mm feature running Android, with 16GB of RAM.
22+
- A USB cable to connect your smartphone to your development machine.
23+
- An AWS Graviton4 r8g.16xlarge instance to test Arm performance optimizations, or any [Arm based instance](/learning-paths/servers-and-cloud-computing/csp/) from a cloud service provider or an on-premise Arm server or Arm based laptop.
24+
- Python 3.10.
25+
26+
author: Parichay Das
27+
28+
### Tags
29+
skilllevels: Introductory
30+
subjects: GenAI
31+
armips:
32+
- Neoverse
33+
34+
tools_software_languages:
35+
- LLM
36+
- GenAI
37+
- Python
38+
- PyTorch
39+
- ExecuTorch
40+
operatingsystems:
41+
- Linux
42+
- Windows
43+
- Android
44+
45+
46+
further_reading:
47+
- resource:
48+
title: Hugging Face Documentation
49+
link: https://huggingface.co/docs
50+
type: documentation
51+
- resource:
52+
title: PyTorch Documentation
53+
link: https://pytorch.org/docs/stable/index.html
54+
type: documentation
55+
- resource:
56+
title: Android
57+
link: https://www.android.com/
58+
type: website
59+
60+
61+
### FIXED, DO NOT MODIFY
62+
# ================================================================================
63+
weight: 1 # _index.md always has weight of 1 to order correctly
64+
layout: "learningpathall" # All files under learning paths have this same wrapper
65+
learning_path_main_page: "yes" # This should be surfaced when looking for related content. Only set for _index.md of learning path content.
66+
---
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
# ================================================================================
3+
# FIXED, DO NOT MODIFY THIS FILE
4+
# ================================================================================
5+
weight: 21 # Set to always be larger than the content in this path to be at the end of the navigation.
6+
title: "Next Steps" # Always the same, html page title.
7+
layout: "learningpathall" # All files under learning paths have this same wrapper for Hugo processing.
8+
---
Loading
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
title: Overview
3+
weight: 2
4+
5+
### FIXED, DO NOT MODIFY
6+
layout: learningpathall
7+
---
8+
9+
## What is Fine-Tuning
10+
Fine-tuning in the context of large language models (LLMs) refers to the process of further training a pre-trained LLM on domain-specific or task-specific data to enhance its performance for a particular application. LLMs, such as GPT, BERT, and LLaMA, are initially trained on massive corpora containing billions of tokens, enabling them to develop a broad linguistic understanding. Fine-tuning refines this knowledge by exposing the model to specialized datasets, allowing it to generate more contextually relevant and accurate responses. Rather than training an LLM from scratch, fine-tuning leverages the pre-existing knowledge embedded in the model, optimizing it for specific use cases such as customer support, content generation, legal document analysis, or medical text processing. This approach significantly reduces computational requirements and data needs while improving adaptability and efficiency in real-world applications.
11+
12+
## Advantage of Fine-Tuning
13+
Fine-tuning is essential for optimizing large language models (LLMs) to meet specific application requirements, enhance performance, and reduce computational costs. While pre-trained LLMs have broad linguistic capabilities, they may not always produce domain-specific, contextually accurate, or application-tailored responses
14+
- Customization for Specific Domains
15+
- Improved Response Quality and Accuracy
16+
- Task-Specific Adaptation
17+
- Reduction in Computational and Data Requirements
18+
- Enhanced Efficiency in Real-World Applications
19+
- Alignment with Ethical, Regulatory, and Organizational Guidelines
20+
21+
## Fine-Tuning Methods
22+
Fine-tuning LLM uses different techniques based on the various use cases, computational constraints, and efficiency requirements. Below are the key fine-tuning methods:
23+
24+
### Full Fine-Tuning (Supervised Learning Approach)
25+
It involves updating all parameters of the LLM using task-specific data, requiring significant computational power and large labeled datasets, which provides the highest level of customization.
26+
27+
### Instruction Fine-Tuning
28+
Instruction fine-tuning is a supervised learning method. A pre-trained large language model (LLM) is further trained on instruction-response pairs to improve its ability to follow human instructions accurately. Instruction Fine-Tuning has some key features using Labeled Instruction-Response Pairs, Enhances Model Alignment with Human Intent, Commonly Used in Chatbots and AI Assistants, and Prepares Models for Zero-Shot and Few-Shot Learning.
29+
30+
### Parameter-Efficient Fine-Tuning (PEFT)
31+
It is a optimized approaches that reduce the number of trainable parameters while maintaining high performance:
32+
33+
- ###### LoRA (Low-Rank Adaptation)
34+
- Introduces small trainable weight matrices (rank decomposition) while freezing the main model weights.
35+
- It will significantly reduce GPU memory usage and training time.
36+
37+
- ###### QLoRA (Quantized LoRA)
38+
- It will use quantization (e.g., 4-bit or 8-bit precision) to reduce memory footprint while applying LoRA fine-tuning.
39+
- It is Ideal for fine-tuning large models on limited hardware.
40+
41+
- ###### Adapter Layers
42+
- Inserts small trainable layers between existing layers of the model and Keeps most parameters frozen, reducing computational overhead.
43+
44+
- ###### Reinforcement Learning from Human Feedback (RLHF)
45+
- Fine-tunes models based on human preferences using reinforcement learning.
46+
47+
- ###### Domain-Specific Fine-Tuning
48+
- Fine-tunes the LLM with domain-specific datasets and Improves accuracy and relevance in specialized applications.
49+
50+
- ###### Multi-Task Learning (MTL) Fine-Tuning
51+
- Trains the model on multiple tasks simultaneously, enabling generalization across different applications.
52+
53+
54+
55+
## Fine-Tuning Implementaion
56+
The following steps need to be performed to implement fine-tuning:
57+
58+
59+
![example image alt-text#center](1.png "Figure 1. Fine-Tuning Implementaion")
60+
61+
- Base Model Selection: Choose a pre-trained model based on your use cases. You can find pre-trained models at [Hugging Face](https://huggingface.co/).
62+
- Fine-Tuning Method Finalization: Select the most appropriate fine-tuning method (e.g., supervised, instruction-based, PEFT) based on your use case and dataset. You can typically find various datasets on [Hugging Face](https://huggingface.co/datasets) and [Kaggle](https://www.kaggle.com/datasets).
63+
- Dataset Prepration:Organize your data for your use case-specific training, ensuring it aligns with the model's required format.
64+
- Training:Utilize frameworks such as TensorFlow and PyTorch to fine-tune the model.
65+
- Evaluate: Evaluate the model, refine it as needed, and retrain to enhance performance.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
---
2+
title: Large Language Model - Setup Environment
3+
weight: 3
4+
5+
### FIXED, DO NOT MODIFY
6+
layout: learningpathall
7+
---
8+
9+
## Large Language Model - Setup Environment
10+
11+
#### Plartform Required
12+
- An AWS Graviton4 r8g.16xlarge instance to test Arm performance optimizations, or any [Arm based instance](/learning-paths/servers-and-cloud-computing/csp/) from a cloud service provider or an on-premise Arm server or Arm based laptop.
13+
- An Arm-powered smartphone with the i8mm feature running Android, with 16GB of RAM.
14+
- A USB cable to connect your smartphone to your development machine.
15+
16+
#### Set Up Required Libraries
17+
The following commands install the necessary libraries for the task, including Hugging Face Transformers, Datasets, and fine-tuning methods. These libraries facilitate model loading, training, and fine-tuning
18+
19+
###### The transformers library (by Hugging Face) provides pre-trained LLMs
20+
```python
21+
!pip install transformers
22+
23+
```
24+
###### This installs transformers along with PyTorch, ensuring that models are trained and fine-tuned using the Torch backend.
25+
```python
26+
!pip install transformers[torch]
27+
```
28+
###### The datasets library (by Hugging Face) provides access to a vast collection of pre-built datasets
29+
30+
```python
31+
!pip install datasets
32+
```
33+
###### The evaluate library provides metrics for model performance assessment
34+
35+
```python
36+
!pip install evaluate
37+
```
38+
###### Speed up fine-tuning of Large Language Models (LLMs)
39+
Use a library designed to speed up fine-tuning of Large Language Models (LLMs) while reducing computational costs, optimizes training efficiency, particularly for LoRA (Low-Rank Adaptation) fine-tuning
40+
41+
42+
```
43+
Used pre-fine-tuned customer support model
44+
```
45+
46+
###### AWS Graviton3 Instance Setup
47+
Launch EC2 Instance:
48+
49+
50+
```
51+
Recommended instance: c7g.xlarge or c7g.2xlarge
52+
- c7g.xlarge: 4 vCPUs, 8 GB RAM
53+
- c7g.2xlarge: 8 vCPUs, 16 GB RAM
54+
55+
Connect to your instance
56+
ssh -i your-key.pem ubuntu@your-instance-ip
57+
```
58+
59+
###### System Setup:
60+
Launch EC2 Instance:
61+
62+
63+
```
64+
Update system
65+
sudo apt update && sudo apt upgrade -y
66+
67+
Install essential packages
68+
sudo apt install -y build-essential git wget curl \
69+
python3-pip python3-venv htop
70+
71+
Verify ARM architecture
72+
uname -m # Should show: aarch64
73+
```
74+
75+
###### Python Environment Setup
76+
77+
78+
79+
```
80+
Create virtual environment
81+
python3 -m venv chatbot_env
82+
source chatbot_env/bin/activate
83+
84+
Upgrade pip
85+
pip install --upgrade pip
86+
87+
Install PyTorch for ARM/CPU
88+
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
89+
90+
Install Transformers and utilities
91+
pip install transformers==4.36.0
92+
pip install datasets accelerate
93+
pip install huggingface-hub
94+
pip install flask psutil
95+
pip install numpy pandas
96+
97+
Verify installation
98+
python -c "import torch; print(f'PyTorch version: {torch.__version__}')"
99+
python -c "import torch; print(f'CPU available: {torch.cpu.device_count()}')"
100+
```
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
title: Model Loading & Optimization for ARM
3+
weight: 4
4+
5+
### FIXED, DO NOT MODIFY
6+
layout: learningpathall
7+
---
8+
9+
## Model Loading & Optimization for ARM
10+
11+
###### Hugging Face Authentication
12+
```bash
13+
Login to Hugging Face (needed for Llama models)
14+
pip install huggingface_hub
15+
huggingface-cli login
16+
17+
Enter your token when prompted
18+
Get token from: https://huggingface.co/settings/tokens
19+
20+
```
21+
22+
###### Load a pre-fine-tuned model (from Hugging Face)
23+
- Example: meta-llama/Llama-3-8B-Instruct or a customer-support fine-tuned variant
24+
25+
###### Model Optimization for ARM (Understanding Quantization)
26+
- Reduces model precision (e.g., 32-bit → 8-bit)
27+
- Decreases memory footprint (~4x reduction)
28+
- Speeds up inference on CPU
29+
- Minimal accuracy loss for most tasks
30+
31+
###### Apply Dynamic Quantization
32+
- Create optimize_model.py
33+
34+
```python
35+
import torch
36+
from transformers import AutoModelForCausalLM, AutoTokenizer
37+
from torch.quantization import quantize_dynamic
38+
import time
39+
import os
40+
41+
def load_base_model(model_name):
42+
"""Load the base model"""
43+
print(f"Loading base model: {model_name}")
44+
45+
tokenizer = AutoTokenizer.from_pretrained(model_name)
46+
tokenizer.pad_token = tokenizer.eos_token
47+
48+
model = AutoModelForCausalLM.from_pretrained(
49+
model_name,
50+
torch_dtype=torch.float32,
51+
device_map=None,
52+
low_cpu_mem_usage=True
53+
)
54+
model.eval()
55+
56+
return model, tokenizer
57+
58+
def apply_quantization(model):
59+
"""Apply dynamic quantization"""
60+
print("Applying dynamic quantization...")
61+
62+
quantized_model = quantize_dynamic(
63+
model,
64+
{torch.nn.Linear}, # Quantize linear layers
65+
dtype=torch.qint8
66+
)
67+
68+
return quantized_model
69+
70+
def test_model(model, tokenizer, prompt):
71+
"""Test model with a sample prompt"""
72+
inputs = tokenizer(prompt, return_tensors="pt")
73+
74+
start_time = time.time()
75+
with torch.no_grad():
76+
outputs = model.generate(
77+
inputs.input_ids,
78+
max_new_tokens=100,
79+
do_sample=False,
80+
pad_token_id=tokenizer.eos_token_id
81+
)
82+
inference_time = time.time() - start_time
83+
84+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
85+
86+
return response, inference_time
87+
88+
def main():
89+
model_name = "meta-llama/Meta-Llama-3-8B-Instruct"
90+
91+
# Load base model
92+
base_model, tokenizer = load_base_model(model_name)
93+
94+
# Test base model
95+
test_prompt = "How do I track my order?"
96+
print("\nTesting base model...")
97+
response, base_time = test_model(base_model, tokenizer, test_prompt)
98+
print(f"Base model inference time: {base_time:.2f}s")
99+
100+
# Apply quantization
101+
quantized_model = apply_quantization(base_model)
102+
103+
# Test quantized model
104+
print("\nTesting quantized model...")
105+
response, quant_time = test_model(quantized_model, tokenizer, test_prompt)
106+
print(f"Quantized model inference time: {quant_time:.2f}s")
107+
print(f"Speedup: {base_time / quant_time:.2f}x")
108+
109+
# Save quantized model
110+
save_dir = "./models/quantized_llama3"
111+
os.makedirs(save_dir, exist_ok=True)
112+
113+
torch.save(quantized_model.state_dict(), f"{save_dir}/model.pt")
114+
tokenizer.save_pretrained(save_dir)
115+
116+
print(f"\nQuantized model saved to: {save_dir}")
117+
118+
if __name__ == "__main__":
119+
main()
120+
121+
```

0 commit comments

Comments
 (0)