harpertoken commited on
Commit
f34fc9e
·
verified ·
1 Parent(s): 4d68b76

Upload modeling_flow.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_flow.py +72 -0
modeling_flow.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transformers-compatible wrapper for the sandbox-lifecycle temporal model.
2
+
3
+ A GRU over ordered sandbox events, not a transformer. Subclasses
4
+ PreTrainedModel so weights serialize as config.json plus model.safetensors and
5
+ load through AutoModel. Importing this module registers the architecture.
6
+ """
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel
11
+
12
+ EVENTS = [
13
+ "sandbox_create",
14
+ "execute",
15
+ "process_exit",
16
+ "recover",
17
+ "wait",
18
+ "sandbox_teardown",
19
+ ]
20
+ LABELS = ["recover_then_wait", "wait_during_outage", "delayed_fault", "cooldown"]
21
+
22
+
23
+ class FlowConfig(PretrainedConfig):
24
+ model_type = "flow_gru"
25
+
26
+ def __init__(self, num_labels=4, dropout=0.25, **kwargs):
27
+ super().__init__(**kwargs)
28
+ self.num_labels = num_labels
29
+ self.dropout = dropout
30
+
31
+
32
+ class FlowGRU(PreTrainedModel):
33
+ config_class = FlowConfig
34
+ base_model_prefix = "flow"
35
+
36
+ # Transformers 5 reads this mapping while finalising a load. Nothing here
37
+ # is tied, but the attribute has to exist or from_pretrained raises
38
+ # AttributeError before the weights are placed.
39
+ all_tied_weights_keys = {}
40
+
41
+ def __init__(self, config):
42
+ super().__init__(config)
43
+ self.emb = nn.Embedding(len(EVENTS) + 1, 8, padding_idx=0)
44
+ self.gru = nn.GRU(input_size=8 + 2, hidden_size=32, batch_first=True)
45
+ self.head = nn.Linear(32, config.num_labels)
46
+ self.drop = nn.Dropout(config.dropout)
47
+
48
+ def forward(self, events):
49
+ f = torch.cat([self.emb(events[..., 0].long()), events[..., 1:]], -1)
50
+ _, h = self.gru(f)
51
+ return self.head(self.drop(h.squeeze(0)))
52
+
53
+ def predict_label(self, sequence):
54
+ """sequence: list of (type, t, duration) triples. Returns the label."""
55
+ self.eval()
56
+ tv = {t: i + 1 for i, t in enumerate(EVENTS)}
57
+ import numpy as np
58
+
59
+ X = np.array(
60
+ [[float(tv[e[0]]), float(e[1]), float(e[2])] for e in sequence],
61
+ dtype=np.float32,
62
+ )
63
+ with torch.no_grad():
64
+ return LABELS[int(self.forward(torch.from_numpy(X).unsqueeze(0)).argmax(1)[0])]
65
+
66
+
67
+ def register():
68
+ AutoConfig.register(FlowConfig.model_type, FlowConfig, exist_ok=True)
69
+ AutoModel.register(FlowConfig, FlowGRU, exist_ok=True)
70
+
71
+
72
+ register()