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
Upload folder using huggingface_hub
Browse filesFiles changed (2)
- README.md+28-88
- handler.py+98-9
14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112214 unmodified linespipeline_tag: text-generation---# 🧠 Noesis Decoder (AletheiaEngine)**Repository:** [gnai-creator/noesis-decoder](https://huggingface.co/gnai-creator/noesis-decoder)**Author:** Felipe M. Muniz (`gnai-creator`)**License:** Apache-2.0---## 🔍 Overview**Noesis Decoder** is the proprietary symbolic decoder of **AletheiaEngine** — a hybrid symbolic–neural system designed for *philosophical artificial general intelligence*.Unlike conventional text generators, Noesis translates **symbolic embeddings (ψₛ)** into meaningful language based on *epistemic coherence*, rather than statistical prediction.---## ⚙️ Model Architecture* **Framework:** PyTorch → ONNX Runtime* **Files:*** `model_infer.onnx` – Inference model (optimized)* `noesis.pt` – PyTorch checkpoint (training artifact)* `inference.py` – Custom ONNX handler* **Input:** float32 symbolic vector, shape `[1, D]`* **Output:** decoded float or token embeddings (depending on context)---## 🧩 Example Usage### 🔹 Python + ONNX Runtime```pythonfrom huggingface_hub import hf_hub_downloadimport onnxruntime as ortimport numpy as np# Download ONNX modelonnx_path = hf_hub_download(repo_id="gnai-creator/noesis-decoder",filename="model_infer.onnx",repo_type="model")# Load runtimesess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])input_name = sess.get_inputs()[0].nameoutput_name = sess.get_outputs()[0].name# Example symbolic vector ψₛx = np.random.randn(1, 300).astype("float32")# Run inferencey = sess.run([output_name], {input_name: x})[0]print("Output shape:", y.shape)```---## 💡 Training DataTrained on **symbolic text pairs** generated from philosophical, logical, and reflective corpora within the AletheiaEngine ecosystem.Goal: alignment between **symbolic intention (ψₛ)** and **natural language output**.---## 📊 Metrics (Indicative)| Metric | Value | Description || ------------- | ------------ | ------------------------------------------ || Cosine(Q) | 0.83 | Symbolic alignment measure || Perplexity | 2.41 | Statistical readability proxy || Latency (CPU) | ~28 ms/token | Inference on Intel Sapphire Rapids (1vCPU) |---## 🚀 DeploymentThis model is compatible with **Hugging Face Inference Endpoints** using the `Default` engine and the included `handler.py` handler.Recommended hardware:* **CPU:** Intel Sapphire Rapids (1vCPU / 2GB)* **GPU:** NVIDIA T4 for larger batch inference---## ⚠️ Limitations* Not a conventional LLM — requires symbolic vectors as input.* Outputs are contextualized to Aletheia’s symbolic reasoning pipeline.* Not suited for free-form text generation.---## 📜 LicenseThis repository is distributed under the **Apache License 2.0**.See [LICENSE](./LICENSE) for details.---> *“Truth is not imposed; it emerges from alignment.”*> — *Felipe M. Muniz (2025)*14 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616214 unmodified linespipeline_tag: text-generation---# Aletheia Noesis DecoderNoesis é o decoder proprietário da AletheiaEngine. Ele traduz estados simbólicos \(\psi_s\) em linguagem natural garantindo a coerência epistemológica medida pela **Qualidade da Verdade (Q)**. Diferente de abordagens puramente estatísticas, o Noesis prioriza a fidelidade semântica entre a intenção simbólica e o texto gerado.## Arquitetura- **Transformer Decoder** com 8 camadas e atenção cruzada condicionada por \(\psi_s\) e estados contínuos.- Entradas: vetor de intenção `psi_s`, memória lenta `state` opcional e sequência de tokens.- Saídas: `logits`, embedding semântico `z_text` e métrica \(\hat{Q}\).- Função de perda combina cross-entropy, coerência Q e penalizações de restrições.## API FastAPIO pacote inclui a aplicação `aletheia_decoder.api.app` com duas rotas:- `POST /generate`: recebe `psi_s`, `state`, `constraints`, prompts opcionais e parâmetros de decodificação. Retorna texto gerado, tokens, \(\hat{Q}\) e metadados.- `POST /train`: permite fine-tuning local a partir de um dataset JSONL.### Execução local```bashpip install -r requirements.txtuvicorn aletheia_decoder.api.app:app --host 0.0.0.0 --port 8000```## TreinamentoUse o script `aletheia_decoder/model/train.py` para treinar o modelo com dados anotados:```bashpython -m aletheia_decoder.model.train data/dataset.jsonl --epochs 200 --batch-size 4 --lr 3e-5```Os checkpoints podem ser salvos com `torch.save(model.state_dict(), "noesis.pt")` e exportados para ONNX se necessário.## Deploy no Hugging Face Spaces1. Faça fork deste diretório para um repositório separado.2. Configure o Space no modo **FastAPI** apontando para `app:app`.3. Defina as variáveis de ambiente de acordo com sua infraestrutura (ex.: `DECODER_ENDPOINT`).4. Opcionalmente publique checkpoints `.pt` e `.onnx` nos assets do Space.## Slogan> **Noesis — onde a intenção se torna linguagem.**
17 unmodified lines18192021222324252627282912 unmodified lines4243444546475 unmodified lines535455565758596061626364659 unmodified lines75767778798018 unmodified lines991001011021031041051061071081097 unmodified lines11711811912012112217 unmodified linesfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Mapping, MutableMapping, Optionalimport numpy as npimport onnxruntime as ort@dataclass(frozen=True)class _ModelIO:"""Snapshot of ONNX input and output metadata."""12 unmodified linesself.primary_input = self.io.inputs[0].nameself.slow_input = self._find_input("slow_state")self._defaults = {node.name: self._zeros_like(node)for node in self.io.inputs5 unmodified linesself._slow_fallback = Nonedef _load_session(self) -> ort.InferenceSession:model_path = self.model_dir / "model.onnx"if not model_path.exists():available = ", ".join(sorted(str(p.name) for p in self.model_dir.glob("*.onnx"))) or "<none>"raise FileNotFoundError("Could not locate 'model.onnx' in %s (available: %s)" % (self.model_dir, available))return ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])@propertydef _input_map(self) -> Mapping[str, ort.NodeArg]:9 unmodified linesreturn node.namereturn None@staticmethoddef _zeros_like(node: ort.NodeArg) -> np.ndarray:shape: list[int] = []18 unmodified linesdef _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")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._coerce_array(psi)}if self.slow_input is not None:slow_value = payload.get("slow_state") or payload.get("slow") or payload.get("state")7 unmodified linesreturn inputs@staticmethoddef _format_output(name: str, value: np.ndarray) -> Any:value = np.asarray(value, dtype=np.float32)17 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798012 unmodified lines939495969798991005 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281299 unmodified lines13914014114214314414514614714814915015115218 unmodified lines1711721731741751761771781791801811821831841851861871881897 unmodified lines19719819920020120220320420520620720820921021117 unmodified linesfrom 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."""12 unmodified linesself.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.inputs5 unmodified linesself._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]:9 unmodified linesreturn 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] = []18 unmodified linesdef _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")7 unmodified linesreturn 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)
README.md+28-88
handler.py+98-9