Text Generation
Transformers
ONNX
PyTorch
English
symbolic-decoder
aletheia
philosophical-agi
gnai-creator
Run this model with HF Jobs
Run gnai-creator/noesis-decoder on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/gnai-creator/noesis-decoder. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/gnai-creator/noesis-decoder on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/gnai-creator/noesis-decoder. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/gnai-creator/noesis-decoder. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use gnai-creator/noesis-decoder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use gnai-creator/noesis-decoder with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="gnai-creator/noesis-decoder")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("gnai-creator/noesis-decoder", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use gnai-creator/noesis-decoder with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "gnai-creator/noesis-decoder" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "gnai-creator/noesis-decoder", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/gnai-creator/noesis-decoder
- SGLang
How to use gnai-creator/noesis-decoder with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "gnai-creator/noesis-decoder" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "gnai-creator/noesis-decoder", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "gnai-creator/noesis-decoder" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "gnai-creator/noesis-decoder", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use gnai-creator/noesis-decoder with Docker Model Runner:
docker model run hf.co/gnai-creator/noesis-decoder
Update handler.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233"""Custom inference handler for Hugging Face Inference Endpoints.This module exposes :class:`EndpointHandler`, the entrypoint used by theHugging Face serving stack when ``--task custom`` is selected. The handlerloads the exported Noesis decoder ONNX graph and accepts symbolic intentvectors (``psi``) along with an optional ``slow_state`` memory tensor. Theoutputs mirror the values produced by the training runtime:* ``z_out`` – semantic embedding projected back into symbolic space.* ``choice``, ``pain``, ``memory`` and ``quality`` – diagnostic scalars.* ``slow_state`` – updated slow memory tensor suitable for recurrent usage.The handler is intentionally lightweight so it can run without the rest of theAletheiaEngine Python package being installed."""from __future__ import annotationsfrom dataclasses import dataclassfrom pathlib import Pathimport refrom typing import Any, Mapping, MutableMapping, Optionalimport numpy as npimport onnxruntime as ort_WORD_RE = re.compile(r"\w+", re.UNICODE)class _TextEncoder:"""Deterministic text → vector encoder.The Hugging Face Inference Endpoints frequently pass user prompts asstrings via the ``inputs`` field. The Noesis decoder, however, expects asymbolic vector (``psi``) as input. To provide a graceful fallback thehandler lazily converts short text prompts into a stable float32 vector byhashing tokens onto a hypersphere. This mirrors the lightweight``TextEncoder256`` implementation bundled with the full AletheiaEnginepackage while avoiding a heavy import dependency inside the endpointcontainer."""def __init__(self, dim: int) -> None:self.dim = dim@staticmethoddef _tokens(text: str) -> list[str]:return [tok.lower() for tok in _WORD_RE.findall(text)]@staticmethoddef _seed(tok: str) -> int:# FNV-1a hash for determinism across processes/platforms.value = 2166136261for byte in tok.encode("utf-8"):value ^= bytevalue = (value * 16777619) & 0xFFFFFFFFreturn int(value)def encode(self, text: str) -> np.ndarray:tokens = self._tokens(text)if not tokens:return np.zeros((1, self.dim), dtype=np.float32)vecs = []for tok in tokens:rs = np.random.RandomState(self._seed(tok))embedding = rs.normal(0.0, 1.0, size=(self.dim,)).astype(np.float32)norm = float(np.linalg.norm(embedding)) or 1.0vecs.append(embedding / norm)stacked = np.stack(vecs, axis=0)pooled = stacked.mean(axis=0, dtype=np.float32, keepdims=True)pooled_norm = float(np.linalg.norm(pooled)) or 1.0return pooled / pooled_norm@dataclass(frozen=True)class _ModelIO:"""Snapshot of ONNX input and output metadata."""inputs: tuple[ort.NodeArg, ...]outputs: tuple[ort.NodeArg, ...]class EndpointHandler:"""Callable endpoint used by Hugging Face to drive inference."""def __init__(self, path: str | None = None) -> None:self.model_dir = Path(path or Path(__file__).parent)self.session = self._load_session()self.io = self._capture_io()self.primary_input = self.io.inputs[0].nameself.slow_input = self._find_input("slow_state")self._primary_dim = self._infer_primary_dim()self._text_encoder = _TextEncoder(self._primary_dim)self._defaults = {node.name: self._zeros_like(node)for node in self.io.inputsif node.name not in {self.primary_input, self.slow_input}}if self.slow_input is not None:self._slow_fallback = self._zeros_like(self._input_map[self.slow_input])else:self._slow_fallback = Nonedef _load_session(self) -> ort.InferenceSession:"""Load the ONNX session, tolerating alternate filenames."""preferred_names = ("model.onnx", "model_infer.onnx")for name in preferred_names:candidate = self.model_dir / nameif candidate.exists():return ort.InferenceSession(str(candidate), providers=["CPUExecutionProvider"])available = sorted(str(p.name) for p in self.model_dir.glob("*.onnx"))if len(available) == 1:# Fall back to the lone ONNX artefact if it has a non-standard name.return ort.InferenceSession(str(self.model_dir / available[0]), providers=["CPUExecutionProvider"])choices = ", ".join(available) or "<none>"raise FileNotFoundError("Could not locate any of %s in %s (available: %s)"% (", ".join(preferred_names), self.model_dir, choices))@propertydef _input_map(self) -> Mapping[str, ort.NodeArg]:return {node.name: node for node in self.io.inputs}def _capture_io(self) -> _ModelIO:return _ModelIO(inputs=tuple(self.session.get_inputs()), outputs=tuple(self.session.get_outputs()))def _find_input(self, target: str) -> Optional[str]:target = target.lower()for node in self.io.inputs:if node.name.lower() == target:return node.namereturn Nonedef _infer_primary_dim(self) -> int:node = self._input_map[self.primary_input]for dim in reversed(node.shape):if isinstance(dim, int) and dim > 0:return dim# Conservative default matching TextEncoder256.return 256@staticmethoddef _zeros_like(node: ort.NodeArg) -> np.ndarray:shape: list[int] = []for dim in node.shape:if isinstance(dim, int) and dim > 0:shape.append(dim)else:shape.append(1)return np.zeros(shape, dtype=np.float32)@staticmethoddef _coerce_array(value: Any, *, allow_empty: bool = False) -> np.ndarray:array = np.asarray(value, dtype=np.float32)if array.size == 0 and not allow_empty:raise ValueError("Received an empty array; provide at least one value.")if array.ndim == 1:array = np.expand_dims(array, axis=0)elif array.ndim > 2:raise ValueError("Expected a 1D or batched 2D array; received shape %s" % (array.shape,))return arraydef _prepare_inputs(self, payload: Mapping[str, Any]) -> MutableMapping[str, np.ndarray]:psi = payload.get("psi")if psi is None:psi = (payload.get("vector")or payload.get("psi_s")or payload.get("inputs")or payload.get("prompt")or payload.get("text"))if psi is None:raise KeyError("Payload must include a 'psi' field containing the symbolic vector.")inputs: MutableMapping[str, np.ndarray] = {self.primary_input: self._vector_from_payload(psi)}if self.slow_input is not None:slow_value = payload.get("slow_state") or payload.get("slow") or payload.get("state")if slow_value is None:inputs[self.slow_input] = self._slow_fallback.copy()else:inputs[self.slow_input] = self._coerce_array(slow_value, allow_empty=True)for name, default in self._defaults.items():inputs[name] = default.copy()return inputsdef _vector_from_payload(self, value: Any) -> np.ndarray:if isinstance(value, str):return self._text_encoder.encode(value)if isinstance(value, (list, tuple)) and value and all(isinstance(v, str) for v in value):return self._text_encoder.encode(" ".join(value))return self._coerce_array(value)@staticmethoddef _format_output(name: str, value: np.ndarray) -> Any:value = np.asarray(value, dtype=np.float32)value = np.nan_to_num(value, nan=0.0, posinf=0.0, neginf=0.0)squeezed = np.squeeze(value)if squeezed.ndim == 0:return float(squeezed)return squeezed.tolist()def __call__(self, data: Mapping[str, Any]) -> Mapping[str, Any]:payload = data.get("inputs", data)if not isinstance(payload, Mapping):payload = {"psi": payload}feed = self._prepare_inputs(payload)outputs = self.session.run(None, feed)result = {node.name: self._format_output(node.name, value)for node, value in zip(self.io.outputs, outputs)}return result__all__ = ["EndpointHandler"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274"""Custom inference handler for Hugging Face Inference Endpoints.This module exposes :class:`EndpointHandler`, the entrypoint used by theHugging Face serving stack when ``--task custom`` is selected. The handlerloads the exported Noesis decoder ONNX graph and accepts symbolic intentvectors (``psi``) along with an optional ``slow_state`` memory tensor. Theoutputs mirror the values produced by the training runtime:* ``z_out`` – semantic embedding projected back into symbolic space.* ``choice``, ``pain``, ``memory`` and ``quality`` – diagnostic scalars.* ``slow_state`` – updated slow memory tensor suitable for recurrent usage.The handler is intentionally lightweight so it can run without the rest of theAletheiaEngine Python package being installed."""from __future__ import annotationsimport importlibimport importlib.utilfrom dataclasses import dataclassfrom pathlib import Pathimport refrom typing import Any, Mapping, MutableMapping, Optionalimport numpy as np_WORD_RE = re.compile(r"\w+", re.UNICODE)class _TextEncoder:"""Deterministic text → vector encoder.The Hugging Face Inference Endpoints frequently pass user prompts asstrings via the ``inputs`` field. The Noesis decoder, however, expects asymbolic vector (``psi``) as input. To provide a graceful fallback thehandler lazily converts short text prompts into a stable float32 vector byhashing tokens onto a hypersphere. This mirrors the lightweight``TextEncoder256`` implementation bundled with the full AletheiaEnginepackage while avoiding a heavy import dependency inside the endpointcontainer."""def __init__(self, dim: int) -> None:self.dim = dim@staticmethoddef _tokens(text: str) -> list[str]:return [tok.lower() for tok in _WORD_RE.findall(text)]@staticmethoddef _seed(tok: str) -> int:# FNV-1a hash for determinism across processes/platforms.value = 2166136261for byte in tok.encode("utf-8"):value ^= bytevalue = (value * 16777619) & 0xFFFFFFFFreturn int(value)def encode(self, text: str) -> np.ndarray:tokens = self._tokens(text)if not tokens:return np.zeros((1, self.dim), dtype=np.float32)vecs = []for tok in tokens:rs = np.random.RandomState(self._seed(tok))embedding = rs.normal(0.0, 1.0, size=(self.dim,)).astype(np.float32)norm = float(np.linalg.norm(embedding)) or 1.0vecs.append(embedding / norm)stacked = np.stack(vecs, axis=0)pooled = stacked.mean(axis=0, dtype=np.float32, keepdims=True)pooled_norm = float(np.linalg.norm(pooled)) or 1.0return pooled / pooled_norm@dataclass(frozen=True)class _ModelIO:"""Snapshot of ONNX input and output metadata."""inputs: tuple[Any, ...]outputs: tuple[Any, ...]class EndpointHandler:"""Callable endpoint used by Hugging Face to drive inference."""def __init__(self, path: str | None = None) -> None:self.model_dir = Path(path or Path(__file__).parent)self.session = self._load_session()self.io = self._capture_io()self.primary_input = self.io.inputs[0].nameself.slow_input = self._find_input("slow_state")self._primary_dim = self._infer_primary_dim()self._text_encoder = _TextEncoder(self._primary_dim)self._defaults = {}for node in self.io.inputs:if node.name in {self.primary_input, self.slow_input}:continueself._defaults[node.name] = self._zeros_like(node)if self.slow_input is not None:self._slow_fallback = self._zeros_like(self._input_map[self.slow_input])else:self._slow_fallback = Nonedef _load_session(self):"""Load the ONNX session, tolerating alternate filenames."""ort = self._import_onnxruntime()preferred_names = ("model.onnx", "model_infer.onnx")for name in preferred_names:candidate = self.model_dir / nameif candidate.exists():return ort.InferenceSession(str(candidate), providers=["CPUExecutionProvider"])available = sorted(str(p.name) for p in self.model_dir.glob("*.onnx"))if len(available) == 1:# Fall back to the lone ONNX artefact if it has a non-standard name.return ort.InferenceSession(str(self.model_dir / available[0]), providers=["CPUExecutionProvider"])choices = ", ".join(available) or "<none>"raise FileNotFoundError("Could not locate any of %s in %s (available: %s)"% (", ".join(preferred_names), self.model_dir, choices))@staticmethoddef _import_onnxruntime():"""Import :mod:`onnxruntime`, providing a helpful error if unavailable."""spec = importlib.util.find_spec("onnxruntime")if spec is None:raise ModuleNotFoundError("onnxruntime is required to load Noesis decoder ONNX graphs. ""Install it with 'pip install onnxruntime'.")return importlib.import_module("onnxruntime")@propertydef _input_map(self) -> Mapping[str, Any]:return {node.name: node for node in self.io.inputs}def _capture_io(self) -> _ModelIO:return _ModelIO(inputs=tuple(self.session.get_inputs()), outputs=tuple(self.session.get_outputs()))def _find_input(self, target: str) -> Optional[str]:target = target.lower()for node in self.io.inputs:if node.name.lower() == target:return node.namereturn Nonedef _infer_primary_dim(self) -> int:node = self._input_map[self.primary_input]for dim in reversed(node.shape):if isinstance(dim, int) and dim > 0:return dim# Conservative default matching TextEncoder256.return 256@staticmethoddef _onnx_type_to_numpy(type_str: str | None) -> np.dtype:mapping = {"tensor(float)": np.float32,"tensor(float16)": np.float16,"tensor(double)": np.float64,"tensor(int64)": np.int64,"tensor(int32)": np.int32,"tensor(int16)": np.int16,"tensor(int8)": np.int8,"tensor(uint8)": np.uint8,"tensor(bool)": np.bool_,}return mapping.get(type_str, np.float32)def _dtype_for(self, node: Any) -> np.dtype:return self._onnx_type_to_numpy(getattr(node, "type", None))def _zeros_like(self, node: Any) -> np.ndarray:shape: list[int] = []for dim in node.shape:if isinstance(dim, int) and dim > 0:shape.append(dim)else:shape.append(1)dtype = self._dtype_for(node)return np.zeros(shape, dtype=dtype)def _coerce_array(self, value: Any, *, node: Any, allow_empty: bool = False) -> np.ndarray:dtype = self._dtype_for(node)array = np.asarray(value, dtype=dtype)if array.size == 0 and not allow_empty:raise ValueError("Received an empty array; provide at least one value.")if array.ndim == 1:array = np.expand_dims(array, axis=0)elif array.ndim > 2:raise ValueError("Expected a 1D or batched 2D array; received shape %s" % (array.shape,))if array.dtype != dtype:array = array.astype(dtype, copy=False)return arraydef _prepare_inputs(self, payload: Mapping[str, Any]) -> MutableMapping[str, np.ndarray]:psi = payload.get("psi")if psi is None:psi = (payload.get("vector")or payload.get("psi_s")or payload.get("inputs")or payload.get("prompt")or payload.get("text"))if psi is None:raise KeyError("Payload must include a 'psi' field containing the symbolic vector.")primary_node = self._input_map[self.primary_input]inputs: MutableMapping[str, np.ndarray] = {self.primary_input: self._vector_from_payload(psi, node=primary_node)}if self.slow_input is not None:slow_value = payload.get("slow_state") or payload.get("slow") or payload.get("state")if slow_value is None:inputs[self.slow_input] = self._slow_fallback.copy()else:inputs[self.slow_input] = self._coerce_array(slow_value,node=self._input_map[self.slow_input],allow_empty=True,)for name, default in self._defaults.items():inputs[name] = default.copy()return inputsdef _vector_from_payload(self, value: Any, *, node: Any) -> np.ndarray:if isinstance(value, str):encoded = self._text_encoder.encode(value)return self._coerce_array(encoded, node=node)if isinstance(value, (list, tuple)) and value and all(isinstance(v, str) for v in value):encoded = self._text_encoder.encode(" ".join(value))return self._coerce_array(encoded, node=node)return self._coerce_array(value, node=node)@staticmethoddef _format_output(name: str, value: np.ndarray) -> Any:value = np.asarray(value, dtype=np.float32)value = np.nan_to_num(value, nan=0.0, posinf=0.0, neginf=0.0)squeezed = np.squeeze(value)if squeezed.ndim == 0:return float(squeezed)return squeezed.tolist()def __call__(self, data: Mapping[str, Any]) -> Mapping[str, Any]:payload = data.get("inputs", data)if not isinstance(payload, Mapping):payload = {"psi": payload}feed = self._prepare_inputs(payload)outputs = self.session.run(None, feed)result = {node.name: self._format_output(node.name, value)for node, value in zip(self.io.outputs, outputs)}return result__all__ = ["EndpointHandler"]
handler.py+274-233