ridvangndoan commited on
Commit
1e8c84d
·
verified ·
1 Parent(s): 236e02a

Add inference.py for Hugging Face Inference API

Browse files
Files changed (1) hide show
  1. inference.py +106 -0
inference.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import os
4
+ import json
5
+ from modeling_omegacode import HolographicMasterCodeTransformer
6
+
7
+ class InferenceHandler:
8
+ def __init__(self):
9
+ self.model = None
10
+ self.initialized = False
11
+
12
+ def initialize(self, context):
13
+ # Modelin yüklendiği depo ID'si (Hugging Face tarafından sağlanır)
14
+ self.model_repo_id = os.getenv("HF_MODEL_ID") # Example: "user/repo_name"
15
+ if not self.model_repo_id:
16
+ raise ValueError("HF_MODEL_ID environment variable not set. Cannot determine model repository.")
17
+
18
+ # Modelin yerel olarak nerede bulunduğunu belirtir
19
+ # Genellikle Hugging Face Inference API, dosyaları `/tmp/model` altına indirir.
20
+ model_dir = context.properties.get("model_dir", "/tmp/model")
21
+
22
+ # `modeling_omegacode.py` dosyasının Python yoluna eklenmesi
23
+ # Bu adım, `modeling_omegacode` modülünün bulunmasını sağlar.
24
+ import sys
25
+ if model_dir not in sys.path:
26
+ sys.path.insert(0, model_dir)
27
+
28
+ # config.json dosyasını oku
29
+ config_path = os.path.join(model_dir, "config.json")
30
+ if not os.path.exists(config_path):
31
+ raise FileNotFoundError(f"config.json not found at {config_path}")
32
+ with open(config_path, 'r') as f:
33
+ model_config = json.load(f)
34
+
35
+ # Modeli yapılandırmadan oluştur
36
+ self.model = HolographicMasterCodeTransformer(
37
+ input_dim=model_config.get('input_dim', 8),
38
+ d_model=model_config.get('d_model', 128),
39
+ nhead=model_config.get('nhead', 8),
40
+ num_layers=model_config.get('num_layers', 6),
41
+ output_dim=model_config.get('output_dim', 1),
42
+ n_harmonics=model_config.get('n_harmonics', 4)
43
+ )
44
+
45
+ # Eğitilmiş ağırlıkları yükle
46
+ model_weights_path = os.path.join(model_dir, "pytorch_model.bin")
47
+ if not os.path.exists(model_weights_path):
48
+ raise FileNotFoundError(f"pytorch_model.bin not found at {model_weights_path}")
49
+ self.model.load_state_dict(torch.load(model_weights_path, map_location='cpu'))
50
+ self.model.eval() # Modeli değerlendirme moduna al
51
+
52
+ self.initialized = True
53
+
54
+ def preprocess(self, inputs):
55
+ # Gelen girişi PyTorch tensoruna dönüştür
56
+ # Hugging Face Inference API'si genellikle JSON veya benzeri bir format alır.
57
+ # Örneğin, inputs = {'input_data': [[...]]}
58
+ try:
59
+ input_data = inputs[0].get('input_data')
60
+ if not input_data:
61
+ raise ValueError("Missing 'input_data' in input payload")
62
+ # Listeyi tensor'a çevir
63
+ tensor_input = torch.tensor(input_data, dtype=torch.float32)
64
+ return tensor_input
65
+ except Exception as e:
66
+ raise ValueError(f"Input preprocessing failed: {e}. Expected format: [{{'input_data': [[...]]}}]")
67
+
68
+ def inference(self, input_batch):
69
+ # Modeli çalıştırma
70
+ if not self.initialized:
71
+ raise RuntimeError("Model not initialized.")
72
+
73
+ # alpha değerini config'den al veya varsayılanı kullan
74
+ # model_config'i initialize içinde self'e atayarak erişilebilir hale getiriyoruz.
75
+ # Ama burada sadece nominal değeri kullanmak daha güvenli olabilir.
76
+ alpha_value = 1/137.035 # Nominal alpha değeri
77
+
78
+ with torch.no_grad():
79
+ output = self.model(input_batch, alpha=alpha_value)
80
+ return output
81
+
82
+ def postprocess(self, outputs):
83
+ # Çıktı tensorunu uygun bir formata dönüştür
84
+ # Örneğin, PyTorch tensorunu bir Python listesine veya sözlüğe çevir.
85
+ return [{'output': outputs.tolist()}]
86
+
87
+ def handle(self, inputs, context):
88
+ # Tüm süreci yöneten ana metod
89
+ model_input = self.preprocess(inputs)
90
+ model_output = self.inference(model_input)
91
+ return self.postprocess(model_output)
92
+
93
+ # Bu kısım genellikle Hugging Face inference container tarafından kullanılır.
94
+ # Yerel test için bu kısmı yorumdan kaldırabilirsiniz.
95
+ # if __name__ == '__main__':
96
+ # handler = InferenceHandler()
97
+ # # Dummy context and inputs for local testing
98
+ # class DummyContext:
99
+ # def __init__(self):
100
+ # self.properties = {"model_dir": "."}
101
+ # dummy_context = DummyContext()
102
+ # handler.initialize(dummy_context)
103
+ #
104
+ # dummy_inputs = [{'input_data': [[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]]}]
105
+ # output = handler.handle(dummy_inputs, dummy_context)
106
+ # print(output)