mkfos 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. easymodel/__init__.py +26 -0
  2. easymodel/__main__.py +48 -0
  3. easymodel/assoc/__init__.py +5 -0
  4. easymodel/assoc/cooccurrence.py +68 -0
  5. easymodel/assoc/features.py +96 -0
  6. easymodel/embedding/__init__.py +4 -0
  7. easymodel/embedding/text.py +63 -0
  8. easymodel/evolve/__init__.py +1 -0
  9. easymodel/evolve/global_change.py +87 -0
  10. easymodel/image/__init__.py +1 -0
  11. easymodel/image/dataset.py +52 -0
  12. easymodel/infx/__init__.py +26 -0
  13. easymodel/infx/core.py +221 -0
  14. easymodel/infx/torch_core.py +196 -0
  15. easymodel/learn/__init__.py +1 -0
  16. easymodel/learn/backward.py +43 -0
  17. easymodel/learn/optim.py +50 -0
  18. easymodel/learn/torch_trainer.py +58 -0
  19. easymodel/learn/trainer.py +57 -0
  20. easymodel/look/__init__.py +1 -0
  21. easymodel/look/forward.py +66 -0
  22. easymodel/metrics.py +67 -0
  23. easymodel/mkfos/__init__.py +6 -0
  24. easymodel/mkfos/core.py +134 -0
  25. easymodel/mkfos/encoders.py +182 -0
  26. easymodel/mkfos/syntax.py +28 -0
  27. easymodel/modes/__init__.py +6 -0
  28. easymodel/modes/registry.py +148 -0
  29. easymodel/moe/__init__.py +4 -0
  30. easymodel/moe/moe.py +150 -0
  31. easymodel/pack/__init__.py +1 -0
  32. easymodel/pack/io.py +35 -0
  33. easymodel/persist.py +53 -0
  34. easymodel/plm/__init__.py +1 -0
  35. easymodel/plm/charlm.py +154 -0
  36. easymodel/py.typed +1 -0
  37. easymodel/rag/__init__.py +4 -0
  38. easymodel/rag/rag.py +39 -0
  39. easymodel/suspect/__init__.py +1 -0
  40. easymodel/suspect/infer.py +56 -0
  41. mkfos-0.9.0.dist-info/METADATA +335 -0
  42. mkfos-0.9.0.dist-info/RECORD +45 -0
  43. mkfos-0.9.0.dist-info/WHEEL +5 -0
  44. mkfos-0.9.0.dist-info/licenses/LICENSE +21 -0
  45. mkfos-0.9.0.dist-info/top_level.txt +1 -0
