AYYasaswini commited on
Commit
ffe1511
·
verified ·
1 Parent(s): 40327c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -32
app.py CHANGED
@@ -1,32 +1,64 @@
1
- import gradio as gr
2
- import torch
3
- from gpt_dev import BigramLanguageModel # Import your model class
4
-
5
- # Load model
6
- model = BigramLanguageModel()
7
- model.load_state_dict(torch.load('transformer_weights.pth'))
8
- model.eval()
9
-
10
- def predict(input_text):
11
- # Your preprocessing and prediction code
12
- # output = model(input_text)
13
- tokens = tokenize(input_text) # Define this function based on your tokenizer
14
- input_tensor = torch.tensor(tokens).unsqueeze(0) # Add batch dimension
15
-
16
- with torch.no_grad():
17
- output = model(input_tensor)
18
-
19
- # Postprocess output
20
- predicted_tokens = torch.argmax(output, dim=-1).squeeze().tolist()
21
- predicted_text = detokenize(predicted_tokens) # Define this function based on your tokenizer
22
-
23
- return predicted_text # Replace with actual prediction logic
24
- def tokenize(text):
25
- # Example tokenizer function
26
- return [ord(char) for char in text] # Replace with actual tokenizer
27
-
28
- def detokenize(tokens):
29
- # Example detokenizer function
30
- return ''.join([chr(token) for token in tokens]) # Replace with actual detokenizer
31
- interface = gr.Interface(fn=predict, inputs="text", outputs="text")
32
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
2
+ from transformers import PreTrainedModel, AutoConfig
3
+ from pathlib import Path
4
+
5
+
6
+ def predict_with_custom_weights(model_name, text, weights_path):
7
+ """
8
+ Loads a model config, creates a model, loads custom weights, performs testing
9
+ and prediction.
10
+
11
+ Args:
12
+ model_name: Name of the pre-trained model architecture (e.g., "bert-base-uncased").
13
+ text: The text string for prediction.
14
+ weights_path: Path to the directory containing your custom weights.
15
+
16
+ Returns:
17
+ A dictionary containing predictions and logits (optional).
18
+ """
19
+ # Load tokenizer and model config
20
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
21
+ config = AutoConfig.from_pretrained(model_name)
22
+
23
+ # Create empty model from config
24
+ model = PreTrainedModel.from_config(config)
25
+
26
+ # Load weights from your directory
27
+ model.load_state_dict(torch.load(Path(weights_path) / "pytorch_model.bin"))
28
+
29
+ # Tokenize the text
30
+ inputs = tokenizer(text, padding="max_length", truncation=True, return_tensors="pt")
31
+
32
+ # Set model to evaluation mode
33
+ model.eval()
34
+
35
+ # Make predictions
36
+ with torch.no_grad():
37
+ outputs = model(**inputs)
38
+ logits = outputs.logits
39
+ predictions = torch.argmax(logits, dim=-1)
40
+
41
+ # Get label names (optional, if your model has labels)
42
+ label_names = config.label_names if hasattr(config, "label_names") else None
43
+
44
+ # Return results
45
+ return {
46
+ "predictions": predictions.item() if len(predictions) == 1 else predictions.tolist(),
47
+ "logits": logits.squeeze().tolist() if label_names else None,
48
+ "labels": label_names[predictions.item()] if label_names else None,
49
+ }
50
+
51
+
52
+ # Example usage (replace with your actual model name, text, and weights path)
53
+ model_name = "bert-base-uncased"
54
+ text = "This movie was absolutely fantastic!"
55
+ weights_path = "transformer_weights.pth" # Replace with actual path
56
+ results = predict_with_custom_weights(model_name, text, weights_path)
57
+
58
+ print(f"Predicted label: {results['predictions']}")
59
+
60
+ if results.get("labels"):
61
+ print(f"Corresponding label name: {results['labels']}")
62
+
63
+ if results.get("logits"):
64
+ print(f"Logits: {results['logits']}")