Skip to content

Commit 698847a

Browse files
authored
unify indent in examples (#1480)
1 parent 70c8ac0 commit 698847a

File tree

5 files changed

+248
-248
lines changed

5 files changed

+248
-248
lines changed

examples/cpu/features/graph_capture.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@
1111
######################################################
1212

1313
with torch.no_grad():
14-
model(data)
14+
model(data)

examples/cpu/features/int8_recipe_tuning/imagenet_autotune.py

Lines changed: 150 additions & 150 deletions
Original file line numberDiff line numberDiff line change
@@ -6,171 +6,171 @@
66
import intel_extension_for_pytorch as ipex
77

88
model_names = sorted(name for name in models.__dict__
9-
if name.islower() and not name.startswith("__")
10-
and callable(models.__dict__[name]))
9+
if name.islower() and not name.startswith("__")
10+
and callable(models.__dict__[name]))
1111

1212
class AverageMeter(object):
13-
"""Computes and stores the average and current value"""
14-
def __init__(self, name, fmt=':f'):
15-
self.name = name
16-
self.fmt = fmt
17-
self.reset()
18-
19-
def reset(self):
20-
self.val = 0
21-
self.avg = 0
22-
self.sum = 0
23-
self.count = 0
24-
25-
def update(self, val, n=1):
26-
self.val = val
27-
self.sum += val * n
28-
self.count += n
29-
self.avg = self.sum / self.count
30-
31-
def __str__(self):
32-
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
33-
return fmtstr.format(**self.__dict__)
13+
"""Computes and stores the average and current value"""
14+
def __init__(self, name, fmt=':f'):
15+
self.name = name
16+
self.fmt = fmt
17+
self.reset()
18+
19+
def reset(self):
20+
self.val = 0
21+
self.avg = 0
22+
self.sum = 0
23+
self.count = 0
24+
25+
def update(self, val, n=1):
26+
self.val = val
27+
self.sum += val * n
28+
self.count += n
29+
self.avg = self.sum / self.count
30+
31+
def __str__(self):
32+
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
33+
return fmtstr.format(**self.__dict__)
3434

3535
class ProgressMeter(object):
36-
def __init__(self, num_batches, meters, prefix=""):
37-
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
38-
self.meters = meters
39-
self.prefix = prefix
36+
def __init__(self, num_batches, meters, prefix=""):
37+
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
38+
self.meters = meters
39+
self.prefix = prefix
4040

41-
def display(self, batch):
42-
entries = [self.prefix + self.batch_fmtstr.format(batch)]
43-
entries += [str(meter) for meter in self.meters]
44-
print('\t'.join(entries))
41+
def display(self, batch):
42+
entries = [self.prefix + self.batch_fmtstr.format(batch)]
43+
entries += [str(meter) for meter in self.meters]
44+
print('\t'.join(entries))
4545

