Skip to content

Commit

Permalink
[BE]: pyupgrade Python to 3.8 - imports and object inheritance only (p…
Browse files Browse the repository at this point in the history
…ytorch#94308)

Apply parts of pyupgrade to torch (starting with the safest changes).
This PR only does two things: removes the need to inherit from object and removes unused future imports.

Pull Request resolved: pytorch#94308
Approved by: https://github.com/ezyang, https://github.com/albanD
  • Loading branch information
Skylion007 authored and pytorchmergebot committed Feb 7, 2023
1 parent 567e615 commit 8fce9a0
Show file tree
Hide file tree
Showing 243 changed files with 487 additions and 492 deletions.
2 changes: 1 addition & 1 deletion benchmarks/distributed/ddp/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def print_measurements(prefix, nelem, measurements):
return results


class Benchmark(object):
class Benchmark:
def __init__(self, device, distributed_backend, bucket_size):
self.device = device
self.batch_size = 32
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/fastrnns/bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def pretty_print(benchresult, colwidth=16, sep=' '):
return sep.join(items)

# shim for torch.cuda.Event when running on cpu
class Event(object):
class Event:
def __init__(self, enable_timing):
pass

Expand Down
2 changes: 1 addition & 1 deletion benchmarks/framework_overhead_benchmark/C2Module.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def add_blob(ws, blob_name, tensor_size):
blob_tensor = np.random.randn(*tensor_size).astype(np.float32)
ws.FeedBlob(blob_name, blob_tensor)

class C2SimpleNet(object):
class C2SimpleNet:
"""
This module constructs a net with 'op_name' operator. The net consist
a series of such operator.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import torch

class WrapperModule(object):
class WrapperModule:
""" Wraps the instance of wrapped_type.
For graph_mode traces the instance of wrapped_type.
Randomaly initializes num_params tensors with single float element.
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/operator_benchmark/benchmark_caffe2.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"""


class Caffe2BenchmarkBase(object):
class Caffe2BenchmarkBase:
""" This is a base class used to create Caffe2 operator benchmark
"""
tensor_index = 0
Expand Down Expand Up @@ -103,7 +103,7 @@ def extract_inputs_tuple(self):
pass


class Caffe2OperatorTestCase(object):
class Caffe2OperatorTestCase:
""" This class includes all the information needed to benchmark an operator.
op_bench: it's a user-defined class (child of Caffe2BenchmarkBase)
which includes input and operator, .etc
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/operator_benchmark/benchmark_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def _build_test(configs, bench_op, OperatorTestCase, run_backward, op_name_funct
yield _create_test(new_op, test_attrs, tags, OperatorTestCase, run_backward, input_name)


class BenchmarkRunner(object):
class BenchmarkRunner:
"""BenchmarkRunner is responsible for benchmarking all the registered
benchmark test groups.
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/operator_benchmark/benchmark_pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def test_name(self, **kargs):
return name


class PyTorchOperatorTestCase(object):
class PyTorchOperatorTestCase:
""" This class includes all the information needed to benchmark an operator.
op_bench: it's a user-defined class (child of TorchBenchmarkBase)
which includes input and operator, .etc
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/operator_benchmark/benchmark_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def attr_probs(**probs):
return probs


class RandomSample(object):
class RandomSample:

def __init__(self, configs):
self.saved_cum_distribution = {}
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/sparse/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import time

# shim for torch.cuda.Event when running on cpu
class Event(object):
class Event:
def __init__(self, enable_timing):
pass

Expand Down
4 changes: 2 additions & 2 deletions benchmarks/tensorexpr/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import json


class Benchmark(object):
class Benchmark:
def __init__(self, mode, device, dtype):
self.mode = mode
self.deterministic = False
Expand Down Expand Up @@ -238,7 +238,7 @@ def cuda_pointwise_context(loop_levels, block_count, block_size):
torch._C._jit_set_te_cuda_pointwise_block_size(old_block_size)

# Auxiliary class to facilitate dynamic input shape
class DynamicShape(object):
class DynamicShape:
r'''
An Auxiliary class for dynamic shape benchmarks
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/tensorexpr/microbenchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import seaborn as sns
import argparse

class kernel_arena_scope(object):
class kernel_arena_scope:
def __enter__(self):
self.scope = te.KernelScope()

Expand Down
2 changes: 1 addition & 1 deletion benchmarks/tensorexpr/pt_engine.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import torch


class TorchTensorEngine(object):
class TorchTensorEngine:
def rand(self, shape, device=None, dtype=None, requires_grad=False):
return torch.rand(shape, device=device, dtype=dtype, requires_grad=requires_grad)

Expand Down
2 changes: 1 addition & 1 deletion caffe2/contrib/playground/AnyExp.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def initialize_params_from_file(*args, **kwargs):
return checkpoint.initialize_params_from_file(*args, **kwargs)


class AnyExpTrainer(object):
class AnyExpTrainer:

def __init__(self, opts):
import logging
Expand Down
2 changes: 1 addition & 1 deletion caffe2/contrib/playground/meter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from abc import abstractmethod


class Meter(object):
class Meter:

@abstractmethod
def __init__(self, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion caffe2/contrib/tensorboard/tensorboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
# tensorflow<=0.12.1
from tensorflow.train import SummaryWriter as FileWriter

class Config(object):
class Config:
HEIGHT = 600
ASPECT_RATIO = 1.6

Expand Down
2 changes: 1 addition & 1 deletion caffe2/distributed/store_ops_test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from caffe2.python import core, workspace


class StoreOpsTests(object):
class StoreOpsTests:
@classmethod
def _test_set_get(cls, queue, create_store_handler_fn, index, num_procs):
store_handler = create_store_handler_fn()
Expand Down
2 changes: 1 addition & 1 deletion caffe2/experiments/python/device_reduce_sum_bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __new__(metacls, name, bases, class_dict):


@add_metaclass(BenchmarkMeta)
class Benchmark(object):
class Benchmark:

def __init__(self):
self.results = []
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/binarysize.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import sys


class Trie(object):
class Trie:
"""A simple class that represents a Trie."""

def __init__(self, name):
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/caffe_translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def _GetInputDims(caffe_net):
return input_dims


class TranslatorRegistry(object):
class TranslatorRegistry:
registry_ = {}

@classmethod
Expand Down
8 changes: 4 additions & 4 deletions caffe2/python/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def db_name(epoch, node_name, db_prefix, path_prefix=None):
return db_name


class CheckpointManager(object):
class CheckpointManager:
"""
Controls saving and loading of workspaces on every epoch boundary of a job.
If a CheckpointManager instance is passed to JobRunner, then JobRunner will
Expand Down Expand Up @@ -429,7 +429,7 @@ def cp_accessible(self, epoch=None):
return True


class MultiNodeCheckpointManager(object):
class MultiNodeCheckpointManager:
"""
Coordinates checkpointing and checkpointing across multiple nodes.
Each of `init`, `load` and `save` will build TaskGroups which will
Expand Down Expand Up @@ -634,7 +634,7 @@ def cp_accessible(self, epoch=None):
return True


class UploadTaskGroupBuilder(object):
class UploadTaskGroupBuilder:
"""A simple class to upload checkpoints."""
def build(self, epoch, checkpoint_manager):
"""Builds the task group to upload checkpoints.
Expand All @@ -652,7 +652,7 @@ def build(self, epoch, checkpoint_manager):
raise NotImplementedError()


class JobRunner(object):
class JobRunner:
"""
Implement the runtime logic for jobs with checkpointing at the level of
epoch. Can be used to run either single-host or distributed jobs. Job
Expand Down
6 changes: 3 additions & 3 deletions caffe2/python/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import functools


class _ContextInfo(object):
class _ContextInfo:
def __init__(self, cls, allow_default):
self.cls = cls
self.allow_default = allow_default
Expand Down Expand Up @@ -35,7 +35,7 @@ def get_active(self, required=True):
return self._stack[-1]


class _ContextRegistry(object):
class _ContextRegistry:
def __init__(self):
self._ctxs = {}

Expand All @@ -62,7 +62,7 @@ def _get_managed_classes(obj):



class Managed(object):
class Managed:
"""
Managed makes the inheritted class a context managed class.
Expand Down
12 changes: 6 additions & 6 deletions caffe2/python/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def InferOpDeviceAsBlobDevices(op):
GradientSlice = namedtuple('GradientSlice', ['indices', 'values'])


class BlobReference(object):
class BlobReference:
"""A wrapper around a blob in a net.
BlobReference gives us a way to refer to the network that the blob is
Expand Down Expand Up @@ -485,7 +485,7 @@ def GetIndexFromGradientList(g_list, name):
])


class IR(object):
class IR:
"""A simple IR class to keep track of all intermediate representations used
in the gradient computation.
"""
Expand Down Expand Up @@ -1103,7 +1103,7 @@ def GetBackwardPass(self, ys):
return all_gradient_ops, all_input_to_grad_out


class GradientRegistry(object):
class GradientRegistry:
"""GradientRegistry holds the mapping from operators to their gradients."""
gradient_registry_ = {}

Expand Down Expand Up @@ -1444,7 +1444,7 @@ def _recover_record_by_prefix(names, prefix=''):
col_blobs=[_get_blob_ref(prefix + name) for name in column_names])


class Net(object):
class Net:
_net_names_used = set()
operator_registry_ = {}

Expand Down Expand Up @@ -2666,7 +2666,7 @@ def _add_net_to_dict(net_dict, net):
return True


class ExecutionStep(object):
class ExecutionStep:
_step_names_used = set()

@staticmethod
Expand Down Expand Up @@ -2872,7 +2872,7 @@ def add_nets_in_order(step, net_list):
net_list.append(proto.report_net)


class Plan(object):
class Plan:

def __init__(self, name_or_step):
self._plan = caffe2_pb2.PlanDef()
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/crf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""


class CRFWithLoss(object):
class CRFWithLoss:
def __init__(self, model, num_classes, transitions_blob=None):
self.model = model
self.num_classes = num_classes
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/data_parallel_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1304,7 +1304,7 @@ def modify_ops(net):
modify_ops(model.net)


class CollectivesConcurrencyControl(object):
class CollectivesConcurrencyControl:
"""
Creates common worlds (up to max_concurrent_context) and manage the
sequential execution of collectives that shares the same context with
Expand Down
8 changes: 4 additions & 4 deletions caffe2/python/dataio.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import time


class Reader(object):
class Reader:
"""
Reader is an abstract class to be implemented in order to provide
operations capable of iterating through a dataset or stream of data.
Expand Down Expand Up @@ -143,7 +143,7 @@ def execution_step(self, reader_net_name=None, external_should_stop=None):
return (read_step, fields)


class Writer(object):
class Writer:
"""
Writer is an abstract class to be implemented in order to provide
operations capable of feeding a data stream or a dataset.
Expand Down Expand Up @@ -207,7 +207,7 @@ def commit(self, finish_net):
pass


class ReaderBuilder(object):
class ReaderBuilder:
""" Allow usage of a reader in distributed fashion. """
def schema(self):
raise NotImplementedError()
Expand Down Expand Up @@ -256,7 +256,7 @@ def new_reader(self, **kwargs):
return output if isinstance(output, Reader) else output.reader()


class Pipe(object):
class Pipe:
def __init__(self, schema=None, obj_key=None):
self._num_writers = 0
self._num_readers = 0
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def execution_step_with_progress(name, init_net, substeps, rows_read):
report_interval=5)


class Dataset(object):
class Dataset:
"""Represents an in-memory dataset with fixed schema.
Use this to store and iterate through datasets with complex schema that
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/device_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from caffe2.python.core import InferOpBlobDevicesAsDict


class DeviceChecker(object):
class DeviceChecker:
"""A device checker in Python to check consistency across multiple devices.
This is not the most efficient way to check devices, as the Python interface
Expand Down
2 changes: 1 addition & 1 deletion caffe2/python/docs/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from caffe2.python.docs.parser import Parser


class Formatter(object):
class Formatter:
def __init__(self):
self.content = ""

Expand Down
Loading

0 comments on commit 8fce9a0

Please sign in to comment.