Upload inference.py
Browse files- inference.py +78 -0
inference.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Retail World Model Inference Script
|
| 2 |
+
Predicts future retail sales given historical context using the trained world model.
|
| 3 |
+
"""
|
| 4 |
+
import os, pickle, numpy as np, pandas as pd, torch, torch.nn as nn
|
| 5 |
+
from transformers import AutoModelForSeq2SeqLM, AutoConfig
|
| 6 |
+
from sklearn.preprocessing import StandardScaler, LabelEncoder
|
| 7 |
+
|
| 8 |
+
# Same architecture as training
|
| 9 |
+
class RetailWorldModel(nn.Module):
|
| 10 |
+
def __init__(self, base_model_name, context_len, pred_len, num_variates, embed_dim):
|
| 11 |
+
super().__init__()
|
| 12 |
+
self.config = AutoConfig.from_pretrained(base_model_name)
|
| 13 |
+
self.encoder = AutoModelForSeq2SeqLM.from_pretrained(base_model_name)
|
| 14 |
+
self.context_len=context_len; self.pred_len=pred_len
|
| 15 |
+
self.num_variates=num_variates; self.embed_dim=embed_dim
|
| 16 |
+
self.input_proj = nn.Linear(num_variates, self.config.d_model)
|
| 17 |
+
self.latent_dynamics = nn.LSTM(self.config.d_model, self.config.d_model, 2, batch_first=True, dropout=0.1)
|
| 18 |
+
self.mean_head = nn.Sequential(nn.Linear(self.config.d_model, embed_dim), nn.GELU(), nn.Linear(embed_dim, 1))
|
| 19 |
+
self.var_head = nn.Sequential(nn.Linear(self.config.d_model, embed_dim), nn.GELU(), nn.Linear(embed_dim, 1), nn.Softplus())
|
| 20 |
+
def forward(self, context):
|
| 21 |
+
x = self.input_proj(context)
|
| 22 |
+
enc_out = self.encoder.encoder(inputs_embeds=x, return_dict=True).last_hidden_state
|
| 23 |
+
h0 = enc_out[:, -1:, :].transpose(0, 1).repeat(2, 1, 1)
|
| 24 |
+
c0 = torch.zeros_like(h0)
|
| 25 |
+
states=[]; curr = enc_out[:, -1:, :]
|
| 26 |
+
for _ in range(self.pred_len):
|
| 27 |
+
out, (h0, c0) = self.latent_dynamics(curr, (h0, c0))
|
| 28 |
+
states.append(out); curr=out
|
| 29 |
+
states = torch.cat(states, dim=1)
|
| 30 |
+
mean = self.mean_head(states).squeeze(-1)
|
| 31 |
+
var = self.var_head(states).squeeze(-1)
|
| 32 |
+
return {'mean': mean, 'var': var}
|
| 33 |
+
|
| 34 |
+
def load_model_and_scaler(checkpoint_dir, base_model_name='amazon/chronos-bolt-small',
|
| 35 |
+
context_len=60, pred_len=14, num_variates=5, embed_dim=64):
|
| 36 |
+
model = RetailWorldModel(base_model_name, context_len, pred_len, num_variates, embed_dim)
|
| 37 |
+
ckpt = torch.load(os.path.join(checkpoint_dir, 'pytorch_model.bin'), map_location='cpu')
|
| 38 |
+
model.load_state_dict(ckpt, strict=False)
|
| 39 |
+
with open(os.path.join(checkpoint_dir, 'scaler.pkl'), 'rb') as f:
|
| 40 |
+
scaler = pickle.load(f)
|
| 41 |
+
return model, scaler
|
| 42 |
+
|
| 43 |
+
def predict(model, scaler, context_history, steps=14):
|
| 44 |
+
"""
|
| 45 |
+
context_history: numpy array (context_len, num_variates) - last 60 days
|
| 46 |
+
Returns: dict with 'mean' (actual sales), 'lower', 'upper' (90% CI)
|
| 47 |
+
"""
|
| 48 |
+
model.eval()
|
| 49 |
+
with torch.no_grad():
|
| 50 |
+
ctx = torch.tensor(context_history).unsqueeze(0).float()
|
| 51 |
+
out = model(ctx)
|
| 52 |
+
mean = out['mean'].squeeze(0).numpy()
|
| 53 |
+
std = np.sqrt(out['var'].squeeze(0).numpy())
|
| 54 |
+
mean_sales = scaler.inverse_transform(mean.reshape(-1, 1)).flatten()
|
| 55 |
+
std_sales = std * scaler.scale_[0]
|
| 56 |
+
return {
|
| 57 |
+
'mean': mean_sales,
|
| 58 |
+
'lower': mean_sales - 1.645 * std_sales,
|
| 59 |
+
'upper': mean_sales + 1.645 * std_sales,
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if __name__ == '__main__':
|
| 63 |
+
import argparse
|
| 64 |
+
parser = argparse.ArgumentParser()
|
| 65 |
+
parser.add_argument('--checkpoint', required=True)
|
| 66 |
+
parser.add_argument('--history', required=True, help='CSV with 60 rows of history')
|
| 67 |
+
parser.add_argument('--output', default='predictions.csv')
|
| 68 |
+
args = parser.parse_args()
|
| 69 |
+
|
| 70 |
+
model, scaler = load_model_and_scaler(args.checkpoint)
|
| 71 |
+
hist = pd.read_csv(args.history)
|
| 72 |
+
pred = predict(model, scaler, hist.values)
|
| 73 |
+
df = pd.DataFrame({'day': range(1, len(pred['mean'])+1),
|
| 74 |
+
'predicted_sales': pred['mean'],
|
| 75 |
+
'lower_90': pred['lower'],
|
| 76 |
+
'upper_90': pred['upper']})
|
| 77 |
+
df.to_csv(args.output, index=False)
|
| 78 |
+
print(f"Saved predictions to {args.output}")
|