Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 8 additions & 4 deletions src/llamafactory/chat/hf_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ def _process_args(
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
input_kwargs: Optional[dict[str, Any]] = {},
input_kwargs: Optional[dict[str, Any]] = None,
) -> tuple[dict[str, Any], int]:
input_kwargs = {} if input_kwargs is None else input_kwargs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent mutating the dictionary passed by the caller (since .pop() is called on input_kwargs later in this method), it is safer to create a copy of the dictionary instead of using it directly.

Suggested change
input_kwargs = {} if input_kwargs is None else input_kwargs
input_kwargs = {} if input_kwargs is None else dict(input_kwargs)

mm_input_dict = {"images": [], "videos": [], "audios": [], "imglens": [0], "vidlens": [0], "audlens": [0]}
if images is not None:
mm_input_dict.update({"images": images, "imglens": [len(images)]})
Expand Down Expand Up @@ -221,8 +222,9 @@ def _chat(
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
input_kwargs: Optional[dict[str, Any]] = {},
input_kwargs: Optional[dict[str, Any]] = None,
) -> list["Response"]:
input_kwargs = {} if input_kwargs is None else input_kwargs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent mutating the dictionary passed by the caller, it is safer to create a copy of the dictionary instead of using it directly.

Suggested change
input_kwargs = {} if input_kwargs is None else input_kwargs
input_kwargs = {} if input_kwargs is None else dict(input_kwargs)

gen_kwargs, prompt_length = HuggingfaceEngine._process_args(
model,
tokenizer,
Expand Down Expand Up @@ -276,8 +278,9 @@ def _stream_chat(
images: Optional[list["ImageInput"]] = None,
videos: Optional[list["VideoInput"]] = None,
audios: Optional[list["AudioInput"]] = None,
input_kwargs: Optional[dict[str, Any]] = {},
input_kwargs: Optional[dict[str, Any]] = None,
) -> Callable[[], str]:
input_kwargs = {} if input_kwargs is None else input_kwargs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent mutating the dictionary passed by the caller, it is safer to create a copy of the dictionary instead of using it directly.

Suggested change
input_kwargs = {} if input_kwargs is None else input_kwargs
input_kwargs = {} if input_kwargs is None else dict(input_kwargs)

gen_kwargs, _ = HuggingfaceEngine._process_args(
model,
tokenizer,
Expand Down Expand Up @@ -315,8 +318,9 @@ def _get_scores(
model: "PreTrainedModelWrapper",
tokenizer: "PreTrainedTokenizer",
batch_input: list[str],
input_kwargs: Optional[dict[str, Any]] = {},
input_kwargs: Optional[dict[str, Any]] = None,
) -> list[float]:
input_kwargs = {} if input_kwargs is None else input_kwargs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent mutating the dictionary passed by the caller (since .pop() is called on input_kwargs later in this method), it is safer to create a copy of the dictionary instead of using it directly.

Suggested change
input_kwargs = {} if input_kwargs is None else input_kwargs
input_kwargs = {} if input_kwargs is None else dict(input_kwargs)

max_length: Optional[int] = input_kwargs.pop("max_length", None)
device = getattr(model.pretrained_model, "device", "cuda")
inputs: dict[str, torch.Tensor] = tokenizer(
Expand Down
39 changes: 39 additions & 0 deletions tests/chat/test_hf_engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Copyright 2025 the LlamaFactory team.
#
# 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 ast
from pathlib import Path


def test_huggingface_engine_input_kwargs_defaults_are_not_mutable():
module_path = Path(__file__).parents[2] / "src" / "llamafactory" / "chat" / "hf_engine.py"
module = ast.parse(module_path.read_text(encoding="utf-8"))

expected_methods = {"_process_args", "_chat", "_stream_chat", "_get_scores"}
methods = {
node.name: node
for node in ast.walk(module)
if isinstance(node, ast.FunctionDef) and node.name in expected_methods
}

assert set(methods) == expected_methods

for method in methods.values():
arguments = method.args.args
defaults = method.args.defaults
default_by_arg = dict(zip((arg.arg for arg in arguments[-len(defaults) :]), defaults))

default = default_by_arg["input_kwargs"]
assert isinstance(default, ast.Constant)
assert default.value is None