File size: 7,577 Bytes
91490fc 727cb3d 91490fc 727cb3d 91490fc 727cb3d 91490fc 727cb3d 91490fc 727cb3d 91490fc 727cb3d bdad09b 727cb3d bdad09b 727cb3d bdad09b 727cb3d bdad09b 727cb3d bdad09b 91490fc bdad09b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
---
license: gemma
base_model: google/functiongemma-270m-it
tags:
- text-classification
- domain-classification
- function-calling
- peft
- lora
- gemma
- functiongemma
datasets:
- custom
language:
- en
metrics:
- accuracy
- f1
library_name: transformers
pipeline_tag: text-classification
---
# FunctionGemma Domain Classifier
Fine-tuned **FunctionGemma-270M** for multi-domain query classification using LoRA.
## Model Details
- **Base Model:** [google/functiongemma-270m-it](https://huggingface.co/google/functiongemma-270m-it)
- **Model Size:** 270M parameters (540MB)
- **Fine-tuning Method:** LoRA (Low-Rank Adaptation)
- **Trainable Parameters:** ~7.6M (2.75%)
- **Training Time:** 23.3 minutes
- **Hardware:** GPU (memory optimized for <5GB VRAM)
## Performance
```
Accuracy: 95.51%
F1 Score (Weighted): 0.96
F1 Score (Macro): 0.88
Training Loss: 0.3
```
## Supported Domains (17)
1. ambiguous
2. api_generation
3. business
4. coding
5. creative_content
6. data_analysis
7. education
8. general_knowledge
9. geography
10. history
11. law
12. literature
13. mathematics
14. medicine
15. science
16. sensitive
17. technology
## Use Cases
- **Query Routing:** Route user queries to specialized models/services
- **Content Classification:** Categorize text by domain
- **Multi-domain Detection:** Identify queries spanning multiple domains
- **Intent Analysis:** Understand query context and domain
## Quick Start
### Installation
```bash
pip install transformers peft torch
```
### Inference
```python
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import torch
import json
# Load model
base_model = AutoModelForCausalLM.from_pretrained(
"google/functiongemma-270m-it",
torch_dtype=torch.bfloat16,
device_map="auto"
)
model = PeftModel.from_pretrained(base_model, "ovinduG/functiongemma-domain-classifier")
tokenizer = AutoTokenizer.from_pretrained("ovinduG/functiongemma-domain-classifier")
# Classify a query
def classify(text):
# Define function schema
function_def = {
"type": "function",
"function": {
"name": "classify_query_domain",
"description": "Classify query into domains",
"parameters": {
"type": "object",
"properties": {
"primary_domain": {"type": "string"},
"primary_confidence": {"type": "number"},
"is_multi_domain": {"type": "boolean"},
"secondary_domains": {"type": "array"}
}
}
}
}
messages = [
{"role": "developer", "content": "You are a model that can do function calling"},
{"role": "user", "content": text}
]
inputs = tokenizer.apply_chat_template(
messages,
tools=[function_def],
add_generation_prompt=True,
return_dict=True,
return_tensors="pt"
).to(model.device)
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=150,
do_sample=False,
pad_token_id=tokenizer.eos_token_id
)
response = tokenizer.decode(
outputs[0][inputs["input_ids"].shape[-1]:],
skip_special_tokens=True
)
# Parse function call
if "{" in response:
start = response.find("{")")
end = response.rfind("}") + 1
return json.loads(response[start:end])
return {"error": "Failed to parse response"}
# Example
result = classify("Write a Python function to calculate fibonacci numbers")
print(json.dumps(result, indent=2))
```
### Example Output
```json
{
"primary_domain": "coding",
"primary_confidence": 0.95,
"is_multi_domain": false,
"secondary_domains": []
}
```
### Multi-Domain Example
```python
result = classify("Build an ML model to predict customer churn and create REST API endpoints")
print(json.dumps(result, indent=2))
```
```json
{
"primary_domain": "data_analysis",
"primary_confidence": 0.85,
"is_multi_domain": true,
"secondary_domains": [
{
"domain": "api_generation",
"confidence": 0.75
}
]
}
```
## Training Details
### Dataset
- **Total Samples:** 5,046
- **Training Samples:** 3,666
- **Validation Samples:** 690
- **Test Samples:** 690
- **Multi-domain Queries:** 546 (10.8%)
### Training Configuration
```python
# LoRA Configuration
r = 32
lora_alpha = 64
lora_dropout = 0.05
target_modules = ['q_proj', 'v_proj', 'k_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj']
# Training Configuration
num_epochs = 5
batch_size = 4
gradient_accumulation_steps = 8
learning_rate = 0.0003
max_length = 1024
optimizer = "adamw_8bit" # Memory optimized
```
### Memory Optimization
This model was trained with memory optimizations to run on GPUs with <5GB VRAM:
- **8-bit Optimizer:** Reduces optimizer memory by 50%
- **Gradient Checkpointing:** Trades compute for memory
- **Smaller Batches:** 4 samples per batch with gradient accumulation
- **Shorter Sequences:** 1024 tokens max (vs 2048)
**Total VRAM Usage:** ~4GB (vs ~40GB without optimization)
## Performance by Domain
| Domain | Precision | Recall | F1-Score | Support |
|--------|-----------|--------|----------|---------|
| ambiguous | 0.98 | 1.00 | 0.99 | 45 |
| api_generation | 0.98 | 1.00 | 0.99 | 45 |
| business | 0.98 | 0.93 | 0.95 | 44 |
| coding | 0.98 | 0.96 | 0.97 | 48 |
| creative_content | 0.90 | 1.00 | 0.95 | 45 |
| data_analysis | 0.96 | 0.98 | 0.97 | 46 |
| education | 0.98 | 0.96 | 0.97 | 45 |
| general_knowledge | 0.76 | 0.84 | 0.80 | 45 |
| law | 0.98 | 0.94 | 0.96 | 49 |
| literature | 1.00 | 0.93 | 0.97 | 45 |
| mathematics | 1.00 | 1.00 | 1.00 | 47 |
| medicine | 0.98 | 0.89 | 0.93 | 46 |
| science | 1.00 | 0.98 | 0.99 | 47 |
| sensitive | 0.92 | 1.00 | 0.96 | 45 |
| technology | 1.00 | 0.93 | 0.97 | 46 |
**Overall Accuracy:** 95.51%
## Advantages
- ✅ **Tiny Size:** 270M parameters (14x smaller than Phi-3)
- ✅ **Fast Inference:** 0.3s on CPU, 0.08s on GPU
- ✅ **Low Memory:** Runs on 4GB VRAM
- ✅ **High Accuracy:** 95.51% (competitive with larger models)
- ✅ **Multi-domain:** Detects queries spanning multiple domains
- ✅ **Function Calling:** Built-in structured output
- ✅ **Mobile-Ready:** Can deploy on smartphones
## Limitations
- Trained on English queries only
- Performance varies by domain (see table above)
- May struggle with highly ambiguous queries
- Limited to 17 pre-defined domains
## Base Model
- **Base model:** `google/functiongemma`
- **Model family:** Gemma
- **Model owner:** Google LLC
- **Fine-tuning task:** Domain classification
## Acknowledgement & Attribution
This model is built upon Google’s FunctionGemma. Use of this model is subject to the **Gemma Terms of Use** and the **Gemma Prohibited Use Policy**:
- **Gemma Terms of Use (March 24, 2025):**
[https://ai.google.dev/gemma/terms](https://ai.google.dev/gemma/terms)
- **Gemma Prohibited Use Policy (February 21, 2024):**
[https://ai.google.dev/gemma/prohibited_use_policy](https://ai.google.dev/gemma/prohibited_use_policy)
Users must comply with these policies when using, modifying, or distributing this model or its derivatives.
## License
This model follows the same terms as **Google’s Gemma models**. Please review the above links for full license and usage restrictions.
## Recommended Hugging Face Metadata
```yaml
license: gemma
base_model: google/functiongemma
tags:
- text-classification
- domain-classification
- gemma
- functiongemma
|