Skip to content

Commit b3b07d8

Browse files
committed
Replace Optional and Union typing with | in some source files
Signed-off-by: Yuanyuan Chen <[email protected]>
1 parent 453a246 commit b3b07d8

27 files changed

+223
-243
lines changed

src/transformers/cli/add_new_model_like.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from collections.abc import Callable
2020
from datetime import date
2121
from pathlib import Path
22-
from typing import Annotated, Any, Optional, Union
22+
from typing import Annotated, Any
2323

2424
import typer
2525

@@ -95,7 +95,7 @@ def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine):
9595

9696
def add_new_model_like(
9797
repo_path: Annotated[
98-
Optional[str], typer.Argument(help="When not using an editable install, the path to the Transformers repo.")
98+
str | None, typer.Argument(help="When not using an editable install, the path to the Transformers repo.")
9999
] = None,
100100
):
101101
"""
@@ -156,7 +156,7 @@ def __init__(self, lowercase_name: str):
156156
self.processor_class = PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None)
157157

158158

159-
def add_content_to_file(file_name: Union[str, os.PathLike], new_content: str, add_after: str):
159+
def add_content_to_file(file_name: str | os.PathLike, new_content: str, add_after: str):
160160
"""
161161
A utility to add some content inside a given file.
162162
@@ -614,9 +614,9 @@ def _add_new_model_like_internal(
614614

615615
def get_user_field(
616616
question: str,
617-
default_value: Optional[str] = None,
618-
convert_to: Optional[Callable] = None,
619-
fallback_message: Optional[str] = None,
617+
default_value: str | None = None,
618+
convert_to: Callable | None = None,
619+
fallback_message: str | None = None,
620620
) -> Any:
621621
"""
622622
A utility function that asks a question to the user to get an answer, potentially looping until it gets a valid

src/transformers/cli/chat.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import string
2020
import time
2121
from collections.abc import AsyncIterator
22-
from typing import Annotated, Optional
22+
from typing import Annotated
2323

2424
import click
2525
import typer
@@ -214,7 +214,7 @@ def __init__(
214214
base_url: Annotated[str, typer.Argument(help="Base url to connect to (e.g. http://localhost:8000/v1).")],
215215
model_id: Annotated[str, typer.Argument(help="ID of the model to use (e.g. 'HuggingFaceTB/SmolLM3-3B').")],
216216
generate_flags: Annotated[
217-
Optional[list[str]],
217+
list[str] | None,
218218
typer.Argument(
219219
help=(
220220
"Flags to pass to `generate`, using a space as a separator between flags. Accepts booleans, numbers, "
@@ -227,15 +227,15 @@ def __init__(
227227
] = None,
228228
# General settings
229229
user: Annotated[
230-
Optional[str],
230+
str | None,
231231
typer.Option(help="Username to display in chat interface. Defaults to the current user's name."),
232232
] = None,
233-
system_prompt: Annotated[Optional[str], typer.Option(help="System prompt.")] = None,
233+
system_prompt: Annotated[str | None, typer.Option(help="System prompt.")] = None,
234234
save_folder: Annotated[str, typer.Option(help="Folder to save chat history.")] = "./chat_history/",
235-
examples_path: Annotated[Optional[str], typer.Option(help="Path to a yaml file with examples.")] = None,
235+
examples_path: Annotated[str | None, typer.Option(help="Path to a yaml file with examples.")] = None,
236236
# Generation settings
237237
generation_config: Annotated[
238-
Optional[str],
238+
str | None,
239239
typer.Option(
240240
help="Path to a local generation config file or to a HuggingFace repo containing a `generation_config.json` file. Other generation settings passed as CLI arguments will be applied on top of this generation config."
241241
),
@@ -455,7 +455,7 @@ async def _inner_run(self):
455455
break
456456

457457

458-
def load_generation_config(generation_config: Optional[str]) -> GenerationConfig:
458+
def load_generation_config(generation_config: str | None) -> GenerationConfig:
459459
if generation_config is None:
460460
return GenerationConfig()
461461

@@ -467,7 +467,7 @@ def load_generation_config(generation_config: Optional[str]) -> GenerationConfig
467467
return GenerationConfig.from_pretrained(generation_config)
468468

469469

470-
def parse_generate_flags(generate_flags: Optional[list[str]]) -> dict:
470+
def parse_generate_flags(generate_flags: list[str] | None) -> dict:
471471
"""Parses the generate flags from the user input into a dictionary of `generate` kwargs."""
472472
if generate_flags is None or len(generate_flags) == 0:
473473
return {}
@@ -521,7 +521,7 @@ def is_number(s: str) -> bool:
521521
return processed_generate_flags
522522

523523

524-
def new_chat_history(system_prompt: Optional[str] = None) -> list[dict]:
524+
def new_chat_history(system_prompt: str | None = None) -> list[dict]:
525525
"""Returns a new chat conversation."""
526526
return [{"role": "system", "content": system_prompt}] if system_prompt else []
527527

src/transformers/cli/download.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
from typing import Annotated, Optional
14+
from typing import Annotated
1515

1616
import typer
1717

1818

1919
def download(
2020
model_id: Annotated[str, typer.Argument(help="The model ID to download")],
21-
cache_dir: Annotated[Optional[str], typer.Option(help="Directory where to save files.")] = None,
21+
cache_dir: Annotated[str | None, typer.Option(help="Directory where to save files.")] = None,
2222
force_download: Annotated[
2323
bool, typer.Option(help="If set, the files will be downloaded even if they are already cached locally.")
2424
] = False,

src/transformers/cli/run.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
from enum import Enum
15-
from typing import Annotated, Optional
15+
from typing import Annotated
1616

1717
import typer
1818

@@ -28,27 +28,27 @@
2828

2929
def run(
3030
task: Annotated[TaskEnum, typer.Argument(help="Task to run", case_sensitive=False)], # type: ignore
31-
input: Annotated[Optional[str], typer.Option(help="Path to the file to use for inference")] = None,
31+
input: Annotated[str | None, typer.Option(help="Path to the file to use for inference")] = None,
3232
output: Annotated[
33-
Optional[str], typer.Option(help="Path to the file that will be used post to write results.")
33+
str | None, typer.Option(help="Path to the file that will be used post to write results.")
3434
] = None,
3535
model: Annotated[
36-
Optional[str],
36+
str | None,
3737
typer.Option(
3838
help="Name or path to the model to instantiate. If not provided, will use the default model for that task."
3939
),
4040
] = None,
4141
config: Annotated[
42-
Optional[str],
42+
str | None,
4343
typer.Option(
4444
help="Name or path to the model's config to instantiate. If not provided, will use the model's one."
4545
),
4646
] = None,
4747
tokenizer: Annotated[
48-
Optional[str], typer.Option(help="Name of the tokenizer to use. If not provided, will use the model's one.")
48+
str | None, typer.Option(help="Name of the tokenizer to use. If not provided, will use the model's one.")
4949
] = None,
5050
column: Annotated[
51-
Optional[str],
51+
str | None,
5252
typer.Option(help="Name of the column to use as input. For multi columns input use 'column1,columns2'"),
5353
] = None,
5454
format: Annotated[FormatEnum, typer.Option(help="Input format to read from", case_sensitive=False)] = "pipe", # type: ignore

src/transformers/cli/serve.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ def __init__(
305305
self,
306306
model: "PreTrainedModel",
307307
timeout_seconds: int,
308-
processor: Optional[Union["ProcessorMixin", "PreTrainedTokenizerFast"]] = None,
308+
processor: Union["ProcessorMixin", "PreTrainedTokenizerFast"] | None = None,
309309
):
310310
self.model = model
311311
self._name_or_path = str(model.name_or_path)
@@ -363,7 +363,7 @@ def __init__(
363363
),
364364
] = "auto",
365365
dtype: Annotated[
366-
Optional[str],
366+
str | None,
367367
typer.Option(
368368
help="Override the default `torch.dtype` and load the model under this dtype. If `'auto'` is passed, the dtype will be automatically derived from the model's weights."
369369
),
@@ -372,7 +372,7 @@ def __init__(
372372
bool, typer.Option(help="Whether to trust remote code when loading a model.")
373373
] = False,
374374
attn_implementation: Annotated[
375-
Optional[str],
375+
str | None,
376376
typer.Option(
377377
help="Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in which case you must install this manually by running `pip install flash-attn --no-build-isolation`."
378378
),
@@ -390,7 +390,7 @@ def __init__(
390390
str, typer.Option(help="Logging level as a string. Example: 'info' or 'warning'.")
391391
] = "info",
392392
default_seed: Annotated[
393-
Optional[int], typer.Option(help="The default seed for torch, should be an integer.")
393+
int | None, typer.Option(help="The default seed for torch, should be an integer.")
394394
] = None,
395395
enable_cors: Annotated[
396396
bool,
@@ -400,7 +400,7 @@ def __init__(
400400
] = False,
401401
input_validation: Annotated[bool, typer.Option(help="Whether to turn on strict input validation.")] = False,
402402
force_model: Annotated[
403-
Optional[str],
403+
str | None,
404404
typer.Option(
405405
help="Name of the model to be forced on all requests. This is useful for testing Apps that don't allow changing models in the request."
406406
),
@@ -445,7 +445,7 @@ def __init__(
445445
# Internal state:
446446
# 1. Tracks models in memory, to prevent reloading the model unnecessarily
447447
self.loaded_models: dict[str, TimedModel] = {}
448-
self.running_continuous_batching_manager: Optional[ContinuousBatchingManager] = None
448+
self.running_continuous_batching_manager: ContinuousBatchingManager | None = None
449449

450450
# 2. preserves information about the last call and last KV cache, to determine whether we can reuse the KV
451451
# cache and avoid re-running prefill
@@ -648,13 +648,13 @@ def validate_transcription_request(self, request: dict):
648648
def build_chat_completion_chunk(
649649
self,
650650
request_id: str = "",
651-
content: Optional[int] = None,
652-
model: Optional[str] = None,
653-
role: Optional[str] = None,
654-
finish_reason: Optional[str] = None,
655-
tool_calls: Optional[list["ChoiceDeltaToolCall"]] = None,
656-
decode_stream: Optional[DecodeStream] = None,
657-
tokenizer: Optional[PreTrainedTokenizerFast] = None,
651+
content: int | None = None,
652+
model: str | None = None,
653+
role: str | None = None,
654+
finish_reason: str | None = None,
655+
tool_calls: list["ChoiceDeltaToolCall"] | None = None,
656+
decode_stream: DecodeStream | None = None,
657+
tokenizer: PreTrainedTokenizerFast | None = None,
658658
) -> ChatCompletionChunk:
659659
"""
660660
Builds a chunk of a streaming OpenAI Chat Completion response.

src/transformers/cli/system.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import io
2323
import os
2424
import platform
25-
from typing import Annotated, Optional
25+
from typing import Annotated
2626

2727
import huggingface_hub
2828
import typer
@@ -40,7 +40,7 @@
4040

4141
def env(
4242
accelerate_config_file: Annotated[
43-
Optional[str],
43+
str | None,
4444
typer.Argument(help="The accelerate config file to use for the default values in the launching script."),
4545
] = None,
4646
) -> None:

0 commit comments

Comments
 (0)