Run this model with HF Jobs
Run CladeTeam/CENO-base-1b-preview 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/CladeTeam/CENO-base-1b-preview. 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/CladeTeam/CENO-base-1b-preview 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/CladeTeam/CENO-base-1b-preview. 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/CladeTeam/CENO-base-1b-preview. 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 CladeTeam/CENO-base-1b-preview with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use CladeTeam/CENO-base-1b-preview with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="CladeTeam/CENO-base-1b-preview")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("CladeTeam/CENO-base-1b-preview", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use CladeTeam/CENO-base-1b-preview with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "CladeTeam/CENO-base-1b-preview" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CladeTeam/CENO-base-1b-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/CladeTeam/CENO-base-1b-preview
- SGLang
How to use CladeTeam/CENO-base-1b-preview 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 "CladeTeam/CENO-base-1b-preview" \ --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": "CladeTeam/CENO-base-1b-preview", "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 "CladeTeam/CENO-base-1b-preview" \ --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": "CladeTeam/CENO-base-1b-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use CladeTeam/CENO-base-1b-preview with Docker Model Runner:
docker model run hf.co/CladeTeam/CENO-base-1b-preview
Scope CENO reference GEMM flags to forward; faster bit-identical decode (CladeTeam/CENO 240b1b3)
Browse filesFiles changed (3)
85 unmodified lines868788899091929394959685 unmodified linesnum_logits_to_keep (`int` or `None`, *optional*, defaults to 1):Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If aninteger value, only last `num_logits_to_keep` logits will be calculated.pad_token_id (`int`, *optional*, defaults to 0):The id of the padding token.bos_token_id (`int`, *optional*, defaults to 1):The id of the "beginning-of-sequence" token.eos_token_id (`int`, *optional*, defaults to 2):The id of the "end-of-sequence" token.sliding_window (`int`, *optional*, defaults to None):Sliding window attention window size.85 unmodified lines868788899091929394959685 unmodified linesnum_logits_to_keep (`int` or `None`, *optional*, defaults to 1):Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If aninteger value, only last `num_logits_to_keep` logits will be calculated.pad_token_id (`int`, *optional*, defaults to 1):The id of the padding token.bos_token_id (`int`, *optional*, defaults to 0):The id of the "beginning-of-sequence" token.eos_token_id (`int`, *optional*, defaults to 0):The id of the "end-of-sequence" token.sliding_window (`int`, *optional*, defaults to None):Sliding window attention window size.
16 unmodified lines17181920212253 unmodified lines7677787980811558 unmodified lines164016411642164316441645225 unmodified lines187118721873187418751876187787 unmodified lines19651966196719681969197016 unmodified lines"""PyTorch CENO model."""import contextlibimport mathfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union53 unmodified linesname = f"{__package__}.training_precision" if __package__ else "training_precision"return importlib.import_module(name)logger = logging.get_logger(__name__)1558 unmodified linesdef set_input_embeddings(self, new_embeddings):self.embeddings = new_embeddings@add_start_docstrings_to_model_forward(CENO_INPUTS_DOCSTRING)@add_code_sample_docstrings(checkpoint=_CHECKPOINT_FOR_DOC,225 unmodified linesmodel = result[0] if isinstance(result, tuple) else resultmodel._ceno_preserve_attention_backend = preserveif getattr(model.config, "ceno_training_precision", False) and not preserve:_precision_module().configure_backend()return resultdef __init__(self, config):87 unmodified lines)return model_inputs@add_start_docstrings_to_model_forward(CENO_INPUTS_DOCSTRING)@add_code_sample_docstrings(checkpoint=_CHECKPOINT_FOR_DOC,16 unmodified lines1718192021222353 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151558 unmodified lines1674167516761677167816791680225 unmodified lines190619071908190919101911191219131914191587 unmodified lines200320042005200620072008200916 unmodified lines"""PyTorch CENO model."""import contextlibimport functoolsimport mathfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union53 unmodified linesname = f"{__package__}.training_precision" if __package__ else "training_precision"return importlib.import_module(name)def _mark_backend_scope(model):"""Run this model's forward (and its backbone's) under the reference GEMM flags."""for module in model.modules():if isinstance(module, (CENOModel, CENOForCausalLM)):module._ceno_backend_scope = Truedef _wants_lazy_precision(model, kwargs):# Mirrors the lazy enable condition in CENOForCausalLM.forward.config = model.configreturn (getattr(config, "ceno_training_precision", False)and not model.training and not torch.is_grad_enabled()and not (kwargs.get("output_attentions") or config.output_attentions)and not getattr(model, "_ceno_preserve_attention_backend", False)and model.device.type == "cuda" and model.dtype == torch.bfloat16)def _with_backend_scope(forward):"""Scope backend flags to the forward instead of changing them process-wide."""@functools.wraps(forward)def wrapper(self, *args, **kwargs):if (not getattr(self, "_ceno_backend_scope", False)and isinstance(self, CENOForCausalLM)and _wants_lazy_precision(self, kwargs)):_precision_module().configure_backend()_mark_backend_scope(self)if getattr(self, "_ceno_backend_scope", False):with _precision_module().backend_scope():return forward(self, *args, **kwargs)return forward(self, *args, **kwargs)return wrapperlogger = logging.get_logger(__name__)1558 unmodified linesdef set_input_embeddings(self, new_embeddings):self.embeddings = new_embeddings@_with_backend_scope@add_start_docstrings_to_model_forward(CENO_INPUTS_DOCSTRING)@add_code_sample_docstrings(checkpoint=_CHECKPOINT_FOR_DOC,225 unmodified linesmodel = result[0] if isinstance(result, tuple) else resultmodel._ceno_preserve_attention_backend = preserveif getattr(model.config, "ceno_training_precision", False) and not preserve:# Only the cuBLAS workspace env is process-level; torch GEMM flags# are applied inside this model's forward (see _with_backend_scope)._precision_module().configure_backend()_mark_backend_scope(model)return resultdef __init__(self, config):87 unmodified lines)return model_inputs@_with_backend_scope@add_start_docstrings_to_model_forward(CENO_INPUTS_DOCSTRING)@add_code_sample_docstrings(checkpoint=_CHECKPOINT_FOR_DOC,
4 unmodified lines56789108 unmodified lines1920212223242526272829303132333429 unmodified lines6465666768692 unmodified lines72737475767722 unmodified lines1001011021031041051064 unmodified lines1111121131141151161 unmodified line1181191201211221231241251261271281291301311321331341351361371381396 unmodified lines14614714814915015115215351 unmodified lines20520620720820921021127 unmodified lines2392402412422432441 unmodified line2462472482492502512524 unmodified linessingle-GPU, BF16, unpadded uniform-length batches. Its prefill token budget isbounded to avoid the old Mamba kernels' large-stride indexing paths."""import contextvarsimport functoolsimport os8 unmodified linesdef configure_backend():"""Call before CUDA matrix multiplication; settings apply to this process."""os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8"os.environ["CUBLASLT_WORKSPACE_SIZE"] = "1"import torchtorch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = Falsetorch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = Falsetorch.backends.cuda.matmul.allow_tf32 = Falsetorch.backends.cudnn.allow_tf32 = Falseif torch.version.cuda is not None:torch.backends.cuda.preferred_blas_library("cublaslt")def _pin_scan():29 unmodified linesfor key in ("initial", "x", "dt", "B", "C", "z"):value = state[key]state[key] = value.index_select(0, beam_idx.to(value.device))return resultcache.reorder_cache = reorder2 unmodified linesdef _install_scan_hooks(module):"""Namespace hooks are inactive unless a precision-enabled mixer sets context."""import torchif hasattr(module, "_ceno_scan_context"):return module._ceno_scan_context22 unmodified lines*args, **prefix_kwargs)[1]else:initial = torch.zeros_like(result[1])state = {"initial": initial, "pos": count}values = {"x": x, "dt": dt, "B": B, "C": C, "z": z}for key, value in values.items():buffer = torch.zeros((batch, _CHUNK, *value.shape[2:]),4 unmodified lines_cache_buffers(cache)[mixer.layer_idx] = statereturn resultdef update_from_chunk(state_tensor, x, dt, A, B, C, D, *args, **kwargs):active = context.get()if active is None:1 unmodified linemixer, cache = activestate = _cache_buffers(cache)[mixer.layer_idx]pos = state["pos"]update(state_tensor, x, dt, A, B, C, D, *args, **kwargs)for key, value in (("x", x), ("dt", dt[:, :, 0]), ("B", B), ("C", C),("z", kwargs["z"])):if pos == 0:state[key].zero_()state[key][:, pos].copy_(value)y, final = scan(state["x"], state["dt"], -torch.exp(mixer.A_log.float()),state["B"], state["C"], chunk_size=_CHUNK, D=mixer.D,z=state["z"], dt_bias=mixer.dt_bias, dt_softplus=True,dt_limit=mixer.time_step_limit, initial_states=state["initial"],return_final_states=True)if pos == _CHUNK - 1:state["initial"].copy_(final)state_tensor.copy_(final)state["pos"] = (pos + 1) % _CHUNKreturn y[:, pos]module.mamba_chunk_scan_combined = scan_with_cachemodule.selective_state_update = update_from_chunk6 unmodified linesimport torchfrom flash_attn.flash_attn_interface import _flash_attn_varlen_forwardq, k, v = q.contiguous(), k.contiguous(), v.contiguous()cuq = torch.tensor([0, len(q)], device=q.device, dtype=torch.int32)cuk = torch.tensor([0, len(k)], device=q.device, dtype=torch.int32)result = _flash_attn_varlen_forward(q, k, v, cuq, cuk, len(q), len(k), dropout_p=0., softmax_scale=q.shape[-1] ** -.5,causal=causal, window_size_left=-1, window_size_right=0 if causal else -1,51 unmodified linesconfigure_backend()import sysimport torchte_rms_norm = _local_module("ceno_norm").te_rms_normconfig = model.configmodeling = sys.modules[type(model).__module__]27 unmodified linesraise ValueError("HF precision requires single-GPU BF16 and the CUDA Mamba/FA2 environment")if any(p.device != model.device for p in model.parameters()):raise ValueError("HF training precision requires one CUDA device")config.ceno_mamba_gate_in_ssm = Trueconfig.ceno_rmsnorm_mode = norm_modeconfig.ceno_reference_cp_size = reference_cp_size1 unmodified line_pin_scan()context = _install_scan_hooks(modeling)def norm(self, x):return te_rms_norm(x, self.weight, self.variance_epsilon, norm_mode)def softmax(x, dim=-1):exp = torch.exp(x - torch.amax(x, dim=dim, keepdim=True))4 unmodified lines5678910118 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585960616229 unmodified lines929394959697982 unmodified lines10110210310410510610722 unmodified lines1301311321331341351364 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062076 unmodified lines21421521621721821922022122222351 unmodified lines27527627727827928028128227 unmodified lines3103113123133143153163173183191 unmodified line3213223233243253263273283294 unmodified linessingle-GPU, BF16, unpadded uniform-length batches. Its prefill token budget isbounded to avoid the old Mamba kernels' large-stride indexing paths."""import contextlibimport contextvarsimport functoolsimport os8 unmodified linesdef configure_backend():"""Set the cuBLAS workspace environment; call before the first CUDA GEMM.These two variables are read once when cuBLAS handles are created, so theystay process-level. The torch backend flags used by the referencearithmetic are no longer changed globally: precision-enabled CENO modulesenter ``backend_scope()`` for the duration of their forward only, so thesurrounding program (e.g. an FP32 head trained with TF32) keeps its ownsettings."""os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8"os.environ["CUBLASLT_WORKSPACE_SIZE"] = "1"@contextlib.contextmanagerdef backend_scope():"""Apply the reference GEMM flags inside the block and restore them on exit."""import torchmatmul, cudnn = torch.backends.cuda.matmul, torch.backends.cudnnhas_cuda = torch.version.cuda is not Nonesaved = (matmul.allow_bf16_reduced_precision_reduction,matmul.allow_fp16_reduced_precision_reduction,matmul.allow_tf32, cudnn.allow_tf32,torch.backends.cuda.preferred_blas_library() if has_cuda else None)matmul.allow_bf16_reduced_precision_reduction = Falsematmul.allow_fp16_reduced_precision_reduction = Falsematmul.allow_tf32 = Falsecudnn.allow_tf32 = Falseif has_cuda:torch.backends.cuda.preferred_blas_library("cublaslt")try:yieldfinally:(matmul.allow_bf16_reduced_precision_reduction,matmul.allow_fp16_reduced_precision_reduction,matmul.allow_tf32, cudnn.allow_tf32) = saved[:4]if has_cuda:torch.backends.cuda.preferred_blas_library(saved[4])def _pin_scan():29 unmodified linesfor key in ("initial", "x", "dt", "B", "C", "z"):value = state[key]state[key] = value.index_select(0, beam_idx.to(value.device))state["states_in"] = None # derived from "initial"; rebuild lazilyreturn resultcache.reorder_cache = reorder2 unmodified linesdef _install_scan_hooks(module):"""Namespace hooks are inactive unless a precision-enabled mixer sets context."""import importlibimport torchif hasattr(module, "_ceno_scan_context"):return module._ceno_scan_context22 unmodified lines*args, **prefix_kwargs)[1]else:initial = torch.zeros_like(result[1])state = {"initial": initial, "pos": count, "states_in": None}values = {"x": x, "dt": dt, "B": B, "C": C, "z": z}for key, value in values.items():buffer = torch.zeros((batch, _CHUNK, *value.shape[2:]),4 unmodified lines_cache_buffers(cache)[mixer.layer_idx] = statereturn result# The combined scan's own building blocks. Off the chunk boundary only the# output row is needed, so chunk_state/state_passing (which only produce the# final state) are skipped; the remaining calls receive exactly the inputs the# combined forward would pass them, so the row is bit-identical.parts = importlib.import_module(scan.__module__)fast = all(hasattr(parts, name) for name in("_chunk_cumsum_fwd", "_bmm_chunk_fwd", "_chunk_scan_fwd", "_state_passing_fwd"))def chunk_row(mixer, state, pos):if state.get("states_in") is None:# Entering-chunk state exactly as _state_passing_fwd emits it for chunk 0# (FP32 initial stored in C's dtype).initial = state["initial"]batch, heads, dim, dstate = initial.shapeflat = initial.reshape(batch, heads, dim * dstate)out, _ = parts._state_passing_fwd(torch.zeros((batch, 1, heads, dim * dstate), device=flat.device, dtype=torch.float32),torch.zeros((batch, heads, 1), device=flat.device, dtype=torch.float32),initial_states=flat, chunk_size=_CHUNK, out_dtype=state["C"].dtype)state["states_in"] = out.view(batch, 1, heads, dim, dstate)dA_cumsum, dt = parts._chunk_cumsum_fwd(state["dt"], state["A"], _CHUNK, dt_bias=mixer.dt_bias, dt_softplus=True,dt_limit=mixer.time_step_limit)CB = parts._bmm_chunk_fwd(state["C"], state["B"], _CHUNK, seq_idx=None,output_dtype=torch.float32)D = mixer.D if mixer.D.stride(-1) == 1 else mixer.D.contiguous()out, _ = parts._chunk_scan_fwd(CB, state["x"], dt, dA_cumsum, state["C"],state["states_in"], D=D, z=state["z"], seq_idx=None)return out[:, pos]def update_from_chunk(state_tensor, x, dt, A, B, C, D, *args, **kwargs):active = context.get()if active is None:1 unmodified linemixer, cache = activestate = _cache_buffers(cache)[mixer.layer_idx]pos = state["pos"]# The recurrent update's output was never used and state_tensor is only# read back at the chunk boundary below, so it is not run per token.for key, value in (("x", x), ("dt", dt[:, :, 0]), ("B", B), ("C", C),("z", kwargs["z"])):if pos == 0:state[key].zero_()state[key][:, pos].copy_(value)if "A" not in state:state["A"] = -torch.exp(mixer.A_log.float())if pos == _CHUNK - 1 or not fast:y, final = scan(state["x"], state["dt"], state["A"],state["B"], state["C"], chunk_size=_CHUNK, D=mixer.D,z=state["z"], dt_bias=mixer.dt_bias, dt_softplus=True,dt_limit=mixer.time_step_limit, initial_states=state["initial"],return_final_states=True)y = y[:, pos]else:y = chunk_row(mixer, state, pos)if pos == _CHUNK - 1:state["initial"].copy_(final)state_tensor.copy_(final)state["states_in"] = Nonestate["pos"] = (pos + 1) % _CHUNKreturn ymodule.mamba_chunk_scan_combined = scan_with_cachemodule.selective_state_update = update_from_chunk6 unmodified linesimport torchfrom flash_attn.flash_attn_interface import _flash_attn_varlen_forwardq, k, v = q.contiguous(), k.contiguous(), v.contiguous()# Build [0, n] on the device: torch.tensor(..., device=cuda) copies from# pageable host memory and synchronizes the stream on every call.steps = torch.arange(2, device=q.device, dtype=torch.int32)cuq, cuk = steps * len(q), steps * len(k)result = _flash_attn_varlen_forward(q, k, v, cuq, cuk, len(q), len(k), dropout_p=0., softmax_scale=q.shape[-1] ** -.5,causal=causal, window_size_left=-1, window_size_right=0 if causal else -1,51 unmodified linesconfigure_backend()import sysimport torchnorm_module = _local_module("ceno_norm")te_rms_norm, te_rms_norm_eager = norm_module.te_rms_norm, norm_module._te_rms_norm_implconfig = model.configmodeling = sys.modules[type(model).__module__]27 unmodified linesraise ValueError("HF precision requires single-GPU BF16 and the CUDA Mamba/FA2 environment")if any(p.device != model.device for p in model.parameters()):raise ValueError("HF training precision requires one CUDA device")mark = getattr(modeling, "_mark_backend_scope", None)if mark is None:raise ValueError("HF precision requires a modeling file with scoped backend flags")mark(model)config.ceno_mamba_gate_in_ssm = Trueconfig.ceno_rmsnorm_mode = norm_modeconfig.ceno_reference_cp_size = reference_cp_size1 unmodified line_pin_scan()context = _install_scan_hooks(modeling)def norm(self, x):# Same Triton kernel; the registered op is only needed under torch.compile.op = te_rms_norm if torch.compiler.is_compiling() else te_rms_norm_eagerreturn op(x, self.weight, self.variance_epsilon, norm_mode)def softmax(x, dim=-1):exp = torch.exp(x - torch.amax(x, dim=dim, keepdim=True))
configuration_ceno.py+3-3
modeling_ceno.py+39
training_precision.py+95-18