Skip to content

Commit

Permalink
Convert directory fbcode/torcheval to use the Ruff Formatter
Browse files Browse the repository at this point in the history
Summary:
Converts the directory specified to use the Ruff formatter in pyfmt

ruff_dog

If this diff causes merge conflicts when rebasing, please run
`hg status -n -0 --change . -I '**/*.{py,pyi}' | xargs -0 arc pyfmt`
on your diff, and amend any changes before rebasing onto latest.
That should help reduce or eliminate any merge conflicts.

allow-large-files

Reviewed By: amyreese

Differential Revision: D66304552

fbshipit-source-id: c138069c4b2b26c6d0fb3d47496ea717f40c8674
  • Loading branch information
Thomas Polasek authored and facebook-github-bot committed Nov 21, 2024
1 parent 2e8759f commit 2c7dfb3
Show file tree
Hide file tree
Showing 31 changed files with 7 additions and 53 deletions.
4 changes: 1 addition & 3 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,7 @@ def setup(app):

# In Sphinx 1.8 it was renamed to `add_css_file`, 1.7 and prior it is
# `add_stylesheet` (deprecated in 1.8).
add_css = getattr(
app, "add_css_file", getattr(app, "add_stylesheet", None)
) # noqa B009
add_css = getattr(app, "add_css_file", getattr(app, "add_stylesheet", None)) # noqa B009
for css_file in html_css_files:
add_css(css_file)
app.set_translator("html", PatchedHTMLTranslator)
Expand Down
5 changes: 3 additions & 2 deletions tests/metrics/aggregation/test_auc.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,9 @@ def test_auc_class_no_unsqueeze(self) -> None:
]