46-
def _get_batch_fmtstr(self, num_batches):
47-
num_digits = len(str(num_batches // 1))
48-
fmt = '{:' + str(num_digits) + 'd}'
49-
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
46+
def _get_batch_fmtstr(self, num_batches):
47+
num_digits = len(str(num_batches // 1))
48+
fmt = '{:' + str(num_digits) + 'd}'
49+
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
5050

5151
def accuracy(output, target, topk=(1,)):
52-
"""Computes the accuracy over the k top predictions for the specified values of k"""
53-
with torch.no_grad():
54-
maxk = max(topk)
55-
batch_size = target.size(0)
52+
"""Computes the accuracy over the k top predictions for the specified values of k"""
53+
with torch.no_grad():
54+
maxk = max(topk)
55+
batch_size = target.size(0)
5656

57-
_, pred = output.topk(maxk, 1, True, True)
58-
pred = pred.t()
59-
correct = pred.eq(target.view(1, -1).expand_as(pred))
57+
_, pred = output.topk(maxk, 1, True, True)
58+
pred = pred.t()
59+
correct = pred.eq(target.view(1, -1).expand_as(pred))
6060

61-
res = []
62-
for k in topk:
63-
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
64-
res.append(correct_k.mul_(100.0 / batch_size))
65-
return res
61+
res = []
62+
for k in topk:
63+
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
64+
res.append(correct_k.mul_(100.0 / batch_size))
65+
return res
6666

6767
def validate(val_loader, model, criterion, args):
6868

69-
# switch to evaluate mode
70-
model.eval()
71-
72-
def eval_func(model):
73-
batch_time = AverageMeter('Time', ':6.3f')
74-
losses = AverageMeter('Loss', ':.4e')
75-
top1 = AverageMeter('Acc@1', ':6.2f')
76-
top5 = AverageMeter('Acc@5', ':6.2f')
77-
number_iter = len(val_loader)
78-
79-
progress = ProgressMeter(
80-
number_iter,
81-
[batch_time, losses, top1, top5],
82-
prefix='Test: ')
83-
print('Evaluating RESNET: total Steps: {}'.format(number_iter))
84-
with torch.no_grad():
85-
for i, (images, target) in enumerate(val_loader):
86-
images = images.contiguous(memory_format=torch.channels_last)
87-
output = model(images)
88-
loss = criterion(output, target)
89-
# measure accuracy and record loss
90-
acc1, acc5 = accuracy(output, target, topk=(1, 5))
91-
losses.update(loss.item(), images.size(0))
92-
top1.update(acc1[0], images.size(0))
93-
top5.update(acc5[0], images.size(0))
94-
if i % args.print_freq == 0:
95-
progress.display(i)
96-
97-
# TODO: this should also be done with the ProgressMeter
98-
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'
99-
.format(top1=top1, top5=top5))
100-
101-
return top1.avg.item()
102-
103-
print(".........runing calibration step.........")
104-
from torch.ao.quantization import MinMaxObserver, PerChannelMinMaxObserver, QConfig
105-
qconfig = QConfig(
106-
activation=MinMaxObserver.with_args(qscheme=torch.per_tensor_symmetric, dtype=torch.qint8),
107-
weight= PerChannelMinMaxObserver.with_args(dtype=torch.qint8, qscheme=torch.per_channel_symmetric))
108-
x = torch.randn(1, 3, 224, 224)
109-
prepared_model = ipex.quantization.prepare(model, qconfig, x, inplace=True)
110-
with torch.no_grad():
111-
for i, (images, target) in enumerate(val_loader):
112-
images = images.contiguous(memory_format=torch.channels_last)
113-
prepared_model(images)
114-
if i == 4:
115-
break
116-
print(".........calibration step done.........")
117-
118-
print(".........runing autotuning step.........")
119-
tuned_model = ipex.quantization.autotune(prepared_model, val_loader, eval_func, sampling_sizes=[300])
120-
print(".........autotuning step done.........")
121-
122-
print(".........runing int8 inference.........")
123-
converted_model = ipex.quantization.convert(tuned_model)
69+
# switch to evaluate mode
70+
model.eval()
71+
72+
def eval_func(model):
73+
batch_time = AverageMeter('Time', ':6.3f')
74+
losses = AverageMeter('Loss', ':.4e')
75+
top1 = AverageMeter('Acc@1', ':6.2f')
76+
top5 = AverageMeter('Acc@5', ':6.2f')
77+
number_iter = len(val_loader)
78+
79+
progress = ProgressMeter(
80+
number_iter,
81+
[batch_time, losses, top1, top5],
82+
prefix='Test: ')
83+
print('Evaluating RESNET: total Steps: {}'.format(number_iter))
12484
with torch.no_grad():
125-
for i, (images, target) in enumerate(val_loader):
126-
images = images.contiguous(memory_format=torch.channels_last)
127-
traced_model = torch.jit.trace(converted_model, images)
128-
traced_model = torch.jit.freeze(traced_model)
129-
break
130-
131-
eval_func(traced_model)
132-
133-
return
85+
for i, (images, target) in enumerate(val_loader):
86+
images = images.contiguous(memory_format=torch.channels_last)
87+
output = model(images)
88+
loss = criterion(output, target)
89+
# measure accuracy and record loss
90+
acc1, acc5 = accuracy(output, target, topk=(1, 5))
91+
losses.update(loss.item(), images.size(0))
92+
top1.update(acc1[0], images.size(0))
93+
top5.update(acc5[0], images.size(0))
94+
if i % args.print_freq == 0:
95+
progress.display(i)
96+
97+
# TODO: this should also be done with the ProgressMeter
98+
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'
99+
.format(top1=top1, top5=top5))
100+
101+
return top1.avg.item()
102+
103+
print(".........runing calibration step.........")
104+
from torch.ao.quantization import MinMaxObserver, PerChannelMinMaxObserver, QConfig
105+
qconfig = QConfig(
106+
activation=MinMaxObserver.with_args(qscheme=torch.per_tensor_symmetric, dtype=torch.qint8),
107+
weight= PerChannelMinMaxObserver.with_args(dtype=torch.qint8, qscheme=torch.per_channel_symmetric))
108+
x = torch.randn(1, 3, 224, 224)
109+
prepared_model = ipex.quantization.prepare(model, qconfig, x, inplace=True)
110+
with torch.no_grad():
111+
for i, (images, target) in enumerate(val_loader):
112+
images = images.contiguous(memory_format=torch.channels_last)
113+
prepared_model(images)
114+
if i == 4:
115+
break
116+
print(".........calibration step done.........")
117+
118+
print(".........runing autotuning step.........")
119+
tuned_model = ipex.quantization.autotune(prepared_model, val_loader, eval_func, sampling_sizes=[300])
120+
print(".........autotuning step done.........")
121+
122+
print(".........runing int8 inference.........")
123+
converted_model = ipex.quantization.convert(tuned_model)
124+
with torch.no_grad():
125+
for i, (images, target) in enumerate(val_loader):
126+
images = images.contiguous(memory_format=torch.channels_last)
127+
traced_model = torch.jit.trace(converted_model, images)
128+
traced_model = torch.jit.freeze(traced_model)
129+
break
130+
131+
eval_func(traced_model)
132+
133+
return
134134

135135
def main(args):
136-
print("=> using pre-trained model '{}'".format(args.arch))
137-
model = models.__dict__[args.arch](pretrained=True)
138-
139-
assert args.data != None, "please set dataset path if you want to using real data"
140-
valdir = os.path.join(args.data, 'val')
141-
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
142-
std=[0.229, 0.224, 0.225])
143-
criterion = torch.nn.CrossEntropyLoss()
144-
145-
val_loader = torch.utils.data.DataLoader(
146-
datasets.ImageFolder(valdir, transforms.Compose([
147-
transforms.Resize(256),
148-
transforms.CenterCrop(224),
149-
transforms.ToTensor(),
150-
normalize,
151-
])),
152-
batch_size=args.batch_size, shuffle=False,
153-
num_workers=args.workers, pin_memory=True)
154-
155-
validate(val_loader, model, criterion, args)
136+
print("=> using pre-trained model '{}'".format(args.arch))
137+
model = models.__dict__[args.arch](pretrained=True)
138+
139+
assert args.data != None, "please set dataset path if you want to using real data"
140+
valdir = os.path.join(args.data, 'val')
141+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
142+
std=[0.229, 0.224, 0.225])
143+
criterion = torch.nn.CrossEntropyLoss()
144+
145+
val_loader = torch.utils.data.DataLoader(
146+
datasets.ImageFolder(valdir, transforms.Compose([
147+
transforms.Resize(256),
148+
transforms.CenterCrop(224),
149+
transforms.ToTensor(),
150+
normalize,
151+
])),
152+
batch_size=args.batch_size, shuffle=False,
153+
num_workers=args.workers, pin_memory=True)
154+
155+
validate(val_loader, model, criterion, args)
156156

