Spaces:
Sleeping
Sleeping
Create model_utils.py
Browse files- model_utils.py +39 -0
model_utils.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# model_utils.py
|
| 2 |
+
|
| 3 |
+
from transformers import (
|
| 4 |
+
AutoTokenizer,
|
| 5 |
+
AutoModel,
|
| 6 |
+
AutoModelForCausalLM,
|
| 7 |
+
)
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
MODEL_OPTIONS = {
|
| 12 |
+
"BERT (bert-base-uncased)": "bert-base-uncased",
|
| 13 |
+
"DistilBERT": "distilbert-base-uncased",
|
| 14 |
+
"RoBERTa": "roberta-base",
|
| 15 |
+
"GPT-2": "gpt2",
|
| 16 |
+
"Electra": "google/electra-small-discriminator",
|
| 17 |
+
"ALBERT": "albert-base-v2",
|
| 18 |
+
"XLNet": "xlnet-base-cased",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_model(model_name):
|
| 23 |
+
if "gpt2" in model_name or "causal" in model_name:
|
| 24 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, output_attentions=True)
|
| 25 |
+
else:
|
| 26 |
+
model = AutoModel.from_pretrained(model_name, output_attentions=True)
|
| 27 |
+
|
| 28 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 29 |
+
return tokenizer, model
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_model_info(model):
|
| 33 |
+
config = model.config
|
| 34 |
+
return {
|
| 35 |
+
"Model Type": config.model_type,
|
| 36 |
+
"Number of Layers": getattr(config, "num_hidden_layers", "N/A"),
|
| 37 |
+
"Number of Attention Heads": getattr(config, "num_attention_heads", "N/A"),
|
| 38 |
+
"Total Parameters": sum(p.numel() for p in model.parameters()),
|
| 39 |
+
}
|