# Build sklearn metrics
sk_x, sk_y = torch.cat([tx.unsqueeze(0) for tx in x], dim=1), torch.cat(
[ty.unsqueeze(0) for ty in y], dim=1
sk_x, sk_y = (
torch.cat([tx.unsqueeze(0) for tx in x], dim=1),
torch.cat([ty.unsqueeze(0) for ty in y], dim=1),
)
compute_result = torch.tensor(
[sklearn_auc(temp_x, temp_y) for temp_x, temp_y in zip(sk_x, sk_y)],
Expand Down
3 changes: 0 additions & 3 deletions tests/metrics/classification/test_accuracy.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ def test_accuracy_class_invalid_input(self) -> None:

class TestTopKAccuracy(MetricClassTester):
def test_accuracy_class_base(self) -> None:

input = torch.tensor(
[
[
Expand Down Expand Up @@ -315,7 +314,6 @@ def test_accuracy_class_base(self) -> None:
)

def test_accuracy_class_macro(self) -> None:

input = torch.tensor(
[
[
Expand Down Expand Up @@ -347,7 +345,6 @@ def test_accuracy_class_macro(self) -> None:
)

def test_accuracy_class_no_average(self) -> None:

input = torch.tensor(
[
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ def _test_binary_binned_precision_recall_curve_class_with_input(
target: torch.Tensor,
threshold: Union[int, List[float], torch.Tensor],
) -> None:

compute_result = binary_binned_precision_recall_curve(
input.reshape(-1), target.reshape(-1), threshold=threshold
)
Expand Down
3 changes: 0 additions & 3 deletions tests/metrics/classification/test_confusion_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def _test_binary_confusion_matrix_with_input(
target: torch.Tensor,
normalize: Optional[str] = None,
) -> None:

input_np = input.flatten().numpy()
target_np = target.flatten().numpy()

Expand Down Expand Up @@ -145,7 +144,6 @@ def test_binary_confusion_matrix_score_thresholding(self) -> None:
)

def test_binary_confusion_matrix_invalid_input(self) -> None:

metric = BinaryConfusionMatrix()

with self.assertRaisesRegex(
Expand Down Expand Up @@ -189,7 +187,6 @@ def _test_multiclass_confusion_matrix_with_input(
num_classes: int,
normalize: Optional[str] = None,
) -> None:

if input.ndim == 3:
input_np = input.argmax(dim=2).flatten().numpy()
else:
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/classification/test_precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ def _test_binary_precision_with_input(
target: torch.Tensor,
threshold: float = 0.5,
) -> None:

input_np = np.where(input.numpy() < threshold, 0, 1)
target_np = target.squeeze().numpy()
compute_result = torch.tensor(
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/classification/test_recall.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,6 @@ def _test_binary_recall_class_with_input(
target: torch.Tensor,
threshold: float = 0.5,
) -> None:

input_np = np.where(input.numpy() < threshold, 0, 1)
target_np = target.squeeze().numpy()

Expand Down
1 change: 0 additions & 1 deletion tests/metrics/functional/classification/test_accuracy.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ def test_binary_accuracy_with_rounding(self) -> None:
self._test_binary_accuracy_with_input(input, target)

def test_binary_accuracy_invalid_input(self) -> None:

with self.assertRaisesRegex(
ValueError,
"The `input` and `target` should have the same dimensions, "
Expand Down
4 changes: 0 additions & 4 deletions tests/metrics/functional/classification/test_auprc.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ class TestBinaryAUPRC(unittest.TestCase):
def _get_sklearn_equivalent(
self, input: torch.Tensor, target: torch.Tensor, device: str = "cpu"
) -> torch.Tensor:

# Convert input/target to sklearn style inputs
# run each task once at a time since no multi-task/multiclass
# available for sklearn
Expand All @@ -43,7 +42,6 @@ def _test_binary_auprc_with_input(
num_tasks: int = 1,
compute_result: Optional[torch.Tensor] = None,
) -> None:

device = "cpu"
if torch.cuda.is_available():
device = "cuda"
Expand Down Expand Up @@ -175,7 +173,6 @@ def _test_multiclass_auprc_with_input(
num_classes: int,
compute_result: Optional[torch.Tensor] = None,
) -> None:

device = "cpu"
if torch.cuda.is_available():
device = "cuda"
Expand Down Expand Up @@ -372,7 +369,6 @@ def _test_multilabel_auprc_with_input(
average: Optional[str] = "macro",
compute_result: Optional[torch.Tensor] = None,
) -> None:

device = "cuda" if torch.cuda.is_available() else "cpu"

# get sklearn compute result if none given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ def test_binary_confusion_matrix_score_thresholding(self) -> None:
)

def test_binary_confusion_matrix_invalid_input(self) -> None:

with self.assertRaisesRegex(
ValueError,
"input should be a one-dimensional tensor for binary confusion matrix, "
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/functional/classification/test_f1_score.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ def test_binary_f1_score_thresholding(self) -> None:
)

def test_binary_f1_score_invalid_input(self) -> None:

with self.assertRaisesRegex(
ValueError,
"input should be a one-dimensional tensor for binary f1 score, "
Expand Down
2 changes: 0 additions & 2 deletions tests/metrics/functional/classification/test_precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ def _test_binary_precision_with_input(
target: torch.Tensor,
threshold: float = 0.5,
) -> None:

input_np = np.where(input.numpy() < threshold, 0, 1)
target_np = target.squeeze().numpy()
sklearn_result = torch.tensor(precision_score(target_np, input_np)).to(
Expand Down Expand Up @@ -71,7 +70,6 @@ def test_binary_precision_with_rounding(self) -> None:
self._test_binary_precision_with_input(input, target)

def test_binary_precision_invalid_input(self) -> None:

with self.assertRaisesRegex(
ValueError,
"The `input` and `target` should have the same dimensions, "
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/functional/classification/test_recall.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ def _test_binary_recall_with_input(
target: torch.Tensor,
threshold: float = 0.5,
) -> None:

my_compute_result = my_binary_recall_score(input, target, threshold=threshold)

input_np = np.where(input.numpy() < threshold, 0, 1)
Expand Down
3 changes: 0 additions & 3 deletions tests/metrics/functional/text/test_perplexity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

class Perplexity(unittest.TestCase):
def test_perplexity(self) -> None:

input = torch.tensor([[[0.3659, 0.7025, 0.3104]], [[0.0097, 0.6577, 0.1947]]])
target = torch.tensor([[2], [1]])
torch.testing.assert_close(
Expand Down Expand Up @@ -43,7 +42,6 @@ def test_perplexity(self) -> None:
)

def test_perplexity_with_ignore_index(self) -> None:

input = torch.tensor([[[0.3659, 0.7025, 0.3104]], [[0.0097, 0.6577, 0.1947]]])
target = torch.tensor([[2], [100]])
torch.testing.assert_close(
Expand Down Expand Up @@ -72,7 +70,6 @@ def test_perplexity_with_ignore_index(self) -> None:
)

def test_perplexity_with_invalid_input(self) -> None:

with self.assertRaisesRegex(
ValueError, "target should be a two-dimensional tensor"
):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

class TestWordInformationLost(unittest.TestCase):
def test_word_information_lost(self) -> None:

input = ["hello world", "welcome to the facebook"]
target = ["hello metaverse", "welcome to meta"]
torch.testing.assert_close(
Expand Down
2 changes: 0 additions & 2 deletions tests/metrics/image/test_fid.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ def _get_random_data_FrechetInceptionDistance(
height: int,
width: int,
) -> torch.Tensor:

imgs = torch.rand(
size=(num_updates, batch_size, num_channels, height, width),
)
Expand Down Expand Up @@ -107,7 +106,6 @@ def _test_fid(
expected_result: torch.Tensor,
model: Optional[torch.nn.Module] = None,
) -> None:

# create an alternating list of boolean values to
# simulate a sequence of alternating real and generated images
real_or_gen = [idx % 2 == 0 for idx in range(NUM_TOTAL_UPDATES)]
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/image/test_psnr.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ def test_psnr_class_invalid_input(self) -> None:
metric.update(torch.rand(4, 3, 4, 4), torch.rand(4, 3, 4, 6))

def test_psnr_class_invalid_data_range(self) -> None:

with self.assertRaisesRegex(
ValueError, "`data_range needs to be either `None` or `float`."
):
Expand Down
2 changes: 0 additions & 2 deletions tests/metrics/image/test_ssim.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ def _get_input_data(
height: int,
width: int,
) -> Dict[str, Tensor]:

images = {
"images_1": torch.rand(
size=(num_updates, batch_size, num_channels, height, width)
Expand All @@ -52,7 +51,6 @@ def _get_input_data(
def test_ssim(
self,
) -> None:

images = self._get_input_data(
NUM_TOTAL_UPDATES, BATCH_SIZE, IMG_CHANNELS, IMG_HEIGHT, IMG_WIDTH
)
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/ranking/test_retrieval_precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@


class TestRetrievalPrecision(MetricClassTester):

# test update and compute functions

def test_retrieval_precision_single_updates_1_query_avg_none(self) -> None:
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/test_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,6 @@ def test_reset_state_tensor_dict(self) -> None:
)

def test_reset_primitive_type(self) -> None:

TDummyMetric = TypeVar("TDummyMetric")

class DummyMetric(Metric[Tuple[float, int]]):
Expand Down
1 change: 0 additions & 1 deletion tests/metrics/text/test_perplexity.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ def test_perplexity_with_ignore_index(self) -> None:
)

def test_perplexity_with_invalid_input(self) -> None:

metric = Perplexity()
with self.assertRaisesRegex(
ValueError, "target should be a two-dimensional tensor"
Expand Down
3 changes: 0 additions & 3 deletions torcheval/metrics/functional/classification/accuracy.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ def _multiclass_accuracy_update(
num_classes: Optional[int],
k: int,
) -> Tuple[torch.Tensor, torch.Tensor]:

_accuracy_update_input_check(input, target, num_classes, k)

if k == 1:
Expand Down Expand Up @@ -353,7 +352,6 @@ def _binary_accuracy_update(
target: torch.Tensor,
threshold: float = 0.5,
) -> Tuple[torch.Tensor, torch.Tensor]:

_binary_accuracy_update_input_check(input, target)

input = torch.where(input < threshold, 0, 1)
Expand Down Expand Up @@ -417,7 +415,6 @@ def _multilabel_update(
target: torch.Tensor,
criteria: str = "exact_match",
) -> Tuple[torch.Tensor, torch.Tensor]:

if criteria == "exact_match":
num_correct = torch.all(input == target, dim=1).sum()
num_total = torch.tensor(target.shape[0], device=target.device)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,6 @@ def _binary_confusion_matrix_update(
target: torch.Tensor,
threshold: float = 0.5,
) -> torch.Tensor:

_binary_confusion_matrix_update_input_check(input, target)

input = torch.where(input < threshold, 0, 1)
Expand Down Expand Up @@ -200,7 +199,6 @@ def _confusion_matrix_compute(
confusion_matrix: torch.Tensor,
normalize: Optional[str],
) -> torch.Tensor:

if normalize == "pred":
return norm(confusion_matrix.to(torch.float), p=1, dim=0)
elif normalize == "true":
Expand Down
1 change: 0 additions & 1 deletion torcheval/metrics/functional/classification/f1_score.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ def _binary_f1_score_update(
target: torch.Tensor,
threshold: float = 0.5,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:

_binary_f1_score_update_input_check(input, target)

input = torch.where(input < threshold, 0, 1)
Expand Down
2 changes: 0 additions & 2 deletions torcheval/metrics/functional/classification/precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ def _precision_compute(
num_label: torch.Tensor,
average: Optional[str],
) -> torch.Tensor:

if average in ("macro", "weighted"):
# Ignore the class that has no samples in both `input` and `target`
mask = (num_label != 0) | ((num_tp + num_fp) != 0)
Expand Down Expand Up @@ -225,7 +224,6 @@ def _binary_precision_update(
target: torch.Tensor,
threshold: float = 0.5,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:

_binary_precision_update_input_check(input, target)

input = torch.where(input < threshold, 0, 1)
Expand Down
1 change: 0 additions & 1 deletion torcheval/metrics/functional/classification/recall.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def _binary_recall_compute(
num_tp: torch.Tensor,
num_true_labels: torch.Tensor,
) -> torch.Tensor:

recall = num_tp / num_true_labels

if torch.isnan(recall):
Expand Down
2 changes: 0 additions & 2 deletions torcheval/metrics/functional/image/psnr.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ def peak_signal_noise_ratio(


def _psnr_param_check(data_range: Optional[float]) -> None:

# Check matching shapes
if data_range is not None:
if type(data_range) is not float:
Expand All @@ -58,7 +57,6 @@ def _psnr_param_check(data_range: Optional[float]) -> None:


def _psnr_input_check(input: torch.Tensor, target: torch.Tensor) -> None:

# Check matching shapes
if input.shape != target.shape:
raise ValueError(
Expand Down
2 changes: 0 additions & 2 deletions torcheval/metrics/functional/text/perplexity.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ def _perplexity_compute(
sum_log_probs: torch.Tensor,
num_total: torch.Tensor,
) -> torch.Tensor:

return torch.exp(sum_log_probs / num_total).double()


Expand All @@ -122,7 +121,6 @@ def _perplexity_input_check(
target: torch.Tensor,
ignore_index: Optional[int] = None,
) -> None:

if target.ndim != 2:
raise ValueError(
f"target should be a two-dimensional tensor, got shape {target.shape}."
Expand Down
4 changes: 2 additions & 2 deletions torcheval/metrics/functional/text/word_information_lost.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ def _wil_update(
input = [input]
if isinstance(target, str):
target = [target]
assert len(input) == len(
target
assert (
len(input) == len(target)
), f"Arguments must contain the same number of strings, but got len(input)={len(input)} and len(target)={len(target)}"
errors, max_total, target_total, input_total = _get_errors_and_totals(input, target)
return errors - max_total, target_total, input_total
Expand Down
2 changes: 1 addition & 1 deletion torcheval/metrics/synclib.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def send_tensors(


def metrics_traversal_order(
state_dict: Dict[str, Dict[str, TState]]
state_dict: Dict[str, Dict[str, TState]],
) -> List[Tuple[str, str]]:
"""
Args:
Expand Down
Loading

0 comments on commit 2c7dfb3

Please sign in to comment.