markovonnx 0.3.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.
markovonnx/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """markovonnx — Markov chains and HMMs with ONNX export/inference."""
2
+
3
+ from markovonnx.archive import load_markov_archive, save_markov_archive
4
+ from markovonnx.config import MarkovConfig
5
+ from markovonnx.generate import generate_markov
6
+ from markovonnx.hmm import HiddenMarkovModel
7
+ from markovonnx.markov import MarkovChain
8
+ from markovonnx.onnx_export import (
9
+ export_hmm_onnx,
10
+ export_markov_onnx,
11
+ export_markov_sparse_onnx,
12
+ quantize_model,
13
+ )
14
+ from markovonnx.onnx_runtime import HMMONNXRuntime, MarkovONNXRuntime
15
+ from markovonnx.tokenizers import (
16
+ SubwordTokenizer,
17
+ char_tokenize,
18
+ corpus_iter,
19
+ get_tokenize_fn,
20
+ word_tokenize,
21
+ )
22
+ from markovonnx.version import __version__
23
+ from markovonnx.vocabulary import Vocabulary
24
+
25
+ __all__ = [
26
+ "MarkovConfig",
27
+ "MarkovChain",
28
+ "HiddenMarkovModel",
29
+ "Vocabulary",
30
+ "SubwordTokenizer",
31
+ "char_tokenize",
32
+ "word_tokenize",
33
+ "corpus_iter",
34
+ "get_tokenize_fn",
35
+ "export_markov_onnx",
36
+ "export_markov_sparse_onnx",
37
+ "export_hmm_onnx",
38
+ "quantize_model",
39
+ "MarkovONNXRuntime",
40
+ "HMMONNXRuntime",
41
+ "generate_markov",
42
+ "save_markov_archive",
43
+ "load_markov_archive",
44
+ "__version__",
45
+ ]
markovonnx/archive.py ADDED
@@ -0,0 +1,132 @@
1
+ """Save and load portable .markov archive files.
2
+
3
+ A ``.markov`` archive is a ZIP file containing:
4
+ - ``model.onnx`` — the exported ONNX model
5
+ - ``vocab.json`` — the serialized :class:`Vocabulary`
6
+ - ``config.json`` — metadata (model_type, order, etc.)
7
+ """
8
+
9
+ import json
10
+ import tempfile
11
+ import zipfile
12
+ from pathlib import Path
13
+ from typing import Union
14
+
15
+ from markovonnx.config import MarkovConfig
16
+ from markovonnx.hmm import HiddenMarkovModel
17
+ from markovonnx.markov import MarkovChain
18
+ from markovonnx.onnx_export import export_hmm_onnx, export_markov_onnx
19
+ from markovonnx.vocabulary import Vocabulary
20
+
21
+
22
+ def save_markov_archive(
23
+ model: Union[MarkovChain, HiddenMarkovModel],
24
+ archive_path: str,
25
+ ) -> str:
26
+ """Save a trained model + vocabulary to a portable ``.markov`` archive.
27
+
28
+ Args:
29
+ model: A trained :class:`MarkovChain` or :class:`HiddenMarkovModel`.
30
+ archive_path: Destination path (should end in ``.markov``).
31
+
32
+ Returns:
33
+ The archive path.
34
+ """
35
+ Path(archive_path).parent.mkdir(parents=True, exist_ok=True)
36
+
37
+ with tempfile.TemporaryDirectory() as tmpdir:
38
+ onnx_path = str(Path(tmpdir) / "model.onnx")
39
+ vocab_path = str(Path(tmpdir) / "vocab.json")
40
+ config_path = str(Path(tmpdir) / "config.json")
41
+
42
+ if isinstance(model, MarkovChain):
43
+ export_markov_onnx(model, onnx_path)
44
+ model.vocab.save(vocab_path)
45
+ config = {
46
+ "model_type": "markov_chain",
47
+ "order": model.order,
48
+ "smoothing": model.smoothing,
49
+ "vocab_size": model.vocab.size,
50
+ "backoff": model.backoff,
51
+ }
52
+ elif isinstance(model, HiddenMarkovModel):
53
+ export_hmm_onnx(model, onnx_path)
54
+ model.obs_vocab.save(vocab_path)
55
+ config = {
56
+ "model_type": "hmm",
57
+ "n_states": model.n_states,
58
+ "smoothing": model.smoothing,
59
+ "vocab_size": model.obs_vocab.size,
60
+ }
61
+ else:
62
+ raise TypeError(f"Unsupported model type: {type(model)}")
63
+
64
+ with open(config_path, "w") as f:
65
+ json.dump(config, f, indent=2)
66
+
67
+ with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as zf:
68
+ zf.write(onnx_path, "model.onnx")
69
+ zf.write(vocab_path, "vocab.json")
70
+ zf.write(config_path, "config.json")
71
+
72
+ print(f"Saved archive: {archive_path} ({Path(archive_path).stat().st_size / 1024:.1f} KB)")
73
+ return archive_path
74
+
75
+
76
+ def load_markov_archive(archive_path: str) -> dict:
77
+ """Load a ``.markov`` archive and return runtime components.
78
+
79
+ Args:
80
+ archive_path: Path to a ``.markov`` file.
81
+
82
+ Returns:
83
+ A dict with keys:
84
+ - ``"runtime"``: :class:`MarkovONNXRuntime` or :class:`HMMONNXRuntime`
85
+ - ``"vocab"``: :class:`Vocabulary`
86
+ - ``"config"``: dict of metadata (model_type, order, etc.)
87
+ - ``"onnx_path"``: path to the extracted ONNX file (in temp dir)
88
+ """
89
+ # Lazy imports to avoid circular dependency
90
+ from markovonnx.onnx_runtime import HMMONNXRuntime, MarkovONNXRuntime
91
+
92
+ import atexit
93
+ import shutil
94
+
95
+ tmpdir = tempfile.mkdtemp(prefix="markovonnx_")
96
+ atexit.register(shutil.rmtree, tmpdir, True) # clean up on exit
97
+
98
+ with zipfile.ZipFile(archive_path, "r") as zf:
99
+ zf.extractall(tmpdir)
100
+
101
+ onnx_path = str(Path(tmpdir) / "model.onnx")
102
+ vocab_path = str(Path(tmpdir) / "vocab.json")
103
+ config_path = str(Path(tmpdir) / "config.json")
104
+
105
+ vocab = Vocabulary.load(vocab_path)
106
+ with open(config_path, "r") as f:
107
+ config = json.load(f)
108
+
109
+ model_type = config["model_type"]
110
+
111
+ if model_type == "markov_chain":
112
+ rt = MarkovONNXRuntime(onnx_path, vocab, config["order"])
113
+ elif model_type == "hmm":
114
+ # Create a minimal HMM for the runtime wrapper (needs pi, obs_vocab)
115
+ import numpy as np
116
+ hmm = HiddenMarkovModel(
117
+ n_states=config["n_states"],
118
+ obs_vocab=vocab,
119
+ smoothing=config.get("smoothing", 1e-5),
120
+ )
121
+ # ORT expects float32 for alpha_in
122
+ hmm.pi = hmm.pi.astype(np.float32)
123
+ rt = HMMONNXRuntime(onnx_path, hmm)
124
+ else:
125
+ raise ValueError(f"Unknown model_type in archive: {model_type}")
126
+
127
+ return {
128
+ "runtime": rt,
129
+ "vocab": vocab,
130
+ "config": config,
131
+ "onnx_path": onnx_path,
132
+ }
markovonnx/cli.py ADDED
@@ -0,0 +1,113 @@
1
+ """Command-line interface for markovonnx."""
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from markovonnx.version import __version__
7
+
8
+
9
+ def cmd_train(args: argparse.Namespace) -> None:
10
+ """Train a Markov chain and save as .markov archive."""
11
+ from markovonnx.archive import save_markov_archive
12
+ from markovonnx.markov import MarkovChain
13
+ from markovonnx.tokenizers import char_tokenize, corpus_iter, get_tokenize_fn, word_tokenize
14
+ from markovonnx.vocabulary import Vocabulary
15
+
16
+ tokenize_fn = get_tokenize_fn(args.mode)
17
+
18
+ print(f"Building vocabulary from {args.corpus}...")
19
+ vocab = Vocabulary(max_vocab=args.max_vocab)
20
+ vocab.build_streaming(args.corpus, tokenize_fn=tokenize_fn, max_lines=args.max_lines)
21
+ print(f"Vocabulary: {vocab.size} tokens")
22
+
23
+ print(f"Training MarkovChain(order={args.order}, backoff={args.backoff})...")
24
+ mc = MarkovChain(
25
+ order=args.order,
26
+ vocab=vocab,
27
+ smoothing=args.smoothing,
28
+ backoff=args.backoff,
29
+ )
30
+ mc.fit_streaming(args.corpus, tokenize_fn=tokenize_fn, max_lines=args.max_lines)
31
+
32
+ save_markov_archive(mc, args.output)
33
+
34
+
35
+ def cmd_generate(args: argparse.Namespace) -> None:
36
+ """Generate text from a .markov archive."""
37
+ from markovonnx.archive import load_markov_archive
38
+ from markovonnx.generate import generate_markov
39
+
40
+ loaded = load_markov_archive(args.archive)
41
+ rt = loaded["runtime"]
42
+ config = loaded["config"]
43
+ order = config.get("order", 2)
44
+ mode = args.mode
45
+
46
+ text = generate_markov(
47
+ rt, args.seed, args.length,
48
+ temperature=args.temperature, mode=mode, order=order,
49
+ )
50
+ print(text)
51
+
52
+
53
+ def cmd_info(args: argparse.Namespace) -> None:
54
+ """Show metadata from a .markov archive."""
55
+ import json
56
+ import zipfile
57
+ from pathlib import Path
58
+
59
+ with zipfile.ZipFile(args.archive, "r") as zf:
60
+ config = json.loads(zf.read("config.json"))
61
+
62
+ size_kb = Path(args.archive).stat().st_size / 1024
63
+ print(f"Archive: {args.archive} ({size_kb:.1f} KB)")
64
+ for key, val in config.items():
65
+ print(f" {key}: {val}")
66
+
67
+
68
+ def main() -> None:
69
+ """Entry point for ``markovonnx`` CLI."""
70
+ parser = argparse.ArgumentParser(
71
+ prog="markovonnx",
72
+ description="Markov chains and HMMs with ONNX export/inference",
73
+ )
74
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
75
+ sub = parser.add_subparsers(dest="command")
76
+
77
+ # -- train ----------------------------------------------------------------
78
+ p_train = sub.add_parser("train", help="Train a Markov chain from a text corpus")
79
+ p_train.add_argument("corpus", help="Path to text corpus (one line per sequence)")
80
+ p_train.add_argument("-o", "--output", default="model.markov", help="Output .markov archive path")
81
+ p_train.add_argument("--mode", choices=["char", "word"], default="char", help="Tokenization mode")
82
+ p_train.add_argument("--order", type=int, default=3, help="N-gram order")
83
+ p_train.add_argument("--smoothing", type=float, default=1e-5, help="Laplace smoothing alpha")
84
+ p_train.add_argument("--max-vocab", type=int, default=0, help="Max vocabulary size (0=unlimited)")
85
+ p_train.add_argument("--max-lines", type=int, default=0, help="Max corpus lines (0=unlimited)")
86
+ p_train.add_argument("--backoff", action="store_true", help="Enable interpolated backoff")
87
+
88
+ # -- generate -------------------------------------------------------------
89
+ p_gen = sub.add_parser("generate", help="Generate text from a .markov archive")
90
+ p_gen.add_argument("archive", help="Path to .markov archive")
91
+ p_gen.add_argument("--seed", default="", help="Seed text")
92
+ p_gen.add_argument("--length", type=int, default=100, help="Tokens to generate")
93
+ p_gen.add_argument("--temperature", type=float, default=0.7, help="Sampling temperature")
94
+ p_gen.add_argument("--mode", choices=["char", "word"], default="char", help="Tokenization mode")
95
+
96
+ # -- info -----------------------------------------------------------------
97
+ p_info = sub.add_parser("info", help="Show metadata from a .markov archive")
98
+ p_info.add_argument("archive", help="Path to .markov archive")
99
+
100
+ args = parser.parse_args()
101
+ if args.command == "train":
102
+ cmd_train(args)
103
+ elif args.command == "generate":
104
+ cmd_generate(args)
105
+ elif args.command == "info":
106
+ cmd_info(args)
107
+ else:
108
+ parser.print_help()
109
+ sys.exit(1)
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()
markovonnx/config.py ADDED
@@ -0,0 +1,72 @@
1
+ """Configuration dataclass with environment variable defaults."""
2
+
3
+ import dataclasses
4
+ import os
5
+ from pathlib import Path
6
+
7
+
8
+ def _env(key: str, default: object, cast: type = str) -> object:
9
+ """Read environment variable with typed default."""
10
+ val = os.environ.get(key, "")
11
+ return cast(val) if val else default
12
+
13
+
14
+ @dataclasses.dataclass
15
+ class MarkovConfig:
16
+ """Configuration for markovonnx training and export.
17
+
18
+ All fields fall back to ``MARKOV_*`` environment variables when not
19
+ provided explicitly.
20
+ """
21
+
22
+ data_path: str = ""
23
+ data_mode: str = "char"
24
+ order: int = 2
25
+ hmm_states: int = 16
26
+ smoothing: float = 1e-5
27
+ max_vocab: int = 0
28
+ max_lines: int = 0
29
+ stream_threshold_mb: int = 1024
30
+ onnx_path: str = "markov.onnx"
31
+ quantize: bool = True
32
+ quant_path: str = "markov_int8.onnx"
33
+ temperature: float = 0.5
34
+ gen_length: int = 10
35
+ seed: str = ""
36
+ outdir: str = "./markov"
37
+
38
+ @classmethod
39
+ def from_env(cls) -> "MarkovConfig":
40
+ """Build config from ``MARKOV_*`` environment variables."""
41
+ return cls(
42
+ data_path=_env("MARKOV_DATA_PATH", ""),
43
+ data_mode=_env("MARKOV_DATA_MODE", "char"),
44
+ order=_env("MARKOV_ORDER", 2, int),
45
+ hmm_states=_env("MARKOV_HMM_STATES", 16, int),
46
+ smoothing=_env("MARKOV_SMOOTHING", 1e-5, float),
47
+ max_vocab=_env("MARKOV_MAX_VOCAB", 0, int),
48
+ max_lines=_env("MARKOV_MAX_LINES", 0, int),
49
+ stream_threshold_mb=_env("MARKOV_STREAM_MB", 1024, int),
50
+ onnx_path=_env("MARKOV_ONNX_PATH", "markov.onnx"),
51
+ quantize=_env("MARKOV_QUANTIZE", "1") in ("1", "true", "yes"),
52
+ quant_path=_env("MARKOV_QUANT_PATH", "markov_int8.onnx"),
53
+ temperature=_env("MARKOV_TEMP", 0.5, float),
54
+ gen_length=_env("MARKOV_GEN_LEN", 10, int),
55
+ seed=_env("MARKOV_SEED", ""),
56
+ outdir=_env("MARKOV_OUTDIR", "./markov"),
57
+ )
58
+
59
+ @property
60
+ def outdir_path(self) -> Path:
61
+ """Return *outdir* as a :class:`~pathlib.Path`."""
62
+ return Path(self.outdir)
63
+
64
+ @property
65
+ def resolved_onnx_path(self) -> str:
66
+ """Full path combining *outdir* and *onnx_path*."""
67
+ return str(self.outdir_path / self.onnx_path)
68
+
69
+ @property
70
+ def resolved_quant_path(self) -> str:
71
+ """Full path combining *outdir* and *quant_path*."""
72
+ return str(self.outdir_path / self.quant_path)
markovonnx/generate.py ADDED
@@ -0,0 +1,62 @@
1
+ """Text generation using a Markov ONNX Runtime model."""
2
+
3
+ from typing import List, Optional
4
+
5
+ from markovonnx.onnx_runtime import MarkovONNXRuntime
6
+ from markovonnx.tokenizers import SubwordTokenizer
7
+
8
+
9
+ def generate_markov(
10
+ ort_model: MarkovONNXRuntime,
11
+ seed: str,
12
+ length: int,
13
+ temperature: float = 1.0,
14
+ mode: str = "char",
15
+ order: int = 2,
16
+ bpe_tokenizer: Optional[SubwordTokenizer] = None,
17
+ ) -> str:
18
+ """Generate text auto-regressively using an ONNX Markov model.
19
+
20
+ Args:
21
+ ort_model: A loaded :class:`MarkovONNXRuntime`.
22
+ seed: Initial text to seed generation.
23
+ length: Number of tokens to generate.
24
+ temperature: Sampling temperature.
25
+ mode: Tokenization mode (``'char'``, ``'word'``, ``'bpe'``).
26
+ order: N-gram order (context window size).
27
+ bpe_tokenizer: Required when *mode* is ``'bpe'``.
28
+
29
+ Returns:
30
+ Generated text string.
31
+ """
32
+ if mode == "char":
33
+ context: List = list(seed) if seed else list("the ")
34
+ result = list(context)
35
+ for _ in range(length):
36
+ nxt = ort_model.sample(context[-order:], temperature)
37
+ result.append(nxt)
38
+ context = (context + [nxt])[-order:]
39
+ return "".join(result)
40
+
41
+ if mode in ("bpe", "subword"):
42
+ if bpe_tokenizer is None:
43
+ raise ValueError("bpe_tokenizer is required for BPE generation")
44
+ context: List = list(bpe_tokenizer.encode_bpe(seed)) if seed else []
45
+ # Pad context to at least `order` tokens with UNK (ID 0)
46
+ while len(context) < order:
47
+ context.insert(0, 0)
48
+ result = list(context)
49
+ for _ in range(length):
50
+ nxt = ort_model.sample(context[-order:], temperature)
51
+ result.append(nxt)
52
+ context = (context + [nxt])[-order:]
53
+ return bpe_tokenizer.decode_bpe(result)
54
+
55
+ # word mode
56
+ context = seed.split() if seed else ["the"]
57
+ result = list(context)
58
+ for _ in range(length):
59
+ nxt = ort_model.sample(context[-order:], temperature)
60
+ result.append(nxt)
61
+ context = (context + [nxt])[-order:]
62
+ return " ".join(result)