mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-11-14 07:00:22 +08:00
### What does this PR do? Type of change: chore / refactor (no behavior change) Two small lint-cleanup commits: **1. `chore(typing): modernize Union/Optional/List to PEP 604 / 585 syntax`** (8 files) - Replace `X = Union[A, B] # noqa: UP007` with `X: TypeAlias = A | B` for the six module-level type aliases (`ModelLike`, `Criterion`, `NodeTarget`, `CalibrationDataType`, `Hparam.Importance` / `ActiveSlice`). The `TypeAlias` annotation is required so mypy continues to treat them as aliases under PEP 604. - Modernize forward-ref unions in `modelopt/onnx/quantization/autotune/` to full-string forward refs (e.g. `"RegionPattern | None"`). - Update docstring type tags in `examples/puzzletron/evaluation/hf_deployable_anymodel.py`. **2. `chore(lint): remove UP032 ignore and convert .format() to f-strings`** (10 files) - Drop `UP032` from `extend-ignore` in `pyproject.toml`. - Auto-convert 19 `"...".format(...)` calls to f-strings across export plugins, examples, tests, and tools. One conversion in `modelopt/torch/utils/plugins/megatron_generate.py` was wrapped manually to stay under the 100-char limit. **Intentionally left as-is:** - `tools/launcher/slurm_config.py` keeps its `# ruff: noqa: UP045` — nemo_run's CLI parser can't introspect PEP 604 optional annotations. - `modelopt/torch/puzzletron/*` is **not** touched. The subtree disables ruff's `UP` family entirely (per-file-ignore `"UP"`) while migration is in progress, and converting `Optional[X]` to `X | None` there would silently break runtime introspection in `block_config._get_dataclass_type` that uses `get_origin(tp) is typing.Union` (PEP 604 unions return `types.UnionType` from `get_origin`, not `typing.Union`). Best revisited when puzzletron's lint carve-out is narrowed. - `UP038` (`isinstance(x, (int, float))` → `isinstance(x, int | float)`) — ruff has officially deprecated this rule; PEP 604 in isinstance is slightly slower and misleads readers about PEP 695 / `Optional`. Ignore kept. ### Usage No user-facing API changes. ### Testing - Pre-commit hooks (ruff check, ruff format, mypy, bandit, license) pass on both commits. - Ruff status against `main`: 37 unrelated pre-existing findings (W291/W293/E501/RUF005/PLR1704); zero new findings introduced by this PR. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ — Runtime behavior of the six type aliases changes from a `typing.Union` instance to `types.UnionType`. Downstream code introspecting via `get_origin(...) is typing.Union` on these aliases would break, but no in-repo caller does this on them. (The introspection in `modelopt/torch/puzzletron/block_config.py` operates on user-supplied dataclass field types, none of which are these aliases.) - If you copied code from any other sources or added a new PIP dependency, did you follow guidance in `CONTRIBUTING.md`: N/A - Did you write any new necessary tests?: N/A (no behavior change) - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ❌ — internal style refactor; happy to add a Misc note if reviewers want one. - Did you get Claude approval on this PR?: ❌ — not yet. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Style** * Modernized type annotations across the codebase to use Python 3.10+ union syntax and TypeAlias where appropriate. * Standardized string formatting to f-strings, improving clarity of logs, errors, and validation messages. * **Chores** * Updated linting configuration to reflect modern typing/style rules. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/NVIDIA/Model-Optimizer/pull/1537?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Shengliang Xu <shengliangx@nvidia.com>
262 lines
9.6 KiB
Python
262 lines
9.6 KiB
Python
# SPDX-FileCopyrightText: Copyright (c) 2023-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.
|
|
|
|
"""Send conversations from a dataset to an OpenAI-compatible endpoint."""
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
import openai
|
|
from openai import AsyncOpenAI
|
|
from tqdm import tqdm
|
|
from transformers import AutoTokenizer
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(
|
|
description="""Collect hidden states from conversations
|
|
by sending full conversations as prompts to an OpenAI-compatible endpoint."""
|
|
)
|
|
|
|
## Model & Generation Parameters ##
|
|
parser.add_argument(
|
|
"--model",
|
|
type=str,
|
|
required=True,
|
|
help="Name of the served model.",
|
|
)
|
|
parser.add_argument(
|
|
"--model_card",
|
|
type=str,
|
|
default="moonshotai/Kimi-K2-Thinking",
|
|
help="Name of the served model card.",
|
|
)
|
|
parser.add_argument(
|
|
"--meta-channel-id",
|
|
type=str,
|
|
default=None,
|
|
help=(
|
|
"Unique identifier for the meta file name used to communicate with "
|
|
"the local serving engine. This should match the value used by the server."
|
|
),
|
|
)
|
|
parser.add_argument(
|
|
"--trust_remote_code",
|
|
action="store_true",
|
|
help="Set trust_remote_code for Huggingface models and tokenizers",
|
|
)
|
|
## Client Parameters ##
|
|
parser.add_argument(
|
|
"--base-url",
|
|
type=str,
|
|
default="http://localhost:8000/v1",
|
|
help="""HTTP URL for the OpenAI-compatible endpoint.
|
|
Defaults to `http://localhost:8000/v1`.""",
|
|
)
|
|
parser.add_argument(
|
|
"--openai-api-key",
|
|
default="EMPTY",
|
|
help="""Access key required by the OpenAI Python client
|
|
(not required for local serving engines like vLLM).""",
|
|
)
|
|
|
|
## I/O Parameters ##
|
|
parser.add_argument(
|
|
"--max-seq-len",
|
|
type=int,
|
|
default=8192,
|
|
help="""Maximum number of tokens in a conversation. Longer conversations will be skipped.
|
|
Defaults to 3072 tokens.""",
|
|
)
|
|
parser.add_argument(
|
|
"--input-file",
|
|
type=Path,
|
|
required=True,
|
|
help="""Path to the input `jsonl` file containing conversations.
|
|
Each entry must have a unique `conversation_id` field and a `conversations` field
|
|
containing a list of messages.""",
|
|
)
|
|
parser.add_argument(
|
|
"--output-dir",
|
|
type=Path,
|
|
required=True,
|
|
help="""Root directory in which to save the hidden states.
|
|
The data will be saved as a torch (`.pt`) dump file for each conversation.""",
|
|
)
|
|
parser.add_argument(
|
|
"--debug-max-num-conversations",
|
|
type=int,
|
|
default=None,
|
|
help="""For debugging purposes, limit the number of conversations processed.
|
|
Default is None, meaning no limit.""",
|
|
)
|
|
parser.add_argument("--num-shards", type=int, default=1, help="number of shards.")
|
|
parser.add_argument("--shard-id-begin", type=int, default=0, help="the shard id to start.")
|
|
parser.add_argument(
|
|
"--shard-id-step", type=int, default=1, help="the step that the shard id progress."
|
|
)
|
|
|
|
return parser.parse_args()
|
|
|
|
|
|
async def main(args: argparse.Namespace) -> None:
|
|
for shard_id in range(args.shard_id_begin, args.num_shards, args.shard_id_step):
|
|
if args.num_shards > 1:
|
|
input_file_path = (
|
|
args.input_file / f"train-{shard_id + 1:05}-{args.num_shards:05}.jsonl"
|
|
)
|
|
else:
|
|
input_file_path = args.input_file
|
|
|
|
if not input_file_path.exists():
|
|
print(f"Input jsonl file {input_file_path} not found, skipping.")
|
|
continue
|
|
|
|
all_conversations = []
|
|
with input_file_path.open("r", encoding="utf-8") as f:
|
|
all_conversations.extend([json.loads(line) for line in f if line.strip()])
|
|
|
|
print("Loaded", len(all_conversations), "conversations from", input_file_path)
|
|
|
|
client: AsyncOpenAI = AsyncOpenAI(
|
|
api_key=args.openai_api_key,
|
|
base_url=args.base_url,
|
|
)
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(
|
|
args.model_card, trust_remote_code=args.trust_remote_code
|
|
)
|
|
if tokenizer.pad_token is None:
|
|
tokenizer.pad_token = tokenizer.eos_token
|
|
bos_token_id = tokenizer.bos_token_id
|
|
if bos_token_id is None:
|
|
raise ValueError("The tokenizer does not have a BOS token.") # diff here
|
|
|
|
# temp_meta_file = Path(f"/tmp/meta_{args.meta_channel_id}.json") # diff here
|
|
|
|
temp_meta_file = Path("/dump_tmp/meta.json") # diff here
|
|
# INSERT_YOUR_CODE
|
|
temp_meta_file.parent.mkdir(parents=True, exist_ok=True)
|
|
if temp_meta_file.exists():
|
|
print(f"Temporary meta file {temp_meta_file} found, removing it.")
|
|
temp_meta_file.unlink()
|
|
|
|
output_dir = args.output_dir / f"train-{(shard_id + 1):05}-{args.num_shards:05}"
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
num_invalid = 0
|
|
num_exists = 0
|
|
num_error = 0
|
|
num_too_long = 0
|
|
num_success = 0
|
|
num_total_conversations = min(
|
|
len(all_conversations), args.debug_max_num_conversations or len(all_conversations)
|
|
)
|
|
for idx, entry in enumerate(
|
|
tqdm(
|
|
all_conversations[: args.debug_max_num_conversations],
|
|
desc="Processing conversations",
|
|
total=num_total_conversations,
|
|
)
|
|
):
|
|
conversation_id = entry.get("conversation_id", None)
|
|
if conversation_id is None:
|
|
conversation_id = entry.get("uuid", None)
|
|
if conversation_id is None:
|
|
conversation_id = f"{idx:08d}"
|
|
conversations = entry["conversations"]
|
|
if not conversations or not isinstance(conversations, list):
|
|
num_invalid += 1
|
|
continue
|
|
|
|
hidden_states_file = output_dir / f"{conversation_id}.pt"
|
|
if hidden_states_file.exists():
|
|
num_exists += 1
|
|
continue
|
|
|
|
# Use /tmp/meta.json to communicate with the local serving engine.
|
|
# See usage guide for more details
|
|
with temp_meta_file.open("w") as f:
|
|
json.dump(
|
|
{
|
|
"conversation_id": conversation_id,
|
|
"output_file": str(hidden_states_file),
|
|
},
|
|
f,
|
|
)
|
|
|
|
input_ids = tokenizer.apply_chat_template(
|
|
conversations, return_tensors=None, add_generation_template=False, tokenize=True
|
|
)
|
|
num_input_tokens = len(input_ids)
|
|
if num_input_tokens <= 10 or num_input_tokens > args.max_seq_len:
|
|
num_too_long += 1
|
|
continue
|
|
if bos_token_id is not None and input_ids[0] == bos_token_id:
|
|
# Remove the leading BOS token. vLLM's completion generation
|
|
# endpoint will prepend the BOS token automatically.
|
|
input_ids = input_ids[1:]
|
|
input_string = tokenizer.decode(input_ids, skip_special_tokens=False)
|
|
|
|
try:
|
|
# Send the message to the OpenAI-compatible endpoint
|
|
await client.completions.create(
|
|
model=args.model,
|
|
prompt=input_string, # diff here
|
|
temperature=0.0,
|
|
max_tokens=1,
|
|
)
|
|
except httpx.HTTPStatusError as e:
|
|
print(f"HTTP error for conversation {conversation_id}: {e}")
|
|
num_error += 1
|
|
continue
|
|
except openai.BadRequestError:
|
|
# Most likely the conversation is too long, ignore
|
|
num_too_long += 1
|
|
continue
|
|
except Exception as e:
|
|
num_error += 1
|
|
print(f"Error sending conversation {conversation_id}: {e}")
|
|
continue
|
|
finally:
|
|
# Ensure the meta file is cleaned up after each request
|
|
if temp_meta_file.exists():
|
|
temp_meta_file.unlink()
|
|
num_success += 1
|
|
continue
|
|
|
|
if num_invalid > 0:
|
|
print(f"Skipped {num_invalid} invalid conversations without proper fields.")
|
|
if num_too_long > 0:
|
|
print(f"Skipped {num_too_long} conversations likely due to length constraints.")
|
|
if num_error > 0:
|
|
print(f"Encountered errors for {num_error} conversations.")
|
|
if num_exists > 0:
|
|
print(f"Skipped {num_exists} conversations that already exist.")
|
|
|
|
if num_success == num_total_conversations:
|
|
print(f"Successfully processed all {num_success} conversations.")
|
|
else:
|
|
print(
|
|
f"Successfully processed {num_success} out of {num_total_conversations} conversations."
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
cli_args = parse_args()
|
|
asyncio.run(main(cli_args))
|