Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion src/nemo_safe_synthesizer/cli/wandb_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Protocol

import wandb
from pydantic import AliasChoices, Field, field_validator
Expand Down Expand Up @@ -263,3 +263,40 @@ def initialize_wandb_run(
logger.info(f"Wandb run id: {wandb.run.id if wandb.run else 'None'}")
if settings.wandb_mode != WandbMode.DISABLED:
logger.info(f"Wandb run url: {wandb.run.url if wandb.run else 'None'}")


class WandbLoggable(Protocol):
"""Structural type for observability events that can be logged to wandb.

Any event exposing ``to_wandb_payload(prefix) -> dict`` satisfies this --
e.g. ``TrainingObservability`` and the generation-side
``GenerationObservability``. Using a Protocol keeps :func:`log_observability_event`
decoupled from the concrete event types (no import of the training/generation
subpackages from this CLI module).
"""

def to_wandb_payload(self, prefix: str = "") -> dict[str, Any]:
"""Return wandb metrics for this event, namespaced under ``prefix``."""


def log_observability_event(event: WandbLoggable, prefix: str) -> None:
"""Log an observability event to the currently active wandb run.

Generic sink shared by the training and generation observability paths.
No-op when no wandb run is active (``WANDB_MODE=disabled`` or the pipeline
hasn't called :func:`initialize_wandb_run`). Errors during ``wandb.log`` are
swallowed at warning level -- observability is best-effort and a wandb
failure must not break the run.

Args:
event: Any object exposing ``to_wandb_payload(prefix) -> dict`` (see
:class:`WandbLoggable`).
prefix: wandb key namespace for this event's metrics (e.g. ``"training"``
or ``"vllm_gen"``).
"""
if wandb.run is None:
return
try:
wandb.log(event.to_wandb_payload(prefix=prefix))
except Exception as exc: # noqa: BLE001 -- degraded mode
logger.warning(f"failed to log observability event ({prefix!r}) to wandb: {exc}")
96 changes: 92 additions & 4 deletions src/nemo_safe_synthesizer/generation/vllm_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from __future__ import annotations

import contextlib
import logging
import os
import tempfile
Expand All @@ -24,6 +25,7 @@

from .. import utils
from ..cli.artifact_structure import Workdir
from ..cli.wandb_setup import log_observability_event
from ..config import SafeSynthesizerParameters
from ..config.generate import (
resolve_structured_generation_schema_method,
Expand All @@ -36,6 +38,13 @@
from ..generation.processors import Processor, TabularDataProcessor, create_processor
from ..generation.regex_manager import build_json_based_regex, build_json_structural_tag
from ..generation.results import GenerateJobResults, GenerationBatches, GenerationStatus
from ..generation.vllm_observability import (
GenerationObservability,
NvmlPeakSampler,
probe_engine_runtime_config,
read_loadavg,
read_vllm_runtime_metrics,
)
from ..llm.metadata import ModelMetadata
from ..llm.utils import ModelRef, cleanup_memory, get_max_vram
from ..observability import get_logger, heartbeat
Expand Down Expand Up @@ -216,6 +225,10 @@ def __init__(
)
self.llm: vLLM | None = None
self._prompt_token_count: int | None = None
# Populated in ``initialize()`` after engine build; pre-declared
# here so ``generate()`` can always read it (tests that mock the
# backend without calling ``initialize()`` see the empty dict).
self._engine_runtime_config: dict[str, Any] = {}

# Do not generate detailed error messages in production to avoid leaking sensitive data.
self.use_detailed_logs = kwargs.pop("use_detailed_logs", False)
Expand Down Expand Up @@ -292,6 +305,13 @@ def initialize(self, **kwargs) -> None:
trust_remote_code=model_ref.trust_remote_code,
)

# Cache the engine's *effective* runtime config once at init. Read by
# ``generate()`` to populate the generation-complete observability
# event; used by the benchmark harness (and any other intent-comparing
# caller) to detect "flag didn't engage" mismatches against what was
# asked for.
self._engine_runtime_config = probe_engine_runtime_config(self.llm)

# vLLM's get_tokenizer() returns a wider union than HF's PreTrainedTokenizerBase;
# in practice it's always a HF tokenizer subclass, so cast for the processor.
tokenizer = cast(PreTrainedTokenizerBase, self.llm.get_tokenizer())
Expand Down Expand Up @@ -632,15 +652,43 @@ def generate(
only for ``TabularDataProcessor``. Native EOS stopping remains enabled
through ``ignore_eos=False``.

Wrapped in an :class:`NvmlPeakSampler` context so a
generation-complete observability event is emitted at end of
the call carrying peak device VRAM, host loadavg pre/post, vLLM's
kv_cache_usage_perc / prefix_cache_hit_rate / spec_accept_rate
(read at end-of-generation), and the engine's effective runtime
config probed at engine-init time. Sampler is degraded-mode when
NVML is unavailable; the event still emits with ``peak_vram_gb=None``.

Args:
data_actions_fn: Optional post-processing / validation function
applied to each batch of generated records.

Returns:
Results containing the generated DataFrame and statistics.
"""
generation_start = time.monotonic()
loadavg_pre = read_loadavg()
sampler = NvmlPeakSampler()
Comment thread
binaryaaron marked this conversation as resolved.
Resolved
try:
with sampler:
self._run_generation(data_actions_fn)
finally:
# Emit regardless of success: the sampler thread has been joined
# by ``with`` exit, so ``sampler.peak_gb`` is the final peak, and
# the event carries whatever measurements were captured up to a
# failure point.
self._emit_generation_observability(sampler, loadavg_pre)

return self.gen_results

def _run_generation(self, data_actions_fn: utils.DataActionsFn | None) -> None:
"""Run the batch-generation loop until the target or a stop condition fires.

Populates ``self.gen_results`` and ``self.elapsed_time``. Extracted
from :meth:`generate` so that method stays a thin observability
bracket around the loop.
"""
generation_start = time.monotonic()
need_special_token_outputs = not isinstance(self.processor, TabularDataProcessor)
sampling_kwargs = dict(
temperature=self.config.generation.temperature,
Expand Down Expand Up @@ -707,13 +755,53 @@ def generate(
else None
)

generation_time_sec = time.monotonic() - generation_start
self.elapsed_time = generation_time_sec
self.elapsed_time = time.monotonic() - generation_start
self.gen_results = GenerateJobResults.from_batches(
batches=batches,
columns=self.columns,
max_num_records=max_num_records,
elapsed_time=self.elapsed_time,
)

return self.gen_results
def _emit_generation_observability(
self, sampler: NvmlPeakSampler, loadavg_pre: tuple[float, float, float] | None
) -> None:
"""Assemble and route the generation-complete observability event.

Reads end-of-generation vLLM metrics plus the NVML peak captured by
``sampler``, builds a :class:`GenerationObservability`, and routes it to
structured logs and (when a run is active) wandb. Best-effort: any
failure here is logged and swallowed so observability never masks a
generation error propagating through :meth:`generate`'s ``finally``.
"""
try:
vllm_metrics = read_vllm_runtime_metrics(self.llm)
gen_event = GenerationObservability(
peak_vram_gb=sampler.peak_gb,
kv_cache_usage_perc=vllm_metrics["kv_cache_usage_perc"],
Comment thread
binaryaaron marked this conversation as resolved.
Resolved
prefix_cache_hit_rate=vllm_metrics["prefix_cache_hit_rate"],
spec_accept_rate=vllm_metrics["spec_accept_rate"],
loadavg_pre=loadavg_pre,
loadavg_post=read_loadavg(),
engine_runtime_config=self._engine_runtime_config,
# ``flag_did_not_engage`` is the consuming caller's job to
# compute. Production generation has no intended-overrides
# dict to compare against; the benchmark harness probes the
# engine config against its candidate's intended settings and
# sets the bit when a knob silently fails to engage.
flag_did_not_engage=False,
)
logger.runtime.info("vLLM generation complete", extra={"ctx": gen_event.model_dump()})
# Mirror to the active wandb run when one exists (no-op when
# ``WANDB_MODE=disabled`` or ``initialize_wandb_run`` was never
# called). Best-effort; wandb failures are swallowed downstream.
log_observability_event(gen_event, prefix="vllm_gen")
except Exception as exc: # noqa: BLE001 — observability must never break generation
# Guard the warning itself: a faulty logger handler must not turn a
# swallowed observability failure into a generation failure.
with contextlib.suppress(Exception):
logger.runtime.debug(
"vLLM generation observability emit failed",
extra={"ctx": {"error": f"{exc!r}"}},
exc_info=True,
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading
Loading