Skip to content

Commit d43b73c

Browse files
cyyeverArthurZucker
authored andcommitted
Simplify unnecessary Optional typing (#40839)
Remove Optional Signed-off-by: Yuanyuan Chen <cyyever@outlook.com>
1 parent 3691102 commit d43b73c

File tree

13 files changed

+45
-43
lines changed

13 files changed

+45
-43
lines changed

src/transformers/audio_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ def chroma_filter_bank(
370370
tuning: float = 0.0,
371371
power: Optional[float] = 2.0,
372372
weighting_parameters: Optional[tuple[float, float]] = (5.0, 2.0),
373-
start_at_c_chroma: Optional[bool] = True,
373+
start_at_c_chroma: bool = True,
374374
):
375375
"""
376376
Creates a chroma filter bank, i.e a linear transformation to project spectrogram bins onto chroma bins.
@@ -391,7 +391,7 @@ def chroma_filter_bank(
391391
weighting_parameters (`tuple[float, float]`, *optional*, defaults to `(5., 2.)`):
392392
If specified, apply a Gaussian weighting parameterized by the first element of the tuple being the center and
393393
the second element being the Gaussian half-width.
394-
start_at_c_chroma (`float`, *optional*, defaults to `True`):
394+
start_at_c_chroma (`bool`, *optional*, defaults to `True`):
395395
If True, the filter bank will start at the 'C' pitch class. Otherwise, it will start at 'A'.
396396
Returns:
397397
`np.ndarray` of shape `(num_frequency_bins, num_chroma)`
@@ -627,7 +627,7 @@ def spectrogram(
627627
reference: float = 1.0,
628628
min_value: float = 1e-10,
629629
db_range: Optional[float] = None,
630-
remove_dc_offset: Optional[bool] = None,
630+
remove_dc_offset: bool = False,
631631
dtype: np.dtype = np.float32,
632632
) -> np.ndarray:
633633
"""
@@ -838,7 +838,7 @@ def spectrogram_batch(
838838
reference: float = 1.0,
839839
min_value: float = 1e-10,
840840
db_range: Optional[float] = None,
841-
remove_dc_offset: Optional[bool] = None,
841+
remove_dc_offset: bool = False,
842842
dtype: np.dtype = np.float32,
843843
) -> list[np.ndarray]:
844844
"""

src/transformers/commands/serving.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ class TransformersTranscriptionCreateParams(TranscriptionCreateParamsBase, total
141141

142142
file: bytes # Overwritten -- pydantic isn't happy with `typing.IO[bytes]`, present in the original type
143143
generation_config: str
144-
stream: Optional[bool] = False
144+
stream: bool = False
145145

146146
# Contrarily to OpenAI's output types, input types are `TypedDict`, which don't have built-in validation.
147147
response_validator = TypeAdapter(TransformersResponseCreateParamsStreaming)
@@ -600,7 +600,7 @@ def validate_transcription_request(self, request: dict):
600600

601601
def build_chat_completion_chunk(
602602
self,
603-
request_id: Optional[str] = "",
603+
request_id: str = "",
604604
content: Optional[int] = None,
605605
model: Optional[str] = None,
606606
role: Optional[str] = None,

src/transformers/data/datasets/squad.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,9 +122,9 @@ def __init__(
122122
tokenizer: PreTrainedTokenizer,
123123
limit_length: Optional[int] = None,
124124
mode: Union[str, Split] = Split.train,
125-
is_language_sensitive: Optional[bool] = False,
125+
is_language_sensitive: bool = False,
126126
cache_dir: Optional[str] = None,
127-
dataset_format: Optional[str] = "pt",
127+
dataset_format: str = "pt",
128128
):
129129
self.args = args
130130
self.is_language_sensitive = is_language_sensitive

src/transformers/generation/beam_search.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,10 @@ def __init__(
165165
batch_size: int,
166166
num_beams: int,
167167
device: torch.device,
168-
length_penalty: Optional[float] = 1.0,
169-
do_early_stopping: Optional[Union[bool, str]] = False,
170-
num_beam_hyps_to_keep: Optional[int] = 1,
171-
num_beam_groups: Optional[int] = 1,
168+
length_penalty: float = 1.0,
169+
do_early_stopping: Union[bool, str] = False,
170+
num_beam_hyps_to_keep: int = 1,
171+
num_beam_groups: int = 1,
172172
max_length: Optional[int] = None,
173173
):
174174
logger.warning_once(
@@ -214,7 +214,7 @@ def __init__(
214214

215215
@property
216216
def is_done(self) -> bool:
217-
return self._done.all()
217+
return self._done.all().item()
218218

219219
def process(
220220
self,
@@ -225,8 +225,8 @@ def process(
225225
pad_token_id: Optional[Union[int, torch.Tensor]] = None,
226226
eos_token_id: Optional[Union[int, list[int], torch.Tensor]] = None,
227227
beam_indices: Optional[torch.LongTensor] = None,
228-
group_index: Optional[int] = 0,
229-
decoder_prompt_len: Optional[int] = 0,
228+
group_index: int = 0,
229+
decoder_prompt_len: int = 0,
230230
) -> dict[str, torch.Tensor]:
231231
# add up to the length which the next_scores is calculated on (including decoder prompt)
232232
cur_len = input_ids.shape[-1] + 1
@@ -460,9 +460,9 @@ def __init__(
460460
num_beams: int,
461461
constraints: list[Constraint],
462462
device: torch.device,
463-
length_penalty: Optional[float] = 1.0,
464-
do_early_stopping: Optional[Union[bool, str]] = False,
465-
num_beam_hyps_to_keep: Optional[int] = 1,
463+
length_penalty: float = 1.0,
464+
do_early_stopping: Union[bool, str] = False,
465+
num_beam_hyps_to_keep: int = 1,
466466
max_length: Optional[int] = None,
467467
):
468468
logger.warning_once(
@@ -495,7 +495,7 @@ def __init__(
495495

496496
@property
497497
def is_done(self) -> bool:
498-
return self._done.all()
498+
return self._done.all().item()
499499

500500
def make_constraint_states(self, n):
501501
return [ConstraintListState([constraint.copy() for constraint in self.constraints]) for _ in range(n)]
@@ -515,7 +515,7 @@ def process(
515515
pad_token_id: Optional[Union[int, torch.Tensor]] = None,
516516
eos_token_id: Optional[Union[int, list[int], torch.Tensor]] = None,
517517
beam_indices: Optional[torch.LongTensor] = None,
518-
decoder_prompt_len: Optional[int] = 0,
518+
decoder_prompt_len: int = 0,
519519
) -> tuple[torch.Tensor]:
520520
r"""
521521
Args:
@@ -912,7 +912,9 @@ def finalize(
912912

913913

914914
class BeamHypotheses:
915-
def __init__(self, num_beams: int, length_penalty: float, early_stopping: bool, max_length: Optional[int] = None):
915+
def __init__(
916+
self, num_beams: int, length_penalty: float, early_stopping: Union[bool, str], max_length: Optional[int] = None
917+
):
916918
"""
917919
Initialize n-best list of hypotheses.
918920
"""

src/transformers/generation/configuration_utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,11 +1282,11 @@ class WatermarkingConfig(BaseWatermarkingConfig):
12821282

12831283
def __init__(
12841284
self,
1285-
greenlist_ratio: Optional[float] = 0.25,
1286-
bias: Optional[float] = 2.0,
1287-
hashing_key: Optional[int] = 15485863,
1288-
seeding_scheme: Optional[str] = "lefthash",
1289-
context_width: Optional[int] = 1,
1285+
greenlist_ratio: float = 0.25,
1286+
bias: float = 2.0,
1287+
hashing_key: int = 15485863,
1288+
seeding_scheme: str = "lefthash",
1289+
context_width: int = 1,
12901290
):
12911291
self.greenlist_ratio = greenlist_ratio
12921292
self.bias = bias

src/transformers/image_processing_utils_fast.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def validate_fast_preprocess_arguments(
8585
size: Optional[SizeDict] = None,
8686
interpolation: Optional["F.InterpolationMode"] = None,
8787
return_tensors: Optional[Union[str, TensorType]] = None,
88-
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
88+
data_format: ChannelDimension = ChannelDimension.FIRST,
8989
):
9090
"""
9191
Checks validity of typically used arguments in an `ImageProcessorFast` `preprocess` method.

src/transformers/integrations/peft.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def load_adapter(
9696
adapter_name: Optional[str] = None,
9797
revision: Optional[str] = None,
9898
token: Optional[str] = None,
99-
device_map: Optional[str] = "auto",
99+
device_map: str = "auto",
100100
max_memory: Optional[str] = None,
101101
offload_folder: Optional[str] = None,
102102
offload_index: Optional[int] = None,

src/transformers/model_debugging_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,8 @@ def clean(val):
269269

270270
def _attach_debugger_logic(
271271
model,
272-
debug_path: Optional[str] = ".",
273-
do_prune_layers: Optional[bool] = True,
272+
debug_path: str = ".",
273+
do_prune_layers: bool = True,
274274
use_repr: bool = True,
275275
):
276276
"""
@@ -399,8 +399,8 @@ def top_wrapped_forward(*inps, **kws):
399399
def model_addition_debugger_context(
400400
model,
401401
debug_path: Optional[str] = None,
402-
do_prune_layers: Optional[bool] = True,
403-
use_repr: Optional[bool] = True,
402+
do_prune_layers: bool = True,
403+
use_repr: bool = True,
404404
):
405405
"""
406406
# Model addition debugger - context manager for model adders

src/transformers/modeling_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3556,7 +3556,7 @@ def _get_resized_lm_head(
35563556
self,
35573557
old_lm_head: nn.Linear,
35583558
new_num_tokens: Optional[int] = None,
3559-
transposed: Optional[bool] = False,
3559+
transposed: bool = False,
35603560
mean_resizing: bool = True,
35613561
) -> nn.Linear:
35623562
"""
@@ -3713,7 +3713,7 @@ def _init_added_lm_head_weights_with_mean(
37133713
old_lm_head_dim,
37143714
old_num_tokens,
37153715
added_num_tokens,
3716-
transposed=False,
3716+
transposed: bool = False,
37173717
):
37183718
if transposed:
37193719
# Transpose to the desired shape for the function.

src/transformers/pipelines/token_classification.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def _sanitize_parameters(
160160
ignore_subwords: Optional[bool] = None,
161161
aggregation_strategy: Optional[AggregationStrategy] = None,
162162
offset_mapping: Optional[list[tuple[int, int]]] = None,
163-
is_split_into_words: Optional[bool] = False,
163+
is_split_into_words: bool = False,
164164
stride: Optional[int] = None,
165165
delimiter: Optional[str] = None,
166166
):

0 commit comments

Comments
 (0)