Downloads ยท 30 days
114
100% of all-time downloads
EnergyAI/Llama-3.1-8B-Energy-Classifier
Llama-3.1-8B-Energy-Classifier is a text classification model from EnergyAI. Use it when you need a label for a piece of text. It is set up for transformers. The card lists the license as llama3.1.
A fine-tuned Llama-3.1-8B model for binary classification of energy-related documents, achieving 98.39% accuracy on test data.
Downloads ยท 30 days
114
100% of all-time downloads
All-time downloads
114
Public
Repo size
362 MB
Likes
0
Public
Click a slice to open those files.
.safetensors168 MB ยท 95%
From the Hugging Face model README
A fine-tuned Llama-3.1-8B model for binary classification of energy-related documents, achieving 98.39% accuracy on test data.
This model uses LoRA (Low-Rank Adaptation) for parameter-efficient fine-tuning, trained on 95,602 documents (perfectly balanced: 47,801 energy + 47,801 non-energy).
| Metric | Score |
|---|---|
| Test Accuracy | 98.39% |
| F1 Score | 98.41% |
| Precision | 97.17% |
| Recall | 99.69% |
| ROC-AUC | 99.76% |
| Metric | Score |
|---|---|
| Val Accuracy | 98.55% |
| Val F1 Score | 98.56% |
| Val Precision | 97.54% |
| Val Recall | 99.60% |
| Val ROC-AUC | 99.76% |
| Predicted Non-Energy | Predicted Energy | |
|---|---|---|
| Actual Non-Energy | 4,642 (97.09%) | 139 (2.91%) |
| Actual Energy | 15 (0.31%) | 4,766 (99.69%) |
Only 154 misclassifications out of 9,562 documents (1.61% error rate)!
Energy-labeled documents were sourced from four HuggingFace datasets (see above). Classification labels for the training data were created with Mistral 3 Large model and this classifier was distilled from this data. Non-energy documents were sampled from a base document pipeline, with deduplication to ensure no overlap with energy documents (validated by both document ID and MD5 hash matching).
This model can classify documents as energy-related or non-energy. Perfect for:
Energy Topics Covered:
pip install torch>=2.0.0 transformers>=4.44.0 peft>=0.12.0 accelerate>=0.28.0
โ ๏ธ Version Requirements:
| Package | Recommended Version | Notes |
|---|---|---|
torch | โฅ2.0.0 | CUDA support recommended |
transformers | 4.44.0 - 4.57.x | Tested range |
peft | 0.12.0 - 0.18.x | LoRA adapter loading |
accelerate | โฅ0.28.0 | For device_map="auto" |
Note: The tokenizer is loaded from the base model (meta-llama/Llama-3.1-8B). You need access to Llama-3.1 on Hugging Face (requires accepting the license agreement).
from peft import AutoPeftModelForSequenceClassification
from transformers import AutoTokenizer
import torch
# Load model and tokenizer
model_name = "omar-elmansouri/Llama-3.1-8B-Energy-Classifier"
# Load tokenizer from base model (recommended for compatibility)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B")
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# Load the PEFT adapter model
model = AutoPeftModelForSequenceClassification.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.bfloat16,
)
model.config.pad_token_id = tokenizer.pad_token_id
model.eval()
# Classify a document
text = """
Solar energy capacity has grown exponentially over the past decade.
The International Energy Agency reports that solar now represents
the fastest-growing renewable energy source globally.
"""
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
predicted_class = torch.argmax(predictions, dim=-1).item()
label_map = {0: "non_energy", 1: "energy"}
print(f"Prediction: {label_map[predicted_class]}")
print(f"Confidence: {predictions[0][predicted_class].item():.4f}")
print(f"Probabilities: Energy={predictions[0][1].item():.4f}, Non-Energy={predictions[0][0].item():.4f}")
Output:
Prediction: energy
Confidence: 0.9987
Probabilities: Energy=0.9987, Non-Energy=0.0013
from transformers import pipeline
# Create classification pipeline
classifier = pipeline(
"text-classification",
model="EnergyAI/Llama-3.1-8B-Energy-Classifier",
device_map="auto",
torch_dtype=torch.bfloat16,
)
# Classify multiple documents
texts = [
"Wind turbines are becoming more efficient with larger blade designs.",
"The software development team completed the sprint planning meeting.",
"Natural gas prices fluctuated amid geopolitical tensions in Europe.",
]
results = classifier(texts, truncation=True, max_length=512)
for text, result in zip(texts, results):
print(f"Text: {text[:50]}...")
print(f"Label: {result['label']}, Score: {result['score']:.4f}\n")
from peft import AutoPeftModelForSequenceClassification
from transformers import AutoTokenizer
import torch
# Load with PEFT (more memory efficient)
model = AutoPeftModelForSequenceClassification.from_pretrained(
"EnergyAI/Llama-3.1-8B-Energy-Classifier",
device_map="auto",
torch_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained("EnergyAI/Llama-3.1-8B-Energy-Classifier")
# Classify
text = "Offshore wind farms are expanding along the Atlantic coast."
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
print(f"Energy probability: {probs[0][1].item():.4f}")
q_proj, k_proj, v_proj, o_proj (Attention)gate_proj, up_proj, down_proj (MLP)| Step | Train Loss | Val Loss | Val Accuracy | Val F1 |
|---|---|---|---|---|
| 100 | 4.31 | 1.00 | 65.2% | 66.8% |
| 300 | 1.78 | 0.83 | 80.0% | 80.4% |
| 500 | 0.73 | 0.70 | 89.6% | 89.7% |
| 700 | 0.42 | 0.65 | 93.9% | 94.0% |
| 900 | 0.27 | 0.64 | 96.1% | 96.1% |
| 1100 | 0.21 | 0.63 | 98.2% | 98.2% |
Label 0 (non_energy): Documents that are NOT primarily about energy topics
Label 1 (energy): Documents primarily discussing energy-related topics
This repository contains:
adapter_config.json - LoRA adapter configurationadapter_model.safetensors - Trained LoRA weights (161 MB)tokenizer.json - Tokenizer vocabularytokenizer_config.json - Tokenizer configurationspecial_tokens_map.json - Special tokens mappingNote: The base Llama-3.1-8B model will be downloaded automatically from HuggingFace.
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from typing import List, Dict
class EnergyClassifier:
def __init__(self, model_name: str = "EnergyAI/Llama-3.1-8B-Energy-Classifier"):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForSequenceClassification.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.bfloat16,
)
self.model.eval()
self.label_map = {0: "non_energy", 1: "energy"}
@torch.no_grad()
def predict(self, text: str, return_probs: bool = True) -> Dict:
inputs = self.tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=1024,
padding=True,
)
inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
outputs = self.model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
predicted_class = torch.argmax(probs, dim=-1).item()
result = {
"label": self.label_map[predicted_class],
"confidence": probs[0][predicted_class].item(),
}
if return_probs:
result["probabilities"] = {
"non_energy": probs[0][0].item(),
"energy": probs[0][1].item(),
}
return result
@torch.no_grad()
def predict_batch(self, texts: List[str], batch_size: int = 8) -> List[Dict]:
results = []
for i in range(0, len(texts), batch_size):
batch = texts[i:i + batch_size]
inputs = self.tokenizer(
batch,
return_tensors="pt",
truncation=True,
max_length=1024,
padding=True,
)
inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
outputs = self.model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
for j in range(len(batch)):
pred_class = torch.argmax(probs[j]).item()
results.append({
"label": self.label_map[pred_class],
"confidence": probs[j][pred_class].item(),
"probabilities": {
"non_energy": probs[j][0].item(),
"energy": probs[j][1].item(),
}
})
return results
# Usage
classifier = EnergyClassifier()
result = classifier.predict("Wind energy is the fastest growing renewable source.")
print(result)
import json
from tqdm import tqdm
def classify_jsonl_file(input_file: str, output_file: str):
classifier = EnergyClassifier()
# Read all texts
texts = []
with open(input_file, 'r') as f:
for line in f:
data = json.loads(line)
texts.append(data['text'])
# Classify in batches
results = classifier.predict_batch(texts, batch_size=16)
# Write results
with open(input_file, 'r') as fin, open(output_file, 'w') as fout:
for line, result in tqdm(zip(fin, results), total=len(texts)):
data = json.loads(line)
data['predicted_label'] = result['label']
data['confidence'] = result['confidence']
data['energy_prob'] = result['probabilities']['energy']
fout.write(json.dumps(data) + '\n')
# Process your dataset
classify_jsonl_file('documents.jsonl', 'documents_classified.jsonl')
The training code is available at: GitHub Repository
To reproduce the training:
# Clone repository
git clone https://github.com/EnergyAI/energy-classifier.git
cd energy-classifier
# Install dependencies
pip install -r requirements.txt
# Prepare your data (train.jsonl, val.jsonl, test.jsonl)
# Format: {"text": "document text", "label": 0 or 1}
# Train
python train.py --config configs/training_config.yaml
torch>=2.0.0
transformers>=4.40.0
peft>=0.10.0
accelerate>=0.28.0
safetensors>=0.4.0
# Use fp16 instead of bfloat16 if your GPU supports it
model = AutoModelForSequenceClassification.from_pretrained(
"EnergyAI/Llama-3.1-8B-Energy-Classifier",
device_map="auto",
torch_dtype=torch.float16, # Faster on some GPUs
)
# Enable torch.compile (PyTorch 2.0+)
model = torch.compile(model, mode="reduce-overhead")
# Use 8-bit quantization
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
model = AutoModelForSequenceClassification.from_pretrained(
"EnergyAI/Llama-3.1-8B-Energy-Classifier",
quantization_config=quantization_config,
device_map="auto",
)
| Batch Size | Throughput (docs/sec) | Latency (ms/doc) |
|---|---|---|
| 1 | 12.3 | 81.3 |
| 8 | 78.4 | 10.2 |
| 16 | 134.7 | 5.9 |
| 32 | 198.5 | 3.2 |
If you use this model in your research, please cite:
@misc{llama31-energy-classifier,
author = {EnergyAI Team},
title = {Llama-3.1-8B Energy Document Classifier},
year = {2025},
publisher = {HuggingFace},
howpublished = {\url{https://huggingface.co/EnergyAI/Llama-3.1-8B-Energy-Classifier}},
}
This model is released under the Llama 3.1 Community License Agreement. See the license for details.
Base Model: meta-llama/Llama-3.1-8B
For questions or issues:
Happy Classifying! ๐โก