Download webui/output/multifactor_engine_v3.py from sgfw/kronos: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/spaces/sgfw/kronos/resolve/main/webui/output/multifactor_engine_v3.py
- Command line
-
hf download hf://spaces/sgfw/kronos/webui/output/multifactor_engine_v3.py
-
curl -L -o multifactor_engine_v3.py https://huggingface.co/spaces/sgfw/kronos/resolve/main/webui/output/multifactor_engine_v3.py
28.9 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| Kronos-Enhanced 多因子预测引擎 v3.0 - 解析梯度反向传播 | |
| ====================================================== | |
| 核心改进: 替换数值梯度为解析梯度(反向传播), CPU训练速度提升100-1000倍 | |
| 兼容: 替换 multifactor_engine.py, API不变, 因子体系不变 | |
| """ | |
| import numpy as np | |
| import json | |
| import os | |
| import time | |
| import pickle | |
| from datetime import datetime | |
| # ============================================================ | |
| # 激活函数 | |
| # ============================================================ | |
| def gelu(x): | |
| return 0.5 * x * (1.0 + np.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * x**3))) | |
| def gelu_grad(x): | |
| f = np.sqrt(2.0 / np.pi) * (x + 0.044715 * x**3) | |
| t = np.tanh(f) | |
| return 0.5 * (1.0 + t) + 0.5 * x * (1.0 - t**2) * np.sqrt(2.0 / np.pi) * (1.0 + 3.0 * 0.044715 * x**2) | |
| def layer_norm(x, g, b, eps=1e-5): | |
| m = x.mean(axis=-1, keepdims=True) | |
| v = x.var(axis=-1, keepdims=True) | |
| return g * (x - m) / np.sqrt(v + eps) + b | |
| def layer_norm_grad(dout, x, g, eps=1e-5): | |
| m = x.mean(axis=-1, keepdims=True) | |
| v = x.var(axis=-1, keepdims=True) | |
| si = 1.0 / np.sqrt(v + eps) | |
| xn = (x - m) * si | |
| dg = (dout * xn).reshape(-1, dout.shape[-1]).sum(0) | |
| db = dout.reshape(-1, dout.shape[-1]).sum(0) | |
| D = x.shape[-1] | |
| dxn = dout * g | |
| dv = (dxn * (x - m) * (-0.5) * (v + eps)**(-1.5)).sum(axis=-1, keepdims=True) | |
| dm = (-dxn * si).sum(axis=-1, keepdims=True) + dv * (-2.0 * (x - m)).mean(axis=-1, keepdims=True) | |
| dx = dxn * si + dv * 2.0 * (x - m) / D + dm / D | |
| return dx, dg, db | |
| # ============================================================ | |
| # FeatureTokenizer | |
| # ============================================================ | |
| class FeatureTokenizer: | |
| def __init__(self, n_cont, n_cat, cat_cards, d=48): | |
| self.n_cont = n_cont | |
| self.n_cat = n_cat | |
| self.d = d | |
| self.Wc = np.random.randn(n_cont, d).astype(np.float32) * 0.02 | |
| self.emb = [np.random.randn(c, d).astype(np.float32) * 0.02 for c in cat_cards] | |
| self.g = np.ones(d, dtype=np.float32) | |
| self.b = np.zeros(d, dtype=np.float32) | |
| self._x = None | |
| self._zero_grads() | |
| def _zero_grads(self): | |
| self.dWc = np.zeros_like(self.Wc) | |
| self.dg = np.zeros_like(self.g) | |
| self.db = np.zeros_like(self.b) | |
| def forward(self, xc, xcat): | |
| self._x = xc | |
| out = xc @ self.Wc | |
| for i in range(min(self.n_cat, xcat.shape[-1])): | |
| idx = np.clip(xcat[:, :, i].astype(np.int32), 0, self.emb[i].shape[0] - 1) | |
| out = out + self.emb[i][idx] | |
| self._pre = out.copy() | |
| return layer_norm(out, self.g, self.b) | |
| def backward(self, dout): | |
| dx, dg, db = layer_norm_grad(dout, self._pre, self.g) | |
| self.dg, self.db = dg, db | |
| self.dWc = self._x.reshape(-1, self.n_cont).T @ dx.reshape(-1, self.d) | |
| return None, None | |
| def params_grads(self): | |
| return [(self.Wc, self.dWc), (self.g, self.dg), (self.b, self.db)] | |
| def get_params(self): | |
| return {'Wc': self.Wc, 'emb': [e.copy() for e in self.emb], 'g': self.g, 'b': self.b} | |
| # ============================================================ | |
| # MultiHeadAttention | |
| # ============================================================ | |
| class Attention: | |
| def __init__(self, d, heads, drop=0.1): | |
| self.d, self.heads, self.dh = d, heads, d // heads | |
| self.drop = drop | |
| s = 0.02 | |
| self.Wq = np.random.randn(heads, d, self.dh).astype(np.float32) * s | |
| self.Wk = np.random.randn(heads, d, self.dh).astype(np.float32) * s | |
| self.Wv = np.random.randn(heads, d, self.dh).astype(np.float32) * s | |
| self.Wo = np.random.randn(heads, self.dh, d).astype(np.float32) * s | |
| self.scale = self.dh ** -0.5 | |
| self._cache = {} | |
| self._zero_grads() | |
| def _zero_grads(self): | |
| self.dWq = np.zeros_like(self.Wq) | |
| self.dWk = np.zeros_like(self.Wk) | |
| self.dWv = np.zeros_like(self.Wv) | |
| self.dWo = np.zeros_like(self.Wo) | |
| def forward(self, x, training=False): | |
| B, S, D = x.shape | |
| self._cache['x'] = x | |
| out = np.zeros((B, S, D), dtype=np.float32) | |
| Qs, Ks, Vs, As = [], [], [], [] | |
| for h in range(self.heads): | |
| Q = x @ self.Wq[h]; K = x @ self.Wk[h]; V = x @ self.Wv[h] | |
| a = Q @ K.transpose(0, 2, 1) * self.scale | |
| ae = np.exp(a - a.max(axis=-1, keepdims=True)) | |
| an = ae / (ae.sum(axis=-1, keepdims=True) + 1e-10) | |
| if training and np.random.random() < self.drop: | |
| m = (np.random.rand(B, S, S) > self.drop).astype(np.float32) | |
| an = an * m / (1 - self.drop) | |
| self._cache[f'm{h}'] = m | |
| else: | |
| self._cache[f'm{h}'] = None | |
| out = out + (an @ V) @ self.Wo[h] | |
| Qs.append(Q); Ks.append(K); Vs.append(V); As.append(an) | |
| self._cache['Qs'] = Qs | |
| self._cache['Ks'] = Ks | |
| self._cache['Vs'] = Vs | |
| self._cache['As'] = As | |
| return out | |
| def backward(self, dout): | |
| """反向传播 - 正确的链式法则 | |
| forward: head_out = (A @ V) @ Wo[h], out += head_out | |
| dout: (B, S, D) - from upper layer/residual | |
| """ | |
| x = self._cache['x'] # (B, S, D) | |
| B, S, D = x.shape | |
| dh = D # = d_token | |
| dx = np.zeros_like(x) | |
| self.dWq = np.zeros_like(self.Wq) # (heads, D, dh_head) | |
| self.dWk = np.zeros_like(self.Wk) | |
| self.dWv = np.zeros_like(self.Wv) | |
| self.dWo = np.zeros_like(self.Wo) # (heads, dh_head, D) | |
| for h in range(self.heads): | |
| A = self._cache['As'][h] # (B, S, S) | |
| V = self._cache['Vs'][h] # (B, S, dh) | |
| Q = self._cache['Qs'][h] # (B, S, dh) | |
| K = self._cache['Ks'][h] # (B, S, dh) | |
| # Step 1: dWo from out += (A@V) @ Wo[h] | |
| # head_out[b] = A[b] @ V[b] shape (S, dh) | |
| # out contribution: head_out[b] @ Wo[h] = (S, dh) @ (dh, D) = (S, D) | |
| # dWo[h] = sum_b head_out[b].T @ dout[b] = (dh, S) @ (S, D) = (dh, D) | |
| for b in range(B): | |
| AV = A[b] @ V[b] # (S, dh) | |
| self.dWo[h] += AV.T @ dout[b] # (dh, S) @ (S, D) = (dh, D) ✓ | |
| # Step 2: d(head_out) = dout @ Wo[h].T # (S, D) @ (D, dh) = (S, dh) | |
| d_head_out = np.zeros((B, S, self.dh), dtype=np.float32) | |
| for b in range(B): | |
| d_head_out[b] = dout[b] @ self.Wo[h].T # (S, dh) | |
| # Step 3: d(A@V) = d_head_out | |
| # A@V = sum_j A[b,s,j] * V[b,j,:], so: | |
| # dV[b,j,:] = sum_s A[b,s,j] * d_head_out[b,s,:] | |
| # dA[b,s,j] = sum_d d_head_out[b,s,d] * V[b,j,d] | |
| dV_raw = np.zeros_like(V) # (B, S, dh) | |
| dA = np.zeros((B, S, S), dtype=np.float32) | |
| for b in range(B): | |
| dV_raw[b] = A[b].T @ d_head_out[b] # (S, S)^T @ (S, dh) = (S, dh) | |
| dA[b] = d_head_out[b] @ V[b].T # (S, dh) @ (dh, S) = (S, S) | |
| # Step 4: softmax backward | |
| mask = self._cache.get(f'm{h}') | |
| if mask is not None: | |
| dA = dA * mask / (1 - self.drop) | |
| dA_pre = A * (dA - (dA * A).sum(axis=-1, keepdims=True)) # softmax grad | |
| # Step 5: dQ, dK from dA_pre | |
| # QK^T = raw_scores * (1/scale) | |
| # A = softmax(QK^T * scale), Q[b] = x[b] @ Wq[h] | |
| # dK[b,j,:] = sum_s dA_pre[b,s,j] * Q[b,s,:] * scale | |
| # dQ[b,s,:] = sum_j dA_pre[b,s,j] * K[b,j,:] * scale | |
| for b in range(B): | |
| dQ_b = (dA_pre[b] @ K[b]) * self.scale # (S, dh) | |
| dK_b = (dA_pre[b].T @ Q[b]) * self.scale # (S, dh) | |
| self.dWq[h] += x[b].T @ dQ_b # (D, S) @ (S, dh) = (D, dh) ✓ | |
| self.dWk[h] += x[b].T @ dK_b # (D, dh) ✓ | |
| self.dWv[h] += x[b].T @ dV_raw[b] # (D, dh) ✓ | |
| dx[b] += dQ_b @ self.Wq[h].T # (S, dh) @ (dh, D) = (S, D) ✓ | |
| dx[b] += dK_b @ self.Wk[h].T | |
| dx[b] += dV_raw[b] @ self.Wv[h].T | |
| return dx | |
| def params_grads(self): | |
| return [(self.Wq, self.dWq), (self.Wk, self.dWk), (self.Wv, self.dWv), (self.Wo, self.dWo)] | |
| # ============================================================ | |
| # FeedForward | |
| # ============================================================ | |
| class FFN: | |
| def __init__(self, d, d_h, drop=0.1): | |
| self.d, self.d_h, self.drop = d, d_h, drop | |
| s = 0.02 | |
| self.W1 = np.random.randn(d, d_h).astype(np.float32) * s | |
| self.b1 = np.zeros(d_h, dtype=np.float32) | |
| self.W2 = np.random.randn(d_h, d).astype(np.float32) * s | |
| self.b2 = np.zeros(d, dtype=np.float32) | |
| self._c = {} | |
| self._zero_grads() | |
| def _zero_grads(self): | |
| self.dW1 = np.zeros_like(self.W1) | |
| self.db1 = np.zeros_like(self.b1) | |
| self.dW2 = np.zeros_like(self.W2) | |
| self.db2 = np.zeros_like(self.b2) | |
| def forward(self, x, training=False): | |
| self._c['x'] = x | |
| h = x @ self.W1 + self.b1 | |
| self._c['hp'] = h | |
| h = gelu(h) | |
| if training and np.random.random() < self.drop: | |
| m = (np.random.rand(*h.shape) > self.drop).astype(np.float32) | |
| h = h * m / (1 - self.drop) | |
| self._c['m'] = m | |
| else: | |
| self._c['m'] = None | |
| self._c['ha'] = h | |
| return h @ self.W2 + self.b2 | |
| def backward(self, dout): | |
| N = self._c['ha'].shape[0] * self._c['ha'].shape[1] | |
| ha = self._c['ha'].reshape(N, self.d_h) | |
| do = dout.reshape(N, self.d) | |
| self.dW2 = ha.T @ do | |
| self.db2 = do.sum(0) | |
| dh = (do @ self.W2.T).reshape(self._c['ha'].shape) | |
| m = self._c['m'] | |
| if m is not None: | |
| dh = dh * m / (1 - self.drop) | |
| dh = dh * gelu_grad(self._c['hp']) | |
| xf = self._c['x'].reshape(N, self.d) | |
| dhf = dh.reshape(N, self.d_h) | |
| self.dW1 = xf.T @ dhf | |
| self.db1 = dhf.sum(0) | |
| return (dhf @ self.W1.T).reshape(self._c['x'].shape) | |
| def params_grads(self): | |
| return [(self.W1, self.dW1), (self.b1, self.db1), (self.W2, self.dW2), (self.b2, self.db2)] | |
| # ============================================================ | |
| # TransformerBlock | |
| # ============================================================ | |
| class TransformerBlock: | |
| def __init__(self, d, heads, ffn_factor=4.0/3.0, drop=0.1): | |
| self.d = d | |
| self.ng1 = np.ones(d, dtype=np.float32) | |
| self.nb1 = np.zeros(d, dtype=np.float32) | |
| self.attn = Attention(d, heads, drop) | |
| self.ng2 = np.ones(d, dtype=np.float32) | |
| self.nb2 = np.zeros(d, dtype=np.float32) | |
| self.ffn = FFN(d, int(d * ffn_factor), drop) | |
| self._c = {} | |
| self.dng1 = np.zeros_like(self.ng1) | |
| self.dnb1 = np.zeros_like(self.nb1) | |
| self.dng2 = np.zeros_like(self.ng2) | |
| self.dnb2 = np.zeros_like(self.nb2) | |
| def forward(self, x, training=False): | |
| self._c['x'] = x | |
| h = layer_norm(x, self.ng1, self.nb1) | |
| self._c['h1'] = h.copy() | |
| x = x + self.attn.forward(h, training) | |
| self._c['x1'] = x | |
| h = layer_norm(x, self.ng2, self.nb2) | |
| self._c['h2'] = h.copy() | |
| x = x + self.ffn.forward(h, training) | |
| self._c['x2'] = x | |
| return x | |
| def backward(self, dout): | |
| dh = self.ffn.backward(dout) | |
| dx2, dg2, db2 = layer_norm_grad(dh, self._c['h2'], self.ng2) | |
| self.dng2, self.dnb2 = dg2, db2 | |
| dout2 = dout + dx2 | |
| dh = self.attn.backward(dout2) | |
| dx1, dg1, db1 = layer_norm_grad(dh, self._c['h1'], self.ng1) | |
| self.dng1, self.dnb1 = dg1, db1 | |
| return dout2 + dx1 | |
| def params_grads(self): | |
| p = [(self.ng1, self.dng1), (self.nb1, self.dnb1), | |
| (self.ng2, self.dng2), (self.nb2, self.dnb2)] | |
| p.extend(self.attn.params_grads()) | |
| p.extend(self.ffn.params_grads()) | |
| return p | |
| # ============================================================ | |
| # MultifactorFTTransformer v3 | |
| # ============================================================ | |
| class MultifactorFTTransformer: | |
| def __init__(self, config): | |
| self.config = config | |
| self.n_cont = config.get('num_continuous_features', 65) | |
| self.n_cat = config.get('num_categorical_features', 7) | |
| self.cat_cards = config.get('cat_cardinalities', [8,4,3,6,12,4,4]) | |
| self.d = config.get('d_token', 48) | |
| self.n_blocks = config.get('n_blocks', 2) | |
| self.heads = config.get('attention_n_heads', 4) | |
| self.out_dim = config.get('output_dim', 3) | |
| drop = config.get('attention_dropout', 0.1) | |
| ffn_f = config.get('ffn_d_hidden_factor', 4.0/3.0) | |
| self.tokenizer = FeatureTokenizer(self.n_cont, self.n_cat, self.cat_cards, self.d) | |
| self.blocks = [TransformerBlock(self.d, self.heads, ffn_f, drop) for _ in range(self.n_blocks)] | |
| self.hg = np.ones(self.d, dtype=np.float32) | |
| self.hb = np.zeros(self.d, dtype=np.float32) | |
| self.hW = np.random.randn(self.d, self.out_dim).astype(np.float32) * 0.02 | |
| self.hb2 = np.zeros(self.out_dim, dtype=np.float32) | |
| self._c = {} | |
| self.dhg = np.zeros_like(self.hg) | |
| self.dhb = np.zeros_like(self.hb) | |
| self.dhW = np.zeros_like(self.hW) | |
| self.dhb2 = np.zeros_like(self.hb2) | |
| def forward(self, x_cont, x_cat, training=False): | |
| h = self.tokenizer.forward(x_cont, x_cat) | |
| for blk in self.blocks: | |
| h = blk.forward(h, training) | |
| h = layer_norm(h, self.hg, self.hb) | |
| self._c['h'] = h | |
| out = h @ self.hW + self.hb2 | |
| self._c['h'] = h | |
| self._c['xc'] = x_cont | |
| self._c['xcat'] = x_cat | |
| return out | |
| def backward(self, dout): | |
| if self._c.get('h') is None: | |
| return None, None | |
| N = self._c['h'].shape[0] * self._c['h'].shape[1] | |
| # dout: (B, out_dim) or (B, S, out_dim) | |
| # dout: (B, 3) or (B, S, 3) - 输出层梯度 | |
| B, S, D = self._c['h'].shape | |
| if dout.ndim == 2: | |
| # (B, out_dim) -> (B, S, D) | |
| dh_head = np.zeros((B, S, D), dtype=np.float32) | |
| dh_head[:, -1, :self.out_dim] = dout | |
| else: | |
| dh_head = np.zeros((B, S, D), dtype=np.float32) | |
| dh_head[:, -1, :self.out_dim] = dout[:, -1, :] | |
| # head_W backward: h_flat (B*S, D) @ dh_head_flat -> dW (D, out_dim) | |
| h_flat = self._c['h'].reshape(B * S, D) | |
| dh_flat = dh_head.reshape(B * S, D) | |
| self.dhW = h_flat.T @ dh_flat[:, :self.out_dim] | |
| self.dhb2 = dh_flat[:, :self.out_dim].sum(0) | |
| # propagate through head | |
| dh = (dh_flat[:, :self.out_dim] @ self.hW.T).reshape(B, S, D) | |
| # propagate through only the last timestep (efficient) | |
| dh_sparse = np.zeros((B, S, D), dtype=np.float32) | |
| dh_sparse[:, -1, :] = dh[:, -1, :] | |
| dx, dg, db = layer_norm_grad(dh_sparse, self._c['h'], self.hg, self.hb) | |
| self.dhg, self.dhb = dg, db | |
| for blk in reversed(self.blocks): | |
| dx = blk.backward(dx) | |
| self.tokenizer.backward(dx) | |
| return None, None | |
| def predict(self, x_cont, x_cat): | |
| out = self.forward(x_cont, x_cat, training=False) | |
| # 返回最后一个时间步的预测 | |
| return out[:, -1, :], None | |
| def params_grads(self): | |
| p = self.tokenizer.params_grads() | |
| for blk in self.blocks: | |
| p.extend(blk.params_grads()) | |
| p.extend([(self.hg, self.dhg), (self.hb, self.dhb), (self.hW, self.dhW), (self.hb2, self.dhb2)]) | |
| return p | |
| def count_params(self): | |
| total = sum(np.prod(p.shape) for p, _ in self.params_grads()) | |
| return int(total) | |
| def save(self, path): | |
| data = { | |
| 'config': self.config, | |
| 'tokenizer': self.tokenizer.get_params(), | |
| 'blocks': [{ | |
| 'ng1': b.ng1, 'nb1': b.nb1, 'ng2': b.ng2, 'nb2': b.nb2, | |
| 'attn': {'Wq': b.attn.Wq, 'Wk': b.attn.Wk, 'Wv': b.attn.Wv, 'Wo': b.attn.Wo}, | |
| 'ffn': {'W1': b.ffn.W1, 'b1': b.ffn.b1, 'W2': b.ffn.W2, 'b2': b.ffn.b2}, | |
| } for b in self.blocks], | |
| 'hg': self.hg, 'hb': self.hb, 'hW': self.hW, 'hb2': self.hb2, | |
| 'total_params': self.count_params(), | |
| } | |
| os.makedirs(os.path.dirname(path) or '.', exist_ok=True) | |
| with open(path, 'wb') as f: | |
| pickle.dump(data, f) | |
| print("[INFO] Model saved: {} ({:,} params)".format(path, data['total_params'])) | |
| def load(self, path): | |
| with open(path, 'rb') as f: | |
| data = pickle.load(f) | |
| tp = data['tokenizer'] | |
| self.tokenizer.Wc = tp['Wc'] | |
| self.tokenizer.emb = tp['emb'] | |
| self.tokenizer.g = tp['g'] | |
| self.tokenizer.b = tp['b'] | |
| for i, bd in enumerate(data['blocks']): | |
| self.blocks[i].ng1 = bd['ng1'] | |
| self.blocks[i].nb1 = bd['nb1'] | |
| self.blocks[i].ng2 = bd['ng2'] | |
| self.blocks[i].nb2 = bd['nb2'] | |
| self.blocks[i].attn.Wq = bd['attn']['Wq'] | |
| self.blocks[i].attn.Wk = bd['attn']['Wk'] | |
| self.blocks[i].attn.Wv = bd['attn']['Wv'] | |
| self.blocks[i].attn.Wo = bd['attn']['Wo'] | |
| self.blocks[i].ffn.W1 = bd['ffn']['W1'] | |
| self.blocks[i].ffn.b1 = bd['ffn']['b1'] | |
| self.blocks[i].ffn.W2 = bd['ffn']['W2'] | |
| self.blocks[i].ffn.b2 = bd['ffn']['b2'] | |
| self.hg = data['hg'] | |
| self.hb = data['hb'] | |
| self.hW = data['hW'] | |
| self.hb2 = data['hb2'] | |
| print("[INFO] Model loaded: {}".format(path)) | |
| # ============================================================ | |
| # Composite Scorer | |
| # ============================================================ | |
| class MultifactorCompositeScorer: | |
| def score(self, pred): | |
| trend = float(pred[0]) | |
| change = float(pred[1]) | |
| vol = float(pred[2]) | |
| signal = "强烈看多" if trend > 0.5 and change > 0.03 else \ | |
| "看多" if trend > 0.2 and change > 0.01 else \ | |
| "震荡偏多" if trend > 0 else \ | |
| "震荡" if abs(trend) <= 0.2 else \ | |
| "震荡偏空" if trend < 0 else \ | |
| "看空" if trend < -0.2 else "强烈看空" | |
| raw = trend * 50 + change * 100 - vol * 30 | |
| composite = max(0, min(100, int(50 + raw))) | |
| return { | |
| 'composite_score': composite, | |
| 'signal_text': signal, | |
| 'predicted_trend': "上涨" if trend > 0 else "下跌", | |
| 'predicted_change': round(change * 100, 2), | |
| 'volatility_score': round(vol * 100, 2), | |
| 'trend_strength': round(abs(trend), 4), | |
| } | |
| # ============================================================ | |
| # Trainer v3 - 解析梯度Adam优化器 | |
| # ============================================================ | |
| class AdamOptimizer: | |
| def __init__(self, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, wd=0.0): | |
| self.lr, self.b1, self.b2, self.eps, self.wd = lr, betas[0], betas[1], eps, wd | |
| self.t = 0 | |
| self.m = {} | |
| self.v = {} | |
| def step(self, params_grads, clip=1.0): | |
| self.t += 1 | |
| for i, (p, g) in enumerate(params_grads): | |
| if g is None: | |
| continue | |
| g = np.clip(g, -clip, clip) | |
| if self.wd > 0: | |
| g = g + self.wd * p | |
| if i not in self.m: | |
| self.m[i] = np.zeros_like(p) | |
| self.v[i] = np.zeros_like(p) | |
| self.m[i] = self.b1 * self.m[i] + (1 - self.b1) * g | |
| self.v[i] = self.b2 * self.v[i] + (1 - self.b2) * g**2 | |
| mh = self.m[i] / (1 - self.b1**self.t) | |
| vh = self.v[i] / (1 - self.b2**self.t) | |
| p -= self.lr * mh / (np.sqrt(vh) + self.eps) | |
| class MultifactorTrainer: | |
| def __init__(self, config=None, checkpoint_dir='./ckpts', report_dir='./reports'): | |
| c = config or {} | |
| self.batch = c.get('batch_size', 16) | |
| self.lr = c.get('learning_rate', 1e-3) | |
| self.epochs = c.get('max_epochs', 50) | |
| self.patience = c.get('early_stopping_patience', 8) | |
| self.clip = c.get('gradient_clip_norm', 1.0) | |
| self.wd = c.get('weight_decay', 1e-5) | |
| self.ckpt_dir = checkpoint_dir | |
| self.rpt_dir = report_dir | |
| self.best_val = float('inf') | |
| self.best_ep = 0 | |
| self.pcnt = 0 | |
| self.history = {'train_loss': [], 'val_loss': [], 'reward': [], 'lr': [], 'epoch_time': []} | |
| def _cosine_lr(self, ep, warmup=3): | |
| if ep <= warmup: | |
| return self.lr * ep / warmup | |
| return self.lr * 0.5 * (1 + np.cos(np.pi * (ep - warmup) / max(1, self.epochs - warmup))) | |
| def _reward_loss(self, pred, y, features): | |
| trend_err = np.mean((np.sign(pred[:, 0]) - y[:, 0])**2) | |
| price_err = np.mean((pred[:, 1] - y[:, 1])**2) | |
| vol_err = np.mean((pred[:, 2] - y[:, 2])**2) | |
| loss = 0.4 * trend_err + 0.35 * price_err + 0.25 * vol_err | |
| reward = -trend_err * 2 + 0.5 | |
| return loss, reward | |
| def _reward_loss_grad(self, pred, y, features): | |
| N = pred.shape[0] | |
| dloss = np.zeros_like(pred) | |
| dloss[:, 0] = 0.8 * 2 * (np.sign(pred[:, 0]) - y[:, 0]) | |
| dloss[:, 1] = 0.7 * 2 * (pred[:, 1] - y[:, 1]) / N | |
| dloss[:, 2] = 0.5 * 2 * (pred[:, 2] - y[:, 2]) / N | |
| # scale down to reasonable magnitude | |
| dloss = dloss * 0.01 | |
| return dloss | |
| def train(self, model, Xc_t, Xcat_t, y_t, Xc_v=None, Xcat_v=None, y_v=None, verbose=True): | |
| os.makedirs(self.ckpt_dir, exist_ok=True) | |
| os.makedirs(self.rpt_dir, exist_ok=True) | |
| opt = AdamOptimizer(self.lr, wd=self.wd) | |
| start = datetime.now() | |
| self.best_val = float('inf') | |
| self.pcnt = 0 | |
| if verbose: | |
| print("=" * 70) | |
| print(" 多因子FT-Transformer v3.0 (解析梯度反向传播)") | |
| print(" 训练: {} | 验证: {} | Batch: {} | Epochs: {} | Params: {:,}".format( | |
| len(Xc_t), len(Xc_v) if Xc_v is not None else 0, | |
| self.batch, self.epochs, model.count_params())) | |
| print("=" * 70) | |
| for ep in range(1, self.epochs + 1): | |
| ep_start = time.time() | |
| lr = self._cosine_lr(ep) | |
| opt.lr = lr | |
| idxs = np.random.permutation(len(Xc_t)) | |
| t_losses, rewards = [], [] | |
| for s in range(0, len(idxs), self.batch): | |
| bi = idxs[s:s + self.batch] | |
| xc = Xc_t[bi]; xcat = Xcat_t[bi]; yb = y_t[bi] | |
| # Forward | |
| pred_full = model.forward(xc, xcat, training=True) | |
| pred = pred_full[:, -1, :] # 取最后时间步 | |
| loss, reward = self._reward_loss(pred, yb, xc) | |
| t_losses.append(loss) | |
| rewards.append(reward) | |
| # Backward | |
| dloss_full = np.zeros_like(pred_full) | |
| dloss_full[:, -1, :] = self._reward_loss_grad(pred, yb, xc) | |
| dloss = dloss_full | |
| model.backward(dloss) | |
| opt.step(model.params_grads(), self.clip) | |
| avg_loss = np.mean(t_losses) | |
| avg_r = np.mean(rewards) | |
| # Validation | |
| val_loss = float('inf') | |
| if Xc_v is not None and len(Xc_v) > 0: | |
| vp, _ = model.predict(Xc_v, Xcat_v) | |
| val_loss, _ = self._reward_loss(vp, y_v, Xc_v) | |
| et = time.time() - ep_start | |
| self.history['train_loss'].append(float(avg_loss)) | |
| self.history['val_loss'].append(float(val_loss)) | |
| self.history['reward'].append(float(avg_r)) | |
| self.history['lr'].append(lr) | |
| self.history['epoch_time'].append(et) | |
| if val_loss < self.best_val: | |
| self.best_val = val_loss | |
| self.best_ep = ep | |
| self.pcnt = 0 | |
| self._save(model, ep, val_loss) | |
| else: | |
| self.pcnt += 1 | |
| if verbose and (ep % 5 == 0 or ep == 1 or ep == self.epochs): | |
| print(" Ep {:3d}/{:3d} | LR: {:.6f} | Train: {:.4f} | Val: {:.4f} | R: {:.3f} | {:.1f}s".format( | |
| ep, self.epochs, lr, avg_loss, val_loss, avg_r, et)) | |
| if self.pcnt >= self.patience: | |
| if verbose: | |
| print(" [Early Stop] {} epochs no improvement".format(self.pcnt)) | |
| break | |
| self._load_best(model) | |
| elapsed = (datetime.now() - start).total_seconds() | |
| if verbose: | |
| print("-" * 70) | |
| print(" Done | {:.1f}s | Best Ep: {} | Best Val: {:.4f}".format(elapsed, self.best_ep, self.best_val)) | |
| print("-" * 70) | |
| return self.history | |
| def _save(self, model, ep, val): | |
| model.save(os.path.join(self.ckpt_dir, 'best_multifactor_model.pkl')) | |
| meta = {'epoch': ep, 'val_loss': val, 'best_val_loss': self.best_val, | |
| 'history': {k: [float(v) for v in vs] for k, vs in self.history.items()}, | |
| 'timestamp': datetime.now().isoformat()} | |
| with open(os.path.join(self.ckpt_dir, 'best_multifactor_model_meta.json'), 'w') as f: | |
| json.dump(meta, f, indent=2, ensure_ascii=False, default=str) | |
| def _load_best(self, model): | |
| p = os.path.join(self.ckpt_dir, 'best_multifactor_model.pkl') | |
| if os.path.exists(p): | |
| model.load(p) | |
| # ============================================================ | |
| # IC/IR Validator | |
| # ============================================================ | |
| class ICRValidator: | |
| def monthly_validation(pred, actual, month_labels, min_ic=0.03, min_ir=0.3): | |
| pred, actual = np.array(pred), np.array(actual) | |
| months = sorted(set(month_labels)) | |
| ics = [] | |
| for m in months: | |
| mask = [i for i, l in enumerate(month_labels) if l == m] | |
| if len(mask) < 3: | |
| continue | |
| p, a = pred[mask], actual[mask] | |
| std_p, std_a = p.std(), a.std() | |
| if std_p < 1e-8 or std_a < 1e-8: | |
| continue | |
| ic = np.corrcoef(p, a)[0, 1] | |
| if not np.isnan(ic): | |
| ics.append(ic) | |
| ic_mean = float(np.mean(ics)) if ics else 0.0 | |
| ic_std = float(np.std(ics)) if ics else 1.0 | |
| ir = ic_mean / (ic_std + 1e-8) | |
| return { | |
| 'ic_mean': round(ic_mean, 4), | |
| 'ir': round(ir, 4), | |
| 'pass_ic': ic_mean >= min_ic, | |
| 'pass_ir': ir >= min_ir, | |
| 'monthly_ics': {m: round(float(ic), 4) for m, ic in zip(months, ics)}, | |
| } | |
| # ============================================================ | |
| # RollingTrainPipeline stub | |
| # ============================================================ | |
| class RollingTrainPipeline: | |
| def __init__(self, fe, model_config, train_config, ckpt_dir, rpt_dir): | |
| self.fe = fe | |
| self.model_config = model_config | |
| self.train_config = train_config | |
| self.ckpt_dir = ckpt_dir | |
| self.rpt_dir = rpt_dir | |
| def _check_collinearity(pipeline, X, fe): | |
| cont = X | |
| n = cont.shape[-1] | |
| names = getattr(fe, 'FEATURE_NAMES', [f'f{i}' for i in range(n)]) | |
| if len(names) < n: | |
| names = names + [f'f{i}' for i in range(len(names), n)] | |
| corr = np.corrcoef(cont.T) if cont.shape[0] > cont.shape[1] else np.eye(n) | |
| np.fill_diagonal(corr, 0) | |
| eliminated = [] | |
| for rnd in range(5): | |
| max_corr = np.abs(corr).max() | |
| if max_corr < 0.85: | |
| break | |
| idx = np.unravel_index(np.abs(corr).argmax(), corr.shape) | |
| eliminated.append({'round': rnd+1, 'name': names[idx[0]], 'vif': round(max_corr, 3)}) | |
| corr[idx[0], :] = 0 | |
| corr[:, idx[0]] = 0 | |
| return { | |
| 'original_count': n, | |
| 'final_count': n - len(eliminated), | |
| 'eliminated': eliminated, | |
| 'max_correlation': round(float(np.abs(corr).max()) if corr.size > 0 else 0, 4), | |
| } | |