157157
if __name__ == '__main__':
158-
import argparse
159-
parser = argparse.ArgumentParser()
160-
parser.add_argument('data', metavar='DIR', nargs='?', default='imagenet',
161-
help='path to dataset (default: imagenet)')
162-
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',
163-
choices=model_names,
164-
help='model architecture: ' +
165-
' | '.join(model_names) +
166-
' (default: resnet18)')
167-
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
168-
help='number of data loading workers (default: 4)')
169-
parser.add_argument('-b', '--batch-size', default=56, type=int,
170-
metavar='N',
171-
help='mini-batch size (default: 256), this is the total '
172-
'batch size of all GPUs on the current node when '
173-
'using Data Parallel or Distributed Data Parallel')
174-
parser.add_argument('-p', '--print-freq', default=10, type=int,
175-
metavar='N', help='print frequency (default: 10)')
176-
main(parser.parse_args())
158+
import argparse
159+
parser = argparse.ArgumentParser()
160+
parser.add_argument('data', metavar='DIR', nargs='?', default='imagenet',
161+
help='path to dataset (default: imagenet)')
162+
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',
163+
choices=model_names,
164+
help='model architecture: ' +
165+
' | '.join(model_names) +
166+
' (default: resnet18)')
167+
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
168+
help='number of data loading workers (default: 4)')
169+
parser.add_argument('-b', '--batch-size', default=56, type=int,
170+
metavar='N',
171+
help='mini-batch size (default: 256), this is the total '
172+
'batch size of all GPUs on the current node when '
173+
'using Data Parallel or Distributed Data Parallel')
174+
parser.add_argument('-p', '--print-freq', default=10, type=int,
175+
metavar='N', help='print frequency (default: 10)')
176+
main(parser.parse_args())

0 commit comments

Comments
 (0)