easymodel/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """EasyModel —— 极小模型底座。
2
+
3
+ look / learn / suspect / pack 四个动作,numpy 与 torch 两个后端;
4
+ MKFOS(RNN / CNN / Transformer / DNN)、MoE、Embedding、RAG、PLM、特征关联。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ __version__ = "0.9.0"
9
+
10
+ from . import assoc, embedding, infx, mkfos, modes, moe, rag # noqa: F401
11
+ from . import metrics, persist # noqa: F401
12
+ from .assoc import Cooccurrence, FeatureModel # noqa: F401
13
+ from .embedding import TextEmbedder # noqa: F401
14
+ from .infx import Core, TextCore # noqa: F401
15
+ from .look.forward import MLP, cross_entropy, softmax # noqa: F401
16
+ from .mkfos import MKFOS # noqa: F401
17
+ from .moe import MoE # noqa: F401
18
+ from .rag import RAG # noqa: F401
19
+
20
+ __all__ = [
21
+ "MLP", "softmax", "cross_entropy",
22
+ "Core", "TextCore", "MKFOS", "MoE", "TextEmbedder", "RAG",
23
+ "FeatureModel", "Cooccurrence",
24
+ "assoc", "embedding", "infx", "mkfos", "modes", "moe", "rag", "metrics", "persist",
25
+ "__version__",
26
+ ]
easymodel/__main__.py ADDED
@@ -0,0 +1,48 @@
1
+ """python -m easymodel —— 命令行入口。
2
+
3
+ python -m easymodel # 帮助
4
+ python -m easymodel modes # 预置模式清单
5
+ python -m easymodel info # 版本 / 可用后端 / 模式数
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+
11
+ from . import __version__, modes
12
+ from .infx import available_backends
13
+
14
+
15
+ def _help():
16
+ print("easymodel " + __version__)
17
+ print()
18
+ print("用法:python -m easymodel <命令>")
19
+ print(" modes 列出所有预置模式(别名 / 必需参数 / 默认参数)")
20
+ print(" info 版本、可用后端、已注册模式数量")
21
+
22
+
23
+ def _modes():
24
+ print(f"{'模式':<12}{'别名':<24}{'需要':<16}{'默认':<30}说明")
25
+ for name, aliases, needs, defaults, summary in modes.table():
26
+ print(f"{name:<12}{aliases:<24}{needs:<16}{defaults:<30}{summary}")
27
+
28
+
29
+ def _info():
30
+ print(f"版本:{__version__}")
31
+ print(f"后端:{', '.join(available_backends())}")
32
+ print(f"模式:{len(modes.available())} 个 —— {', '.join(modes.available())}")
33
+
34
+
35
+ def main(argv=None):
36
+ args = list(argv if argv is not None else sys.argv[1:])
37
+ cmd = args[0] if args else "help"
38
+ if cmd == "modes":
39
+ _modes()
40
+ elif cmd == "info":
41
+ _info()
42
+ else:
43
+ _help()
44
+ return 0
45
+
46
+
47
+ if __name__ == "__main__":
48
+ raise SystemExit(main())
@@ -0,0 +1,5 @@
1
+ """EasyModel · assoc —— 这件事有什么、没有什么,下一个有它的概率是多少。"""
2
+ from .cooccurrence import Cooccurrence
3
+ from .features import FeatureModel
4
+
5
+ __all__ = ["FeatureModel", "Cooccurrence"]
@@ -0,0 +1,68 @@
1
+ """特征之间的共现:看到 A 有某个东西,猜下一个东西也有它,给百分之几。
2
+
3
+ 两个概率:
4
+ 1. 条件概率 P(B | A):历史上「A 出现时 B 也出现」的比例(带平滑);
5
+ 2. 多条证据合成:1 − Π(1 − P(B | A_i)),即 noisy-OR,证据越多越接近 1。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+
12
+ class Cooccurrence:
13
+ def __init__(self, smoothing=1.0):
14
+ self.smoothing = float(smoothing)
15
+ self.names = []
16
+ self.p = None
17
+ self.count = None
18
+
19
+ def fit(self, Y, names=None):
20
+ """Y: (n, F) 的 0/1 矩阵。"""
21
+ Y = np.asarray(Y, dtype=np.float64)
22
+ n, f = Y.shape
23
+ self.names = list(names or [f"f{i}" for i in range(f)])
24
+ self.count = Y.sum(axis=0)
25
+ pair = Y.T @ Y
26
+ s = self.smoothing
27
+ self.p = (pair + s) / (self.count[:, None] + s * f)
28
+ return self
29
+
30
+ def p_given(self, a):
31
+ """P(B|A) 的完整一行。"""
32
+ i = self.names.index(a)
33
+ return {self.names[j]: float(self.p[i, j]) for j in range(len(self.names))}
34
+
35
+ def next_features(self, present, topk=5, exclude_present=True):
36
+ """看到 present 这些特征,下一个事物带某特征的概率(降到 0~1)。"""
37
+ idx = [self.names.index(x) for x in present if x in self.names]
38
+ if not idx:
39
+ return []
40
+ probs = 1.0 - np.prod(1.0 - self.p[idx], axis=0)
41
+ order = np.argsort(probs)[::-1]
42
+ out = []
43
+ for j in order:
44
+ if exclude_present and j in idx:
45
+ continue
46
+ out.append((self.names[int(j)], float(probs[j])))
47
+ if len(out) >= topk:
48
+ break
49
+ return out
50
+
51
+ def report(self, present, topk=3):
52
+ """一句话读数:看到 X → 下一个有 Y 68%、Z 51%。"""
53
+ res = self.next_features(present, topk=topk)
54
+ head = "、".join(present)
55
+ if not res:
56
+ return f"看到 {head} → 没有可推测的特征"
57
+ body = "、".join(f"{name} {prob * 100:.0f}%" for name, prob in res)
58
+ return f"看到 {head} → 下一个有 {body}"
59
+
60
+ def matrix_text(self):
61
+ """把每个特征最可能带出的下一个特征列成表。"""
62
+ rows = []
63
+ for i, name in enumerate(self.names):
64
+ row = self.p[i].copy()
65
+ row[i] = -1.0
66
+ j = int(np.argmax(row))
67
+ rows.append(f"{name:>4s} → {self.names[j]} {row[j] * 100:.0f}%")
68
+ return "\n".join(rows)
@@ -0,0 +1,96 @@
1
+ """物 → 特征:这个东西「有什么、没有什么」,每项给一个概率。
2
+
3
+ 和分类不同:分类是互斥的 softmax(只能是其中一个),这里是独立 sigmoid——
4
+ 一辆车可以同时有轮子、玻璃、方向盘,也可以都没有。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+
10
+ from ..learn.optim import Adam
11
+ from ..look.forward import relu, relu_grad
12
+
13
+
14
+ def sigmoid(z):
15
+ return 1.0 / (1.0 + np.exp(-z))
16
+
17
+
18
+ class FeatureModel:
19
+ def __init__(self, dims, feature_names=None, seed=0):
20
+ """dims: [输入维度, 隐层..., 特征数]"""
21
+ self.dims = list(dims)
22
+ rng = np.random.default_rng(seed)
23
+ self.params = {}
24
+ for i in range(len(self.dims) - 1):
25
+ self.params[f"W{i + 1}"] = rng.normal(0.0, np.sqrt(2.0 / self.dims[i]),
26
+ (self.dims[i], self.dims[i + 1]))
27
+ self.params[f"b{i + 1}"] = np.zeros(self.dims[i + 1])
28
+ self.feature_names = list(feature_names or [f"f{i}" for i in range(self.dims[-1])])
29
+ self.cache = {}
30
+
31
+ # ---------- 前向 ----------
32
+ def forward(self, X):
33
+ p = self.params
34
+ X = np.asarray(X, dtype=np.float64)
35
+ z1 = X @ p["W1"] + p["b1"]
36
+ a1 = relu(z1)
37
+ z2 = a1 @ p["W2"] + p["b2"]
38
+ a2 = relu(z2)
39
+ logits = a2 @ p["W3"] + p["b3"]
40
+ probs = sigmoid(logits)
41
+ self.cache = {"X": X, "z1": z1, "a1": a1, "z2": z2, "a2": a2, "probs": probs}
42
+ return probs
43
+
44
+ def bce(self, probs, Y):
45
+ eps = 1e-12
46
+ Y = np.asarray(Y, dtype=np.float64)
47
+ return float(-(Y * np.log(probs + eps) + (1 - Y) * np.log(1 - probs + eps)).mean())
48
+
49
+ # ---------- 反传 ----------
50
+ def gradients(self, Y):
51
+ c = self.cache
52
+ n = c["probs"].shape[0]
53
+ dlogits = (c["probs"] - np.asarray(Y, dtype=np.float64)) / n
54
+
55
+ g = {}
56
+ g["W3"] = c["a2"].T @ dlogits
57
+ g["b3"] = dlogits.sum(axis=0)
58
+ da2 = dlogits @ self.params["W3"].T
59
+ dz2 = da2 * relu_grad(c["z2"])
60
+ g["W2"] = c["a1"].T @ dz2
61
+ g["b2"] = dz2.sum(axis=0)
62
+ da1 = dz2 @ self.params["W2"].T
63
+ dz1 = da1 * relu_grad(c["z1"])
64
+ g["W1"] = c["X"].T @ dz1
65
+ g["b1"] = dz1.sum(axis=0)
66
+ return g
67
+
68
+ # ---------- 训练 ----------
69
+ def fit(self, X, Y, epochs=120, lr=0.05, batch_size=32, seed=0, verbose=False):
70
+ X = np.asarray(X, dtype=np.float64)
71
+ Y = np.asarray(Y, dtype=np.float64)
72
+ rng = np.random.default_rng(seed)
73
+ opt = Adam(lr=lr)
74
+ n = X.shape[0]
75
+ for epoch in range(1, epochs + 1):
76
+ order = rng.permutation(n)
77
+ for start in range(0, n, batch_size):
78
+ idx = order[start:start + batch_size]
79
+ self.forward(X[idx])
80
+ opt.step(self.params, self.gradients(Y[idx]))
81
+ if verbose and (epoch == 1 or epoch % 20 == 0):
82
+ print(f"epoch {epoch:3d} | bce {self.bce(self.forward(X), Y):.4f}")
83
+ return self
84
+
85
+ # ---------- 推理 ----------
86
+ def proba(self, X):
87
+ return self.forward(X)
88
+
89
+ def describe(self, x, threshold=0.5):
90
+ """输出一句话:有 X(概率)、有 Y(概率);没有 Z。"""
91
+ probs = self.forward(np.asarray(x).reshape(1, -1))[0]
92
+ has = [(self.feature_names[i], float(probs[i])) for i in np.argsort(probs)[::-1] if probs[i] >= threshold]
93
+ hasnt = [self.feature_names[i] for i in np.argsort(probs) if probs[i] < threshold]
94
+ left = "、".join(f"{n}({p * 100:.0f}%)" for n, p in has) or "无"
95
+ right = "、".join(hasnt) or "无"
96
+ return f"有:{left} 没有:{right}"
@@ -0,0 +1,4 @@
1
+ """EasyModel · embedding —— 文本向量化。"""
2
+ from .text import TextEmbedder
3
+
4
+ __all__ = ["TextEmbedder"]
@@ -0,0 +1,63 @@
1
+ """文本向量化:字符袋 + 稀有度加权 + 固定随机投影。
2
+
3
+ 为什么不直接用 PLM 的隐状态:小语料上训练几百步后,字符嵌入会坍缩到同一个方向,
4
+ 任何两句话的余弦都在 0.7 以上,检索排不出差别(实测过)。
5
+
6
+ 现在这版是**无监督的词袋投影**:
7
+ - 每个字有一个固定的随机向量(Johnson–Lindenstrauss 投影,保持近似内积);
8
+ - 按「稀有度」加权(越少见的字权重越高);
9
+ - 减去语料中心方向,避免常见字把所有向量拉向同一侧。
10
+
11
+ 它不懂语义,只懂字面重合。要语义,需要更大语料 + 对比学习,那是另一条路。
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from collections import Counter
16
+
17
+ import numpy as np
18
+
19
+ from ..plm.charlm import CharVocab
20
+
21
+
22
+ class TextEmbedder:
23
+ def __init__(self, corpus, dim=16, seed=0):
24
+ self.corpus = corpus
25
+ self.vocab = CharVocab(corpus)
26
+ self._dim = dim
27
+ rng = np.random.default_rng(seed)
28
+ self.proj = rng.normal(0.0, 1.0 / np.sqrt(dim), (len(self.vocab), dim))
29
+
30
+ counts = Counter(corpus)
31
+ total = max(1, len(corpus))
32
+ self.idf = {c: float(np.log(1.0 + total / (1.0 + n))) for c, n in counts.items()}
33
+ self._center = self._mean_vec(self.vocab.encode(corpus))
34
+
35
+ @property
36
+ def dim(self):
37
+ return self._dim
38
+
39
+ def _weights(self, ids):
40
+ return np.array([self.idf.get(self.vocab.itos[int(i)], 1.0) for i in ids])
41
+
42
+ def _mean_vec(self, ids):
43
+ w = self._weights(ids)
44
+ return (self.proj[ids] * w[:, None]).sum(axis=0) / (w.sum() + 1e-12)
45
+
46
+ def embed(self, text):
47
+ ids = self.vocab.encode(text)
48
+ if len(ids) == 0:
49
+ return np.zeros(self.dim)
50
+ return self._mean_vec(ids) - self._center
51
+
52
+ def embed_many(self, texts):
53
+ return np.stack([self.embed(t) for t in texts])
54
+
55
+ @staticmethod
56
+ def cosine(a, b):
57
+ return float(np.dot(a, b) / ((np.linalg.norm(a) * np.linalg.norm(b)) + 1e-12))
58
+
59
+ def most_similar(self, text, candidates, k=3):
60
+ q = self.embed(text)
61
+ scored = [(self.cosine(q, self.embed(c)), c) for c in candidates]
62
+ scored.sort(key=lambda x: x[0], reverse=True)
63
+ return scored[:k]
@@ -0,0 +1 @@
1
+ """EasyModel · evolve —— 全局改变式搜索。"""
@@ -0,0 +1,87 @@
1
+ """全局改变(Global Change):不靠梯度,靠猜。
2
+
3
+ 规则只有三条:
4
+ 1. 不停随机猜;
5
+ 2. 猜对了(适应度变好)就保留;
6
+ 3. 猜错的位置删掉(回退)。
7
+
8
+ 两种粒度:
9
+ block —— 整组参数一起扰动,好就整体收下,不好整体回退;
10
+ element —— 逐位置试探,只保留真正变好的那几个位置("猜错的删除")。
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+
16
+
17
+ class GlobalChange:
18
+ def __init__(self, sigma=0.05, mode="element", candidates=4, seed=0):
19
+ self.sigma = float(sigma)
20
+ self.mode = mode
21
+ self.candidates = int(candidates)
22
+ self.rng = np.random.default_rng(seed)
23
+ self.accepted = 0
24
+ self.rejected = 0
25
+
26
+ # ---- 工具 ----
27
+ @staticmethod
28
+ def _copy(params):
29
+ return {k: np.array(v, copy=True) for k, v in params.items()}
30
+
31
+ def _perturb_block(self, params):
32
+ for k in params:
33
+ params[k] += self.rng.normal(0.0, self.sigma, params[k].shape)
34
+
35
+ def step(self, params, fitness):
36
+ """对 params 就地尝试一次改变。fitness(params) -> float,越小越好。
37
+
38
+ 返回 True 表示这一步猜对了(参数被保留或部分保留)。
39
+ """
40
+ base = fitness(params)
41
+
42
+ if self.mode == "block":
43
+ for _ in range(self.candidates):
44
+ trial = self._copy(params)
45
+ self._perturb_block(trial)
46
+ if fitness(trial) < base:
47
+ for k in params:
48
+ params[k][...] = trial[k]
49
+ self.accepted += 1
50
+ return True
51
+ self.rejected += 1
52
+ return False
53
+
54
+ # element:随机选一个参数,再随机选其中一部分位置逐个试
55
+ key = list(params)[int(self.rng.integers(len(params)))]
56
+ arr = np.ascontiguousarray(params[key])
57
+ flat = arr.ravel()
58
+ n = max(1, int(flat.size * 0.25))
59
+ idx = self.rng.choice(flat.size, size=min(n, flat.size), replace=False)
60
+
61
+ improved = False
62
+ for i in idx:
63
+ old = flat[i]
64
+ flat[i] = old + self.rng.normal(0.0, self.sigma)
65
+ f = fitness(params)
66
+ if f < base:
67
+ base = f
68
+ improved = True
69
+ self.accepted += 1
70
+ else:
71
+ flat[i] = old
72
+ self.rejected += 1
73
+ return improved
74
+
75
+ def run(self, params, fitness, steps=1000, verbose_every=0):
76
+ history = []
77
+ for s in range(1, steps + 1):
78
+ self.step(params, fitness)
79
+ if verbose_every and s % verbose_every == 0:
80
+ history.append((s, fitness(params)))
81
+ return history
82
+
83
+ @property
84
+ def stats(self):
85
+ total = self.accepted + self.rejected
86
+ rate = self.accepted / total if total else 0.0
87
+ return {"accepted": self.accepted, "rejected": self.rejected, "accept_rate": rate}
@@ -0,0 +1 @@
1
+ """EasyModel · image —— 合成图像数据与预处理。"""
@@ -0,0 +1,52 @@
1
+ """image —— 合成图像数据与预处理。
2
+
3
+ 用 8×8 的三类纹理(横条 / 竖条 / 棋盘)加噪声,避免依赖外部数据集。
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import numpy as np
8
+
9
+
10
+ def make_pattern_images(n_per_class=200, size=8, noise=0.40, shift=True, seed=0):
11
+ """三类纹理 + 随机平移 + 高斯噪声:平移让模型必须学到「条纹方向」而不是记住像素位置。"""
12
+ rng = np.random.default_rng(seed)
13
+ rows = np.arange(size)[:, None] * np.ones((1, size))
14
+ cols = np.ones((size, 1)) * np.arange(size)[None, :]
15
+
16
+ bases = [
17
+ (rows % 2 == 0).astype(np.float64), # 0 横条
18
+ (cols % 2 == 0).astype(np.float64), # 1 竖条
19
+ ((rows + cols) % 2 == 0).astype(np.float64), # 2 棋盘
20
+ ]
21
+
22
+ X, y = [], []
23
+ for cls, base in enumerate(bases):
24
+ for _ in range(n_per_class):
25
+ img = base
26
+ if shift:
27
+ dy, dx = rng.integers(0, size, size=2)
28
+ img = np.roll(np.roll(base, int(dy), axis=0), int(dx), axis=1)
29
+ X.append((img + noise * rng.normal(size=(size, size))).ravel())
30
+ y.append(cls)
31
+
32
+ X = np.asarray(X, dtype=np.float64)
33
+ y = np.asarray(y, dtype=np.int64)
34
+ idx = rng.permutation(len(y))
35
+ return X[idx], y[idx]
36
+
37
+
38
+ def train_val_test_split(X, y, ratios=(0.70, 0.15, 0.15), seed=0):
39
+ rng = np.random.default_rng(seed)
40
+ idx = rng.permutation(len(y))
41
+ n = len(y)
42
+ n_tr = int(n * ratios[0])
43
+ n_va = int(n * ratios[1])
44
+ tr, va, te = idx[:n_tr], idx[n_tr:n_tr + n_va], idx[n_tr + n_va:]
45
+ return (X[tr], y[tr]), (X[va], y[va]), (X[te], y[te])
46
+
47
+
48
+ def standardize(train, *others):
49
+ """只用训练集的均值方差,避免验证/测试信息泄漏。"""
50
+ mu = train.mean(axis=0)
51
+ sd = train.std(axis=0) + 1e-8
52
+ return (train - mu) / sd, *[(o - mu) / sd for o in others]
@@ -0,0 +1,26 @@
1
+ """EasyModel · infx —— 统一核心(模型 / 推理 / 多维态)。
2
+
3
+ 两个后端,一套语法:
4
+ Core numpy,零依赖,手写反传(教学与可移植)
5
+ TorchCore torch,自动微分、GPU(生产)
6
+ """
7
+ from .core import Core, Pipeline, TextCore
8
+ from .torch_core import TORCH_AVAILABLE, TorchCore
9
+
10
+
11
+ def available_backends():
12
+ return ["numpy"] + (["torch"] if TORCH_AVAILABLE else [])
13
+
14
+
15
+ def make(dims=(64, 32, 16, 3), backend="numpy", **kwargs):
16
+ """按后端取一个核心;backend="auto" 时优先 torch。"""
17
+ if backend == "auto":
18
+ backend = "torch" if TORCH_AVAILABLE else "numpy"
19
+ if backend == "torch":
20
+ return TorchCore(dims, **kwargs)
21
+ if backend == "numpy":
22
+ return Core(dims, **kwargs)
23
+ raise ValueError(f"未知后端 {backend!r},可选 {available_backends()}")
24
+
25
+
26
+ __all__ = ["Core", "Pipeline", "TextCore", "TorchCore", "TORCH_AVAILABLE", "make", "available_backends"]