File size: 12,692 Bytes
8c31d70 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
import gc
import os
from abc import ABC
from typing import Any
import numpy as np
import torch
from .t5_text_encoder import CosmosT5TextEncoder
from .presets import presets as guardrail_presets
class BaseWorldGenerationPipeline(ABC):
def __init__(
self,
inference_type: str | None = None,
checkpoint_dir: str | None = None,
checkpoint_name: str | None = None,
enable_text_guardrail: bool = False,
enable_video_guardrail: bool = False,
offload_network: bool = False,
offload_tokenizer: bool = False,
offload_text_encoder_model: bool = False,
offload_guardrail_models: bool = False,
):
"""Initialize base world generation pipeline.
This abstract base class provides core functionality for world generation models including:
- Model loading and initialization
- Text encoding and embedding
- Safety checks and content filtering
- Memory management through model offloading
Args:
inference_type: The type of inference pipeline ("text2world" or "video2world")
checkpoint_dir: Root directory containing model checkpoints
checkpoint_name: Name of the specific checkpoint file to load
enable_text_guardrail: If True, validates input prompts for safety
enable_video_guardrail: If True, validates generated videos for safety
offload_network: If True, moves main model to CPU after inference
offload_tokenizer: If True, moves tokenizer to CPU after use
offload_text_encoder_model: If True, moves T5 encoder to CPU after encoding
offload_guardrail_models: If True, moves safety models to CPU after checks
"""
self.inference_type = inference_type
self.checkpoint_dir = checkpoint_dir
self.checkpoint_name = checkpoint_name
self.guardrail_dir = "Cosmos-1.0-Guardrail"
self.enable_text_guardrail = enable_text_guardrail
self.enable_video_guardrail = enable_video_guardrail
# Add offloading flags
self.offload_network = offload_network
self.offload_tokenizer = offload_tokenizer
self.offload_text_encoder_model = offload_text_encoder_model
self.offload_guardrail_models = offload_guardrail_models
# Initialize model instances
self.text_guardrail = None
self.video_guardrail = None
self.text_encoder = None
self.model = None
self._load_model()
if not self.offload_text_encoder_model:
self._load_text_encoder_model()
if not self.offload_guardrail_models:
if self.enable_text_guardrail:
self._load_text_guardrail()
if self.enable_video_guardrail:
self._load_video_guardrail()
if not self.offload_network:
self._load_network()
if not self.offload_tokenizer:
self._load_tokenizer()
def _load_tokenizer(self):
pass
def _load_network(self):
pass
def _load_model(self, checkpoint_name: str) -> Any:
"""Load the world generation model from a checkpoint.
This abstract method must be implemented by subclasses to load their specific
model architecture and weights.
Args:
checkpoint_name: Path to the model checkpoint file
Returns:
The loaded model instance
Raises:
NotImplementedError: Must be implemented by subclasses
"""
pass
def _load_text_encoder_model(self):
"""Load the T5 text encoder model.
Initializes and loads the T5 encoder model used for converting text prompts
into embeddings that condition the world generation model.
Returns:
Loaded T5 text encoder model instance
"""
self.text_encoder = CosmosT5TextEncoder(cache_dir=self.checkpoint_dir)
def _load_text_guardrail(self):
"""Load text safety classifier models.
Initializes models used for checking input prompts against safety policies.
Models are loaded from the specified guardrail directory.
"""
self.text_guardrail = guardrail_presets.create_text_guardrail_runner(
checkpoint_dir=os.path.join(self.checkpoint_dir, self.guardrail_dir)
)
def _load_video_guardrail(self):
"""Load video safety classifier models.
Initializes models used for validating generated video content against
safety policies. Models are loaded from the specified guardrail directory.
"""
self.video_guardrail = guardrail_presets.create_video_guardrail_runner(
checkpoint_dir=os.path.join(self.checkpoint_dir, self.guardrail_dir)
)
def _offload_network(self):
if self.model.model:
del self.model.model
self.model.model = None
gc.collect()
torch.cuda.empty_cache()
def _offload_tokenizer(self):
if self.model.tokenizer:
del self.model.tokenizer
self.model.tokenizer = None
gc.collect()
torch.cuda.empty_cache()
def _offload_guardrail_models(self):
"""Offload safety classifier models to reduce memory usage.
Moves safety models to CPU and clears GPU memory if they are no longer needed.
This helps manage memory when processing multiple inputs sequentially.
"""
if self.text_guardrail:
del self.text_guardrail
self.text_guardrail = None
if self.video_guardrail:
del self.video_guardrail
self.video_guardrail = None
gc.collect()
torch.cuda.empty_cache()
def _offload_text_encoder_model(self):
"""Offload T5 text encoder to reduce memory usage.
Moves the T5 encoder to CPU and clears GPU memory after text encoding is complete.
This helps manage memory when processing multiple inputs sequentially.
"""
if self.text_encoder:
del self.text_encoder
self.text_encoder = None
gc.collect()
torch.cuda.empty_cache()
def _run_model(self, *args: Any, **kwargs: Any) -> torch.Tensor:
"""Generate world latents using the model.
This abstract method must be implemented by subclasses to define their specific
generation process.
Args:
*args: Variable positional arguments for model inference
**kwargs: Variable keyword arguments for model inference
Returns:
torch.Tensor: Generated world representation tensor
"""
pass
def _run_model_with_offload(self, *args: Any, **kwargs: Any) -> torch.Tensor:
"""Generate world representation with memory management.
Handles loading the model before inference and offloading afterward if enabled.
This helps minimize GPU memory usage during inference.
Args:
*args: Arguments passed to _run_model
**kwargs: Keyword arguments passed to _run_model
Returns:
np.ndarray: Generated world representation as numpy array
"""
pass
def _run_guardrail_on_prompt(self, prompt: str) -> bool:
"""Check if prompt meets safety requirements.
Validates the input prompt against safety policies using loaded guardrail models.
Args:
prompt: Raw text prompt to validate
Returns:
bool: True if prompt passes all safety checks, False otherwise
"""
return guardrail_presets.run_text_guardrail(prompt, self.text_guardrail)
def _run_guardrail_on_prompt_with_offload(self, prompt: str) -> bool:
"""Check prompt safety with memory management.
Validates prompt safety while handling model loading/offloading to manage memory.
Args:
prompt: Raw text prompt to validate
Returns:
bool: True if prompt passes all safety checks, False otherwise
"""
if self.offload_guardrail_models:
self._load_text_guardrail()
is_safe = self._run_guardrail_on_prompt(prompt)
if self.offload_guardrail_models:
self._offload_guardrail_models()
return is_safe
def _run_guardrail_on_video(self, video: np.ndarray) -> np.ndarray | None:
"""Check if video meets safety requirements.
Validates generated video content against safety policies using guardrail models.
Args:
video: Video frames to validate
Returns:
np.ndarray: Processed video if safe, None if unsafe
"""
return guardrail_presets.run_video_guardrail(video, self.video_guardrail)
def _run_guardrail_on_video_with_offload(self, video: np.ndarray) -> np.ndarray | None:
"""Check if generated video meets safety requirements.
Args:
video: Video frames to validate
Returns:
np.ndarray: Processed video frames if safe, None otherwise
Note:
Guardrail models are offloaded after checks if enabled.
"""
if self.offload_guardrail_models:
self._load_video_guardrail()
video = self._run_guardrail_on_video(video)
if self.offload_guardrail_models:
self._offload_guardrail_models()
return video
def _run_text_embedding_on_prompt(
self, prompts: list[str], **kwargs: Any
) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
"""Convert text prompts to embeddings.
Processes text prompts into embedding tensors that condition the generation model.
Args:
prompts: List of text prompts to encode
**kwargs: Additional arguments for text encoding
Returns:
tuple containing:
- List of text embedding tensors for each prompt
- List of attention masks for each embedding
"""
embeddings = []
masks = []
for prompt in prompts:
embedding, mask = self.text_encoder.encode_prompts(
[prompt],
**kwargs,
)
embeddings.append(embedding)
masks.append(mask)
return embeddings, masks
def _run_text_embedding_on_prompt_with_offload(
self, prompts: list[str], **kwargs: Any
) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
"""Convert text prompt into embeddings using T5 encoder.
Args:
prompt: Processed and validated text prompt
Returns:
Text embedding tensor to condition diffusion model
Note:
T5 model is offloaded after encoding if enabled.
"""
if self.offload_text_encoder_model:
self._load_text_encoder_model()
embeddings, masks = self._run_text_embedding_on_prompt(prompts, **kwargs)
if self.offload_text_encoder_model:
self._offload_text_encoder_model()
return embeddings, masks
def _run_tokenizer_decoding(self, samples: torch.Tensor) -> np.ndarray:
"""Decode model outputs into final world representation.
This abstract method must be implemented by subclasses to convert raw model
outputs into their specific world representation format.
Args:
samples: Raw output tensor from the generation model
Returns:
np.ndarray: Decoded world representation
"""
pass
def generate(self, *args: Any, **kwargs: Any):
"""Generate world representation.
This abstract method must be implemented by subclasses to convert raw model
outputs into their specific world representation format.
Args:
*args: Variable positional arguments for model inference
**kwargs: Variable keyword arguments for model inference
"""
pass
|