Metadata-Version: 2.4
Name: preframr-tokens
Version: 0.20.0
Summary: SID reglog parsing, tokenization, and macro transforms extracted from the preframr research codebase.
Author: Anarkiwi
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/anarkiwi/preframr-tokens
Project-URL: Source, https://github.com/anarkiwi/preframr-tokens
Project-URL: Issues, https://github.com/anarkiwi/preframr-tokens/issues
Keywords: sid,c64,preframr,tokenizer,reglog
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2
Requires-Dist: pyarrow>=14
Requires-Dist: tokenizers>=0.20
Requires-Dist: tqdm>=4.65
Requires-Dist: zstandard>=0.22
Requires-Dist: numba>=0.59
Provides-Extra: dev
Requires-Dist: black>=24; extra == "dev"
Requires-Dist: coverage>=7; extra == "dev"
Requires-Dist: pylint>=3; extra == "dev"
Requires-Dist: pyright>=1.1; extra == "dev"
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-cov>=4; extra == "dev"
Requires-Dist: preframr-audio>=0.5.0; extra == "dev"
Provides-Extra: audio
Requires-Dist: preframr-audio>=0.5.0; extra == "audio"
Dynamic: license-file

# preframr-tokens

SID reglog parsing, tokenization, and macro transforms extracted from
the [preframr](https://github.com/anarkiwi/preframr) research codebase.

Torch-free. The training-side concerns (model, loss, DataLoader,
predict) live in the main `preframr` repo; this package contains the
stable parsing + encoding layer that produces the parsed parquets +
unigram tokenizer alphabet that downstream training consumes.

## Install

```bash
pip install preframr-tokens
```

Optional extras:

- `preframr-tokens[audio]` — pulls `preframr-audio` for the lossy-macro
  round-trip check (`Transform.round_trip_check` lazy-imports
  `preframr_audio.fidelity.assert_dfs_render_equivalent` for any
  `TIER != "bit_exact"` macro). Skip if you only use the parsing /
  tokenisation / constrained-decode paths.

## Importing

Import from the package root:

```python
from preframr_tokens import RegLogParser, RegTokenizer, Corpus, reg_class
```

`preframr_tokens.__all__` is the semver-promised surface. Two submodules
are also public, stable namespaces you import directly:
`preframr_tokens.stfconstants` (reg ids, op codes, dtypes, PAL clock) and
`preframr_tokens.engine_fingerprint` (feature-vector layout, `ClusterTable`,
`compute_fingerprint`). Every other `preframr_tokens.*` submodule path is
**internal and may move between releases** — depend on the root re-exports
instead. The module list below documents that internal structure.

## Modules

- `preframr_tokens.reglogparser` -- SID dump → parsed dataframe
  pipeline. `RegLogParser`, plus `read_initial_irq` (first-frame IRQ
  read off a parser-output df, with PAL default).
- `preframr_tokens.regtokenizer` -- alphabet build + unigram tokenizer
  fit. `RegTokenizer`.
- `preframr_tokens.macros.*` -- declarative `Transform` registry plus
  the macro / pre-norm passes (slope, preset, hard_restart,
  legato_per_cluster, voice_block_order, ctrl_bigram, loop, etc.).
  Macros declare `OP_CODES`, `LOSS_TIER`, `SUBSTITUTABLE_OPS`,
  `MUST_FOLLOW`, etc. on their classes; `pipeline_check.validate_pipeline_spec`
  validates a pipeline declaratively.
- `preframr_tokens.stfconstants` -- SID register IDs, op codes, pandas
  dtypes, PAL clock constants.
- `preframr_tokens.engine_fingerprint` -- engine clustering for
  cross-engine evaluation pinning.
- `preframr_tokens.coarsen_pass` -- tracker-export pass (lossy
  audio-domain bucketing).
- `preframr_tokens.dump_meta` -- per-dump metadata sidecar with code-hash
  staleness gate.
- `preframr_tokens.reg_match` -- voice-relative register classification:
  raw `reg` id → boolean row mask (`freq_match`, `pcm_match`,
  `ctrl_match`, `adsr_match`, `ad_match`, `sr_match`, `filter_match`,
  `frame_match`, built on `vreg_match`), plus `reg_class(reg) -> (kind,
  voice)` for scalar per-reg classification. Pure-`stfconstants`
  parse-domain sibling of `macros.roles`.
- `preframr_tokens.palette_io` -- JSON sidecar load/dump for the
  engine-fingerprint / engine-fp-cluster `df.attrs`.
- `preframr_tokens.macros.roles` -- single source of truth for macro
  `(op, subreg)` → role classification. `distance_pair_role`,
  `slope_subreg_role`, `frame_weight_role`, plus the
  `DISTANCE_PAIR_OPS` table and the `DistancePairSpec` dataclass. The
  parse-domain reg-id counterpart is `reg_match`.
- `preframr_tokens.vocab_signature` -- `VocabSignature` class. Single-
  pass per-vocab-id (loss-tier, frame-time-weight) computation. The
  `tier_classify` and `token_weighting` free functions are thin
  wrappers; consumers that need both should build a `VocabSignature`
  directly to avoid two passes over the vocab.
- `preframr_tokens.alphabet_projection` -- eval-set atom projection
  table.
- `preframr_tokens.reg_mappers` -- `FreqMapper` (PAL clock + cents
  quantization).
- `preframr_tokens.constrained_decode` -- per-step structural-validity
  mask for sampling-time logit guarding. Pure numpy state machine;
  consumers (torch users) apply the returned bool mask with a single
  `masked_fill` at the boundary.
- `preframr_tokens.blocks` -- block iteration + materialization
  helpers: `iter_voiced_blocks`, `materialize_block_array`,
  `parser_worker`, `glob_dumps`, `reg_widths_path`,
  `self_contained_prompt_df`, plus the `SeqMeta` dataclass and
  `parse_eval_reglogs` / `LEGACY_EVAL_SUBSET_NAME` for eval-subset
  routing. Torch-free; main repo's RegDataset wraps the outputs in
  DataLoaders.
- `preframr_tokens.audit_primitives` -- pure-Python token-level
  audit functions: `tier_accuracy` (per-tier hit-rate + content/
  structural ratio), `detect_tail_cycle` (loop-collapse detector),
  `distinct_n` (n-gram diversity). Used by the generalization-gate
  callback in main repo and by post-hoc audit scripts.
- `preframr_tokens.parse_runner` -- `write_df(args, logger, dump_file)`
  + `parse_corpus(args, logger)` parallel dump-parsing orchestrator.
  Main-repo `preframr/parse.py` is a thin argparse shim around this.
- `preframr_tokens.corpus` -- `Corpus` class: torch-free corpus
  orchestration owning the RegTokenizer + reg_widths +
  tokenize-stage metadata. Methods `load_dfs`, `make_tokens`,
  `encode_and_save_cached_blocks`, `try_preload_from_disk`,
  `preload`, `iter_block_seqs`, `iter_predict_block_seqs` cover
  the full parse → tokenize → load pipeline up to the point where
  blocks need to be routed into a torch `BlockMapper` (main repo's
  RegDataset is a thin adapter that does that routing).

## Library-only

No CLI entry points. Consumers build their own (the main `preframr`
repo's `parse.py` and `stftokenize.py` are simple wrappers that
construct `RegLogParser` / `RegTokenizer` from an `argparse.Namespace`).

## API surface

Design principle: **expose decisions, not facts.** Whenever a
consumer would otherwise import raw `stfconstants` (reg ids, op
codes, subreg constants) and re-implement a classification switch
on top of them, that's a sign the helper should live here instead.
Helpers ride the same code as the parser/tokenizer, so the
classification matches the data by construction.

The decision helpers below were added in that vein; each replaces an
ad-hoc reg/op classification or arithmetic that consumers used to
open-code on top of raw `stfconstants`:

- `preframr_tokens.tier_classify` — `vocab_id_tier`,
  `build_vocab_tier_ids`, `build_vocab_tier_map`, `CONTENT_TIER`.
  Replaces ad-hoc reg/op tier classification in consumers.
- `preframr_tokens.reg_match.reg_class` — scalar `reg -> (kind, voice)`
  classification (`"FREQ" | "PW" | "CTRL" | "AD" | "SR"`). Replaces the
  hand-built `{reg: (kind, voice)}` table consumers open-coded from the
  per-voice register layout.
- `preframr_tokens.token_weighting.vocab_frame_weights` — per-vocab
  audio-frame-time weighting. Replaces ad-hoc BACK_REF / DO_LOOP /
  SLOPE / DELAY / FRAME val accounting in consumers.
- `preframr_tokens.vocab_signature.VocabSignature` — single-pass
  bundle of both of the above. Consumers that need both `tier_ids`
  and `frame_weights` should construct this directly.
- `preframr_tokens.reglogparser.read_initial_irq` — first-frame
  diff lookup with PAL default. Replaces the `df[df["reg"] ==
  FRAME_REG]` dance in consumers.
- `preframr_tokens.constrained_decode.tail_charge_for_prompt` —
  cycle cost of real-reg writes after the last frame marker.
  Replaces the manual `is_real_reg[tail].sum() * MIN_DIFF`
  arithmetic + the matching `MIN_DIFF` import in consumers.
- `preframr_tokens.constrained_decode.frame_marker_count` —
  formerly `_frame_marker_count`; promoted (underscore alias dropped).
- `preframr_tokens.constrained_decode.StreamState.compute_invalid_mask`
  — formerly `_compute_invalid`; promoted (underscore alias dropped).
- `preframr_tokens.macros.transform.ensure_default_transforms_registered`
  — call before any `_REGISTRY` lookup to populate
  `transforms_audio_bit_exact` / `transforms_bit_exact` side effects.
  Idempotent. Replaces the duplicated import-and-cache dance.
- `preframr_tokens.corpus.TokenizeMeta` — typed snapshot of the
  tokenize-stage metadata previously carried as an untyped dict on
  `Corpus._tokenize_meta`.
- `preframr_tokens.constrained_decode.VocabArrays` — `dict` subclass
  with attribute access (`a.is_real_reg` alongside `a["is_real_reg"]`).
  Return type of `precompute_vocab_arrays` /
  `precompute_subtoken_arrays`; external dict consumers see no change.
- `preframr_tokens.macros.transform.PassBackedTransform`,
  `RowExpandingTransform` — public bases for `Transform` subclasses
  that wrap a `MacroPass` for `forward()` and (optionally) a decoder
  for `expand_atom()`. Hoisted from `transforms_bit_exact.py` so other
  transform files can reuse the pattern.
- `preframr_tokens.macros.transform_registry` (internal) — holds
  the shared pipeline-spec primitives (`_REGISTRY`, `PipelineEntry`,
  `PipelineConfigError`, `_normalize_spec`) so `transform.py` and
  `pipeline_check.py` can both depend on them without forming an
  import cycle. Consumers should keep importing from
  `preframr_tokens.macros.transform`, which re-exports.
- `preframr_tokens.utils.to_int64_arrays(df, *names, fillna={col: val})`
  — extract named columns as int64 numpy arrays with explicit per-column
  NaN fill values. Replaces 10+ ad-hoc
  `df[col].fillna(...).astype(np.int64).to_numpy()` triples.

## Stability

Library follows semver from v1.0. Pre-1.0 releases may break API as
the preframr codebase evolves. Token-alphabet shape changes bump
major version since they invalidate downstream checkpoints.

The authoritative promised surface is `preframr_tokens.__all__`
(importable from the package root), plus the `stfconstants` and
`engine_fingerprint` namespaces noted under "Importing". It groups as:

- **Classes**: `RegLogParser`, `RegTokenizer`, `Corpus`, `TokenizeMeta`,
  `StreamState`, `PendingSlot`, `VocabArrays`, `VocabSignature`,
  `Transform` (+ `register` decorator, `PipelineEntry`,
  `TransformPipeline`, `PassBackedTransform`, `RowExpandingTransform`),
  `DistancePairSpec`, and the pass classes `SlopePass`, `PresetPass`,
  `PerRegBurstPass`, `GateSlopeShiftPass`.
- **Decision helpers**: the `tier_classify` (`vocab_id_tier`,
  `build_vocab_tier_ids`, `build_vocab_tier_map`) / `token_weighting`
  (`vocab_frame_weights`) / `VocabSignature` / `read_initial_irq` /
  `reg_class` / `to_int64_arrays` family catalogued under "API surface".
- **Routines**: `parse_corpus`, `precompute_vocab_arrays`,
  `precompute_subtoken_arrays`, `prepare_df_for_audio`,
  `remove_voice_reg`, `validate_back_refs`, `validate_pattern_overlays`,
  `frame_marker_count`, `tail_charge_for_prompt`,
  `ensure_default_transforms_registered`, `get_transform_class`,
  `distance_pair_role`, `slope_subreg_role`, `frame_weight_role`,
  `classify_carveout`, `iter_voiced_blocks`, `reg_widths_path`,
  `self_contained_prompt_df`, `tier_accuracy`, `detect_tail_cycle`,
  `distinct_n`, `load_palettes_attrs`, `dump_palettes_attrs`.
- **Boundary constants**: `PAD_ID`, `MODEL_PDTYPE`, `DUMP_SUFFIX`,
  `LEGACY_EVAL_SUBSET_NAME`, `DEFAULT_IRQ_CYCLES`, `LOSS_TIER_NAMES`,
  `DISTANCE_PAIR_OPS`, `CONTENT_TIER`.

### Intentional shape (won't narrow)

- `precompute_vocab_arrays` / `precompute_subtoken_arrays` return a
  `dict` of numpy arrays (the `VocabArrays` subclass adds attribute
  access without breaking dict consumers) — fast iteration over named
  keys with no per-call wrapper ceremony.
- `RegLogParser` and `Corpus` take an `argparse.Namespace` and thread
  `args` through their methods — matches how the main repo wires them;
  a typed config object would force every consumer to translate.
- `BlockMapper` / DataLoader wrapping stays in the main repo — the
  torch-free guarantee here is load-bearing and never accepts a torch
  dependency.

### Removed back-compat aliases

All back-compat aliases have been removed. The internal aliases
(`_frame_marker_count`, `_compute_invalid`, `_LOSS_TIER_NAMES`) and the
public `MIN_DIFF` re-export went in the prior round; the `reglog_helpers`
re-export set (`dump_palettes_attrs`, `load_palettes_attrs`, `wrapbits`)
followed once the last main-repo consumer (`render_play.py`) cut over to
the source modules.

The `reglog_helpers` module itself was then dissolved (it had become a
grab-bag): the reg matchers moved to `reg_match`, `tighten_persist_dtypes`
to `utils` (beside `to_int64_arrays`), and `read_initial_irq` to
`reglogparser`. Import palette sidecar IO from `palette_io`, `wrapbits`
and dtype helpers from `utils`, reg matchers from `reg_match`, and
`read_initial_irq` from `reglogparser`.

Symbols prefixed `_` are package-internal and may change without
notice.

## License

Apache 2.0. See `LICENSE`.
