python_code
stringlengths 0
258k
|
---|
from abc import ABC, abstractmethod
from typing import Any, Callable
from torch.utils.benchmark import Timer
from torch.utils._pytree import tree_flatten
class BenchmarkCase(ABC):
@abstractmethod
def name(self) -> str:
pass
@abstractmethod
def run(self) -> Callable:
pass
def time(fn: Callable, test_runs: int) -> float:
t = Timer(stmt="fn()", globals={"fn": fn})
times = t.blocked_autorange()
return times.median * 1000 # time in ms
def benchmark(case: BenchmarkCase, warmup_runs: int = 10, test_runs: int = 20) -> float:
for _ in range(warmup_runs):
case.run()
return time(case.run, test_runs)
|
import torch
from ..utils import dump_output
from .cases import benchmark_cases
from .util import benchmark
import pprint
from typing import List
BM_NAME = 'functorch'
def run_benchmarks():
metrics = {}
for case_ctor in benchmark_cases:
case = case_ctor()
runtime_ms = benchmark(case)
metrics[case.name()] = runtime_ms
return metrics
def run(args: List[str]):
metrics = run_benchmarks()
result = {
'name': BM_NAME,
'environ': {
'pytorch_git_version': torch.version.git_version,
},
'metrics': metrics,
}
pprint.pprint(result)
dump_output(BM_NAME, result)
|
from .util import BenchmarkCase
from torchbenchmark.models.lennard_jones import Model as LJModel
from torchbenchmark.models.functorch_maml_omniglot import Model as FTMamlOmniglot
from torchbenchmark.models.functorch_dp_cifar10 import Model as FTDPCifar10
from .vmap_hessian_fc import VmapHessianFC
from .simple_models import (
SimpleCNN,
SimpleMLP,
VmapWrapper,
EnsembleMultiWrapper,
EnsembleSingleWrapper,
PerSampleGradWrapper,
)
class TorchBenchModelWrapper(BenchmarkCase):
def __init__(self, name, model, device):
self.model = model('train', device)
self.name_ = f'{name}_{device}'
def name(self):
return self.name_
def run(self):
return self.model.train()
# functorch user benchmark
# ------------------------
# This userbenchmark is used for regression testing of:
# - microbenchmarks,
# - low-quality models that shouldn't go into torchbenchmark
# - pieces of models where we do not have access to the full model.
# - models in torchbenchmark that have not yet made it to a release branch
# (and therefore are not being tracked for regressions).
#
# When adding a functorch-related benchmark, please prefer finding a high-quality
# model that uses the benchmark and adding it to the torchbenchmark suite.
# There is better infra support there and other folks use those models
# for cross-cutting tests.
benchmark_cases = [
# [models from torchbench that haven't made it to stable yet]
lambda: TorchBenchModelWrapper('lennard_jones', LJModel, 'cpu'),
lambda: TorchBenchModelWrapper('lennard_jones', LJModel, 'cuda'),
lambda: TorchBenchModelWrapper('functorch_maml_omniglot', FTMamlOmniglot, 'cpu'),
lambda: TorchBenchModelWrapper('functorch_maml_omniglot', FTMamlOmniglot, 'cuda'),
lambda: TorchBenchModelWrapper('functorch_dp_cifar10', FTDPCifar10, 'cuda'),
# end [models from torchbench that haven't made it to stable yet]
VmapHessianFC,
# [combinations from functorch tutorials]
lambda: VmapWrapper(SimpleMLP, 'cpu'),
lambda: VmapWrapper(SimpleMLP, 'cuda'),
lambda: EnsembleMultiWrapper(SimpleMLP, 'cpu'),
lambda: EnsembleMultiWrapper(SimpleMLP, 'cuda'),
lambda: EnsembleMultiWrapper(SimpleCNN, 'cuda'),
lambda: EnsembleSingleWrapper(SimpleMLP, 'cpu'),
lambda: EnsembleSingleWrapper(SimpleMLP, 'cuda'),
lambda: EnsembleSingleWrapper(SimpleCNN, 'cuda'),
lambda: PerSampleGradWrapper(SimpleMLP, 'cpu'),
lambda: PerSampleGradWrapper(SimpleMLP, 'cuda'),
lambda: PerSampleGradWrapper(SimpleCNN, 'cuda'),
# end [combinations from functorch tutorials]
]
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from functorch import vmap, grad, combine_state_for_ensemble, make_functional_with_buffers
import functools
from .util import BenchmarkCase
class SimpleMLP(nn.Module):
def __init__(self):
super(SimpleMLP, self).__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, 10)
def forward(self, x):
x = x.flatten(1)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
@classmethod
def make_input(cls, bs=None):
shape = [64, 1, 28, 28]
if bs is None:
return torch.randn(*shape)
return torch.randn(bs, *shape)
@classmethod
def make_target(cls, bs=None):
shape = [64]
if bs is None:
return torch.randint(10, shape)
return torch.randn(10, [bs] + shape)
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
output = x
return output
@classmethod
def make_input(cls, bs=None):
shape = [64, 1, 28, 28]
if bs is None:
return torch.randn(*shape)
return torch.randn(bs, *shape)
@classmethod
def make_target(cls, bs=None):
shape = [64]
if bs is None:
return torch.randint(10, shape)
return torch.randn(10, [bs] + shape)
class VmapWrapper(BenchmarkCase):
def __init__(self, model_cls, device):
self.name_ = f'{model_cls.__name__}_vmap_{device}'
self.model = model_cls().to(device)
self.inputs = model_cls.make_input().to(device)
def name(self):
return self.name_
def run(self):
vmap(self.model)(self.inputs)
def ensemble_setup(self, model_cls, device):
num_models = 10
models = [model_cls().to(device) for _ in range(num_models)]
fmodel, params, buffers = combine_state_for_ensemble(models)
self.fmodel = fmodel
self.params = params
self.buffers = buffers
self.inputs = model_cls.make_input(num_models).to(device)
class EnsembleMultiWrapper(BenchmarkCase):
def __init__(self, model_cls, device):
self.name_ = f'{model_cls.__name__}_ensemble_multi_{device}'
ensemble_setup(self, model_cls, device)
def name(self):
return self.name_
def run(self):
vmap(self.fmodel)(self.params, self.buffers, self.inputs)
class EnsembleSingleWrapper(BenchmarkCase):
def __init__(self, model_cls, device):
self.name_ = f'{model_cls.__name__}_ensemble_single_{device}'
ensemble_setup(self, model_cls, device)
self.inputs = self.inputs[0]
def name(self):
return self.name_
def run(self):
vmap(self.fmodel, (0, 0, None))(self.params, self.buffers, self.inputs)
def loss_fn(predictions, targets):
return F.nll_loss(predictions, targets)
def compute_loss(fmodel, params, buffers, sample, target):
sample = sample.unsqueeze(0) # prepend batch dimension for processing
target = target.unsqueeze(0)
prediction = fmodel(params, buffers, sample)
return loss_fn(prediction, target)
class PerSampleGradWrapper(BenchmarkCase):
def __init__(self, model_cls, device):
self.name_ = f'{model_cls.__name__}_persamplegrad_{device}'
model = model_cls().to(device)
self.model = make_functional_with_buffers(model)
self.inputs = model_cls.make_input().to(device)
self.targets = model_cls.make_target().to(device)
def name(self):
return self.name_
def run(self):
fmodel, params, buffers = self.model
loss = functools.partial(compute_loss, fmodel)
vmap(grad(loss), (None, None, 0, 0))(params, buffers, self.inputs, self.targets)
|
import torch
import argparse
import json
import os
import time
import torch.utils.jit.log_extract as log_extract
from datetime import datetime
from typing import Any, List
def parse_fusers(extra_args: List[str]):
parser = argparse.ArgumentParser()
parser.add_argument(
"--fusers",
nargs="*",
default=[],
choices=["no_fuser", "fuser0", "fuser1", "fuser2"],
help="List of fusers to run tests on")
parser.add_argument("--filters", nargs="*", default=[], help='List of fuser microbenchmarks to test')
parser.add_argument("--output", help="specifiy the output file name")
args = parser.parse_args(extra_args)
return args
class NVFuserBenchmark():
def __init__(self, name, ir, warmup_runs=10, test_runs=20):
self.name = name
self.ir = ir
self.warmup_runs = warmup_runs
self.test_runs = test_runs
def run_test(self, inputs, fuser_name: str) -> float:
if fuser_name == "no_fuser":
return log_extract.run_baseline_no_fusion(self.ir, inputs)
elif fuser_name == "nnc-static":
return log_extract.run_nnc(self.ir, inputs, dynamic=False)
elif fuser_name == "nnc-dynamic" or fuser_name == "fuser1":
return log_extract.run_nnc(self.ir, inputs, dynamic=True)
elif fuser_name == "fuser2" or fuser_name == "nvfuser":
return log_extract.run_nvfuser(self.ir, inputs)
assert False
def get_inputs(self) -> List[Any]:
_, inputs = log_extract.load_graph_and_inputs(self.ir)
return inputs
def dump_metrics(metrics, output_name):
output = {
"name": "nvfuser",
"environ": {"pytorch_git_version": torch.version.git_version},
"metrics": metrics,
}
current_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.normpath(os.path.join(current_dir, "../../.userbenchmark/nvfuser/"))
os.makedirs(target_dir, exist_ok=True)
fname = "metrics-{}.json".format(datetime.fromtimestamp(time.time()).strftime("%Y%m%d%H%M%S"))
full_fname = os.path.join(target_dir, fname)
if output_name is not None:
full_fname = output_name
with open(full_fname, 'w') as f:
json.dump(output, f, indent=4)
def run_nvfuser_microbenchmarks(extra_args: List[str]):
from userbenchmark.nvfuser.ir import ir_list
benchmarks = [NVFuserBenchmark(name, ir) for name, ir in ir_list]
args = parse_fusers(extra_args)
filters, fusers = args.filters, args.fusers
if len(filters) > 0:
benchmarks = [x for x in benchmarks if x.name in filters]
if len(fusers) == 0:
fusers = ["no_fuser", "nnc-static", "nnc-dynamic", "nvfuser"]
metrics = {}
for b in benchmarks:
outputs = []
for fuser in fusers:
inputs = b.get_inputs()
runtime = b.run_test(inputs, fuser)
outputs.append((fuser, runtime))
metrics[f"{fuser}:{b.name}"] = runtime
print(f"{b.name}:", "; ".join(f"{name} = {time:.3f} ms" for name, time in outputs))
dump_metrics(metrics, args.output)
def run(args: List[str]):
run_nvfuser_microbenchmarks(extra_args=args)
|
# contains the list of microbenchmark strings
# format: list of tuples (name, IR)
ir_list = [("autogen-0", """graph(%0 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(4096, 512, strides=[512, 1], requires_grad=0, device=cuda:0),
%2 : int):
%3 : int[] = prim::Constant[value=[4096, 512]]()
%4 : int[] = prim::Constant[value=[1, 4096, 512]]()
%5 : Float(1, 4096, 512, strides=[2097152, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %4)
%6 : Float(1, 4096, 512, strides=[2097152, 512, 1], requires_grad=0, device=cuda:0) = aten::add(%5, %0, %2)
%7 : Float(4096, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%6, %3)
%8 : Float(1, 4096, 512, strides=[2097152, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %4)
%9 : Float(1, 4096, 512, strides=[2097152, 512, 1], requires_grad=0, device=cuda:0) = aten::relu(%8)
%10 : Float(4096, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %3)
return (%10)
"""), ("autogen-1", """graph(%0 : Float(1, 12, 4096, 64, strides=[3145728, 64, 768, 1], requires_grad=0, device=cuda:0),
%1 : Float(requires_grad=0, device=cuda:0)):
%2 : int[] = prim::Constant[value=[1, 12, 64, 64, 64]]()
%3 : Float(1, 12, 4096, 64, strides=[3145728, 64, 768, 1], requires_grad=0, device=cuda:0) = aten::div(%0, %1)
%4 : Float(1, 12, 64, 64, 64, strides=[768, 64, 49152, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %2)
return (%4)
"""), ("autogen-2", """graph(%0 : Float(8, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0),
%1 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(8, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0),
%6 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%8 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%9 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%10 : int):
%11 : float = prim::Constant[value=1.0000000000000001e-05]()
%12 : float = prim::Constant[value=0.10000000000000001]()
%13 : bool = prim::Constant[value=0]()
%14 : Float(8, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0), %15 : Tensor, %16 : Tensor = aten::native_batch_norm(%5, %6, %7, %8, %9, %13, %12, %11)
%17 : Float(8, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0), %18 : Tensor, %19 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %13, %12, %11)
%20 : Float(8, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0) = aten::add(%17, %14, %10)
%21 : Float(8, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0) = aten::relu(%20)
return (%21)
"""), ("autogen-3", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%5 : Double(requires_grad=0, device=cuda:0),
%6 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%7 : Double(requires_grad=0, device=cuda:0),
%8 : Double(requires_grad=0, device=cuda:0),
%9 : Double(requires_grad=0, device=cuda:0),
%10 : Double(requires_grad=0, device=cuda:0),
%11 : Double(requires_grad=0, device=cuda:0),
%12 : Double(requires_grad=0, device=cuda:0),
%13 : Double(requires_grad=0, device=cuda:0),
%14 : Double(requires_grad=0, device=cuda:0),
%15 : Double(requires_grad=0, device=cuda:0),
%16 : Double(requires_grad=0, device=cuda:0),
%17 : Double(requires_grad=0, device=cuda:0),
%18 : Double(requires_grad=0, device=cuda:0),
%19 : Double(requires_grad=0, device=cuda:0),
%20 : Double(requires_grad=0, device=cuda:0),
%21 : Double(requires_grad=0, device=cuda:0),
%22 : Double(requires_grad=0, device=cuda:0),
%23 : Double(1, 1, 26, strides=[26, 26, 1], requires_grad=0, device=cuda:0),
%24 : Double(requires_grad=0, device=cuda:0),
%25 : Double(requires_grad=0, device=cuda:0),
%26 : Double(requires_grad=0, device=cuda:0),
%27 : int,
%28 : int,
%29 : int,
%30 : int,
%31 : int,
%32 : int,
%33 : int,
%34 : int,
%35 : int,
%36 : int,
%37 : int,
%38 : int,
%39 : int,
%40 : int,
%41 : int,
%42 : int,
%43 : int,
%44 : int,
%45 : int,
%46 : int,
%47 : int,
%48 : int,
%49 : int,
%50 : int,
%51 : int,
%52 : int,
%53 : int,
%54 : int,
%55 : int,
%56 : int,
%57 : int,
%58 : int,
%59 : int,
%60 : int,
%61 : int,
%62 : int,
%63 : int,
%64 : int,
%65 : int,
%66 : int):
%67 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %16)
%68 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%67, %12)
%69 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %26)
%70 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %25)
%71 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%70, %10, %66)
%72 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %71)
%73 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%72, %24, %65)
%74 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%73, %69, %64)
%75 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%74, %23)
%76 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %22)
%77 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%76, %9, %63)
%78 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %77)
%79 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%78, %8, %62)
%80 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %79)
%81 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%80, %21, %61)
%82 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sqrt(%6)
%83 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%82, %81)
%84 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %20)
%85 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%84, %7, %60)
%86 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %85)
%87 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%86, %19, %59)
%88 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%87, %83, %58)
%89 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %88)
%90 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %18)
%91 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%90, %5, %57)
%92 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %91)
%93 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%92, %3, %56)
%94 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %93)
%95 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%94, %17, %55)
%96 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%95, %89, %54)
%97 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%96, %74)
%98 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %16)
%99 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%98, %15, %53)
%100 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %99)
%101 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%100, %12)
%102 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %14)
%103 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%102, %13, %52)
%104 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %103)
%105 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%104, %12)
%106 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%105, %11, %51)
%107 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%106, %101, %50)
%108 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::pow(%107, %49)
%109 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%108, %97, %48)
%110 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sqrt(%109)
%111 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%105, %11, %47)
%112 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%111, %101, %46)
%113 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%112, %110, %45)
%114 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%113, %75, %44)
%115 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::reciprocal(%114)
%116 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%115, %2)
%117 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%105, %11, %43)
%118 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%117, %101, %42)
%119 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%118, %110, %41)
%120 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::reciprocal(%119)
%121 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%120, %2)
%122 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%110, %121)
%123 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%122, %116)
%124 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%75, %0)
%125 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%124, %123)
%126 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%125, %2, %40)
%127 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%70, %0)
%128 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%127, %10, %39)
%129 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%76, %0)
%130 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%129, %9, %38)
%131 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %130)
%132 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%78, %8, %37)
%133 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%132, %131, %36)
%134 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%82, %133)
%135 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%84, %0)
%136 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%135, %7, %35)
%137 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%136, %134, %34)
%138 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %137)
%139 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%90, %0)
%140 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%139, %5, %33)
%141 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %140)
%142 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%92, %3, %32)
%143 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%142, %141, %31)
%144 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%143, %138, %30)
%145 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%144, %74)
%146 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%102, %2)
%147 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%146, %1, %29)
%148 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%147, %68, %28)
%149 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%107, %0)
%150 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%149, %148)
%151 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%150, %145, %27)
return (%151, %148, %146, %144, %128, %126, %123, %121, %119, %116, %114, %110, %109, %108, %107, %104, %102, %100, %96, %82, %75, %74, %68, %67)
"""), ("batchnorm-silu", """graph(%0 : Float(32, 480, 14, 14, strides=[94080, 196, 14, 1], requires_grad=0, device=cuda:0),
%1 : Float(480, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(480, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(480, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(480, strides=[1], requires_grad=0, device=cuda:0)):
%5 : float = prim::Constant[value=1.0000000000000001e-05]()
%6 : float = prim::Constant[value=0.10000000000000001]()
%7 : bool = prim::Constant[value=0]()
%8 : Float(32, 480, 14, 14, strides=[94080, 196, 14, 1], requires_grad=0, device=cuda:0), %9 : Tensor, %10 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %7, %6, %5)
%11 : Float(32, 480, 14, 14, strides=[94080, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::silu(%8)
return (%11)
"""), ("autogen-4", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0),
%3 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(4096, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : float = prim::Constant[value=9.9999999999999998e-13]()
%8 : int[] = prim::Constant[value=[768]]()
%9 : int[] = prim::Constant[value=[4096, 768]]()
%10 : int[] = prim::Constant[value=[1, 4096, 768]]()
%11 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %10)
%12 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %3, %6)
%13 : Float(4096, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %9)
%14 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %10)
%15 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%14, %2, %5)
%16 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0), %17 : Tensor, %18 : Tensor = aten::native_layer_norm(%15, %8, %0, %1, %7)
%19 : Float(4096, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %9)
return (%19)
"""), ("autogen-5", """graph(%0 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0),
%1 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0),
%6 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%8 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%9 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%10 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0),
%11 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%12 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%13 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%14 : Float(160, strides=[1], requires_grad=0, device=cuda:0),
%15 : int,
%16 : int):
%17 : float = prim::Constant[value=1.0000000000000001e-05]()
%18 : float = prim::Constant[value=0.10000000000000001]()
%19 : bool = prim::Constant[value=0]()
%20 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0), %21 : Tensor, %22 : Tensor = aten::native_batch_norm(%10, %11, %12, %13, %14, %19, %18, %17)
%23 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0), %24 : Tensor, %25 : Tensor = aten::native_batch_norm(%5, %6, %7, %8, %9, %19, %18, %17)
%26 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0), %27 : Tensor, %28 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %19, %18, %17)
%29 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::add(%26, %23, %16)
%30 : Float(96, 160, 7, 7, strides=[7840, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::add(%29, %20, %15)
return (%30)
"""), ("autogen-6", """graph(%0 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%5 : Double(requires_grad=0, device=cuda:0),
%6 : Double(requires_grad=0, device=cuda:0),
%7 : Double(requires_grad=0, device=cuda:0),
%8 : Double(requires_grad=0, device=cuda:0),
%9 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%10 : Double(requires_grad=0, device=cuda:0),
%11 : Double(requires_grad=0, device=cuda:0),
%12 : Double(requires_grad=0, device=cuda:0),
%13 : Double(requires_grad=0, device=cuda:0),
%14 : Double(requires_grad=0, device=cuda:0),
%15 : Double(requires_grad=0, device=cuda:0),
%16 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%17 : Double(requires_grad=0, device=cuda:0),
%18 : Double(requires_grad=0, device=cuda:0),
%19 : Double(requires_grad=0, device=cuda:0),
%20 : Double(requires_grad=0, device=cuda:0),
%21 : Double(requires_grad=0, device=cuda:0),
%22 : Double(requires_grad=0, device=cuda:0),
%23 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%24 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%25 : Double(requires_grad=0, device=cuda:0),
%26 : Double(requires_grad=0, device=cuda:0),
%27 : Double(requires_grad=0, device=cuda:0),
%28 : Double(requires_grad=0, device=cuda:0),
%29 : Double(requires_grad=0, device=cuda:0),
%30 : Double(requires_grad=0, device=cuda:0),
%31 : Double(requires_grad=0, device=cuda:0),
%32 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%33 : Double(requires_grad=0, device=cuda:0),
%34 : Double(requires_grad=0, device=cuda:0),
%35 : Double(requires_grad=0, device=cuda:0),
%36 : Double(requires_grad=0, device=cuda:0),
%37 : Double(requires_grad=0, device=cuda:0),
%38 : Double(requires_grad=0, device=cuda:0),
%39 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%40 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%41 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%42 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%43 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%44 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%45 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%46 : Double(requires_grad=0, device=cuda:0),
%47 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%48 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%49 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%50 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%51 : Double(1, 1, 26, strides=[26, 26, 1], requires_grad=0, device=cuda:0),
%52 : int,
%53 : int,
%54 : int,
%55 : int,
%56 : int,
%57 : int,
%58 : int,
%59 : int,
%60 : int,
%61 : int,
%62 : int,
%63 : int,
%64 : int,
%65 : int,
%66 : int,
%67 : int,
%68 : int,
%69 : int,
%70 : int,
%71 : int,
%72 : int,
%73 : int,
%74 : int,
%75 : int,
%76 : int,
%77 : int,
%78 : int,
%79 : int,
%80 : int,
%81 : int,
%82 : int,
%83 : int,
%84 : int,
%85 : int,
%86 : int,
%87 : int,
%88 : int,
%89 : int,
%90 : int,
%91 : int,
%92 : int,
%93 : int,
%94 : int):
%95 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%50, %51)
%96 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%24, %50)
%97 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%49, %96, %94)
%98 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::reciprocal(%47)
%99 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%98, %3)
%100 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%99, %97)
%101 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::div(%100, %22)
%102 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%45, %46, %93)
%103 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%102, %44, %92)
%104 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%103, %101, %91)
%105 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%104, %95, %90)
%106 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::pow(%48, %89)
%107 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%42, %47)
%108 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%107, %22)
%109 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%108, %41)
%110 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::div(%109, %106)
%111 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%110, %105)
%112 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%45, %46, %88)
%113 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%112, %44, %87)
%114 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%113, %101, %86)
%115 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::pow(%43, %85)
%116 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::div(%108, %115)
%117 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%116, %40)
%118 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%117, %114)
%119 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%42, %99)
%120 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%119, %41)
%121 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%120, %40)
%122 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%121, %97)
%123 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%95, %22)
%124 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%123, %39)
%125 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%124, %122, %84)
%126 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%125, %118, %83)
%127 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%126, %111, %82)
%128 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::reciprocal(%2)
%129 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%128, %3)
%130 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%9, %38)
%131 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %37)
%132 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%131, %36, %81)
%133 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%132, %130, %80)
%134 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %133)
%135 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%134, %35, %79)
%136 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%135, %22)
%137 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%136, %23)
%138 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %34)
%139 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%138, %33, %78)
%140 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%139, %24)
%141 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%139, %32)
%142 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%141, %31)
%143 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%142, %129)
%144 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%143, %140, %77)
%145 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%144, %137, %76)
%146 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%145, %129)
%147 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %30)
%148 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%147, %29, %75)
%149 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%9, %148)
%150 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %28)
%151 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%150, %27, %74)
%152 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %151)
%153 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%152, %26, %73)
%154 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %153)
%155 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%154, %25, %72)
%156 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%155, %149, %71)
%157 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%156, %146, %70)
%158 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%157, %23)
%159 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%135, %24)
%160 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%23, %129)
%161 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%140, %22)
%162 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%161, %160)
%163 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%162, %159, %69)
%164 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%163, %129)
%165 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %21)
%166 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%165, %20, %68)
%167 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %166)
%168 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%167, %19, %67)
%169 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %168)
%170 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%169, %18, %66)
%171 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %170)
%172 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%171, %17, %65)
%173 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%16, %172)
%174 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%9, %15)
%175 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %14)
%176 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%175, %13, %64)
%177 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %176)
%178 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%177, %12, %63)
%179 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %178)
%180 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%179, %11, %62)
%181 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %180)
%182 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%181, %10, %61)
%183 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%182, %174, %60)
%184 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%183, %173, %59)
%185 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%9, %184)
%186 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %8)
%187 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%186, %7, %58)
%188 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %187)
%189 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%188, %6, %57)
%190 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %189)
%191 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%190, %5, %56)
%192 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %191)
%193 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%192, %3, %55)
%194 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%193, %185, %54)
%195 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%194, %164, %53)
%196 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%195, %2)
%197 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%196, %158, %52)
%198 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%197, %129)
%199 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%198, %1)
%200 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%199, %99)
%201 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%200, %127)
%202 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::div(%201, %0)
return (%202, %198, %197, %195, %190, %188, %186, %179, %177, %175, %169, %167, %165, %163, %161, %160, %157, %152, %150, %145, %142, %139, %136, %135, %134, %131, %130, %129, %99, %97, %95)
"""), ("autogen-7", """graph(%0 : Float(8, 197, 6, 64, strides=[75648, 64, 12608, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[1576, 384]]()
%2 : int[] = prim::Constant[value=[8, 197, 384]]()
%3 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %2)
%4 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %1)
return (%4)
"""), ("autogen-8", """graph(%0 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%1 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%2 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%3 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%4 : Double(requires_grad=0, device=cuda:0),
%5 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0)):
%6 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::log(%5)
%7 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%3, %4)
%8 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::div(%7, %2)
%9 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::div(%8, %1)
%10 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%9, %6)
%11 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%10, %0)
return (%11, %6)
"""), ("autogen-9", """graph(%0 : Float(1, 12, 1, 64, 64, strides=[768, 64, 49152, 768, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[1, 12, 64, 64, 1, 1]]()
%2 : int[] = prim::Constant[value=[1, 12, 64, 64, 1]]()
%3 : int[] = prim::Constant[value=[1, 12, 64, 64]]()
%4 : Float(1, 12, 64, 64, strides=[768, 64, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %3)
%5 : Float(1, 12, 64, 64, 1, strides=[768, 64, 768, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %2)
%6 : Float(1, 12, 64, 64, 1, 1, strides=[768, 64, 768, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%5, %1)
return (%6, %4)
"""), ("autogen-10", """graph(%0 : Long(1, 1, 26, strides=[26, 26, 1], requires_grad=0, device=cuda:0),
%1 : Long(200, 200, strides=[200, 1], requires_grad=0, device=cuda:0)):
%2 : int[] = prim::Constant[value=[200, 200, 1]]()
%3 : Long(200, 200, 1, strides=[200, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %2)
%4 : Bool(200, 200, 26, strides=[5200, 26, 1], requires_grad=0, device=cuda:0) = aten::ge(%0, %3)
return (%4)
"""), ("autogen-11", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%2 : int):
%3 : int[] = prim::Constant[value=[1, 512, 12, 64]]()
%4 : int[] = prim::Constant[value=[512, 768]]()
%5 : int[] = prim::Constant[value=[1, 512, 768]]()
%6 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %5)
%7 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%6, %0, %2)
%8 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %4)
%9 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%8, %5)
%10 : Float(1, 512, 12, 64, strides=[393216, 768, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %3)
return (%10)
"""), ("autogen-12", """graph(%0 : Float(32, 360, 14, 14, strides=[70560, 196, 14, 1], requires_grad=0, device=cuda:0),
%1 : Float(32, 360, 1, 1, strides=[360, 1, 1, 1], requires_grad=0, device=cuda:0)):
%2 : Float(32, 360, 1, 1, strides=[360, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::sigmoid(%1)
%3 : Float(32, 360, 14, 14, strides=[70560, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::mul(%0, %2)
return (%3)
"""), ("autogen-13", """graph(%0 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(32, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0),
%5 : Float(256, strides=[1], requires_grad=0, device=cuda:0)):
%6 : float = prim::Constant[value=1.0000000000000001e-05]()
%7 : float = prim::Constant[value=0.10000000000000001]()
%8 : bool = prim::Constant[value=0]()
%9 : int[] = prim::Constant[value=[1, 256, 1, 1]]()
%10 : Float(1, 256, 1, 1, strides=[256, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%5, %9)
%11 : Float(32, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0) = aten::div(%4, %10)
%12 : Float(32, 256, 56, 56, strides=[802816, 3136, 56, 1], requires_grad=0, device=cuda:0), %13 : Tensor, %14 : Tensor = aten::native_batch_norm(%11, %0, %1, %2, %3, %8, %7, %6)
return (%12, %13, %14)
"""), ("autogen-14", """graph(%0 : Float(8, 2048, 2048, strides=[4194304, 2048, 1], requires_grad=0, device=cuda:0),
%1 : Float(8, 2048, 2048, strides=[1, 16384, 8], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 1, 2048, 2048, strides=[4194304, 4194304, 2048, 1], requires_grad=0, device=cuda:0),
%5 : Float(1, 1, 1, 2048, strides=[2048, 2048, 2048, 1], requires_grad=0, device=cuda:0),
%6 : int,
%7 : int,
%8 : int):
%9 : bool = prim::Constant[value=0]()
%10 : int = prim::Constant[value=-1]()
%11 : int[] = prim::Constant[value=[8, 2048, 2048]]()
%12 : int[] = prim::Constant[value=[1, 8, 2048, 2048]]()
%13 : Float(1, 1, 2048, 2048, strides=[4194304, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %5)
%14 : Float(1, 1, 2048, 2048, strides=[4194304, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %13, %8)
%15 : Float(1, 1, 2048, 2048, strides=[4194304, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %2)
%16 : Float(1, 8, 2048, 2048, strides=[8, 1, 16384, 8], requires_grad=0, device=cuda:0) = aten::reshape(%1, %12)
%17 : Float(1, 8, 2048, 2048, strides=[8, 1, 16384, 8], requires_grad=0, device=cuda:0) = aten::add(%16, %15, %7)
%18 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %12)
%19 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::add(%18, %17, %6)
%20 : Float(8, 2048, 2048, strides=[4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%19, %11)
%21 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%20, %12)
%22 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%21, %10, %9)
return (%22, %17)
"""), ("batchnorm-silu-mean", """graph(%0 : Float(32, 240, 14, 14, strides=[47040, 196, 14, 1], requires_grad=0, device=cuda:0),
%1 : Float(240, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(240, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(240, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(240, strides=[1], requires_grad=0, device=cuda:0)):
%5 : NoneType = prim::Constant()
%6 : bool = prim::Constant[value=1]()
%7 : int[] = prim::Constant[value=[2, 3]]()
%8 : float = prim::Constant[value=1.0000000000000001e-05]()
%9 : float = prim::Constant[value=0.10000000000000001]()
%10 : bool = prim::Constant[value=0]()
%11 : Float(32, 240, 14, 14, strides=[47040, 196, 14, 1], requires_grad=0, device=cuda:0), %12 : Tensor, %13 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %10, %9, %8)
%14 : Float(32, 240, 14, 14, strides=[47040, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::silu(%11)
%15 : Float(32, 240, 1, 1, strides=[240, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%14, %7, %6, %5)
return (%15, %14)
"""), ("autogen-15", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%2 : int):
%3 : int[] = prim::Constant[value=[512, 768]]()
%4 : int[] = prim::Constant[value=[1, 512, 768]]()
%5 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %4)
%6 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%5, %0, %2)
%7 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%6, %3)
%8 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %4)
%9 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%8, %3)
return (%9, %8)
"""), ("autogen-16", """graph(%0 : Float(1, 1, 512, 512, strides=[262144, 262144, 512, 1], requires_grad=0, device=cuda:0),
%1 : Float(12, 512, 512, strides=[262144, 512, 1], requires_grad=0, device=cuda:0),
%2 : int):
%3 : bool = prim::Constant[value=0]()
%4 : int = prim::Constant[value=-1]()
%5 : int[] = prim::Constant[value=[12, 512, 512]]()
%6 : int[] = prim::Constant[value=[1, 12, 512, 512]]()
%7 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %6)
%8 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::add(%7, %0, %2)
%9 : Float(12, 512, 512, strides=[262144, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%8, %5)
%10 : Float(12, 512, 512, strides=[262144, 512, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%9, %4, %3)
return (%10)
"""), ("autogen-17", """graph(%0 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0),
%1 : Float(768, 64, 128, strides=[8192, 128, 1], requires_grad=0, device=cuda:0),
%2 : int,
%3 : int,
%4 : int):
%5 : NoneType = prim::Constant()
%6 : bool = prim::Constant[value=1]()
%7 : int[] = prim::Constant[value=[-1]]()
%8 : int[] = prim::Constant[value=[1, 12, 64, 64, 128]]()
%9 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %8)
%10 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%9, %0, %4)
%11 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::exp(%10)
%12 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::sum(%11, %7, %6, %5)
%13 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::log(%12)
%14 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%13, %0, %3)
%15 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%9, %14, %2)
%16 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::exp(%15)
return (%16)
"""), ("autogen-18", """graph(%0 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0),
%3 : Float(1, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0),
%4 : int):
%5 : int[] = prim::Constant[value=[1576, 384]]()
%6 : float = prim::Constant[value=9.9999999999999995e-07]()
%7 : int[] = prim::Constant[value=[384]]()
%8 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %3, %4)
%9 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0), %10 : Tensor, %11 : Tensor = aten::native_layer_norm(%8, %7, %0, %1, %6)
%12 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %5)
return (%12, %8)
"""), ("autogen-19", """graph(%0 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 4096, 256, strides=[2097152, 512, 1], requires_grad=0, device=cuda:0),
%3 : Float(4096, 256, strides=[256, 1], requires_grad=0, device=cuda:0),
%4 : int):
%5 : int[] = prim::Constant[value=[4096, 256]]()
%6 : float = prim::Constant[value=9.9999999999999998e-13]()
%7 : int[] = prim::Constant[value=[256]]()
%8 : int[] = prim::Constant[value=[1, 4096, 256]]()
%9 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %8)
%10 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %9, %4)
%11 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0), %12 : Tensor, %13 : Tensor = aten::native_layer_norm(%10, %7, %0, %1, %6)
%14 : Float(4096, 256, strides=[256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%11, %5)
return (%14, %10)
"""), ("autogen-20", """graph(%0 : Float(16, 512, 7, 7, strides=[25088, 49, 7, 1], requires_grad=0, device=cuda:0),
%1 : Float(16, 512, 7, 7, strides=[25088, 49, 7, 1], requires_grad=0, device=cuda:0),
%2 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%6 : int):
%7 : int[] = prim::Constant[value=[16, 512]]()
%8 : NoneType = prim::Constant()
%9 : bool = prim::Constant[value=1]()
%10 : int[] = prim::Constant[value=[-1, -2]]()
%11 : float = prim::Constant[value=1.0000000000000001e-05]()
%12 : float = prim::Constant[value=0.10000000000000001]()
%13 : bool = prim::Constant[value=0]()
%14 : Float(16, 512, 7, 7, strides=[25088, 49, 7, 1], requires_grad=0, device=cuda:0), %15 : Tensor, %16 : Tensor = aten::native_batch_norm(%1, %2, %3, %4, %5, %13, %12, %11)
%17 : Float(16, 512, 7, 7, strides=[25088, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::add(%14, %0, %6)
%18 : Float(16, 512, 7, 7, strides=[25088, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::relu(%17)
%19 : Float(16, 512, 1, 1, strides=[512, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%18, %10, %9, %8)
%20 : Float(16, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%19, %7)
return (%20)
"""), ("autogen-21", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0),
%3 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0),
%4 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[512, 768]]()
%8 : float = prim::Constant[value=9.9999999999999998e-13]()
%9 : int[] = prim::Constant[value=[768]]()
%10 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%3, %4, %6)
%11 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%10, %2, %5)
%12 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0), %13 : Tensor, %14 : Tensor = aten::native_layer_norm(%11, %9, %0, %1, %8)
%15 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %7)
return (%15, %12)
"""), ("autogen-22", """graph(%0 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%1 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%4 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%5 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%6 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%7 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%8 : Double(requires_grad=0, device=cuda:0),
%9 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%10 : Double(requires_grad=0, device=cuda:0),
%11 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%12 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%13 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%14 : Double(requires_grad=0, device=cuda:0),
%15 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%16 : Double(requires_grad=0, device=cuda:0),
%17 : Double(requires_grad=0, device=cuda:0),
%18 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%19 : int,
%20 : int,
%21 : int,
%22 : int,
%23 : int,
%24 : int,
%25 : int,
%26 : int,
%27 : int):
%28 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::pow(%18, %27)
%29 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::reciprocal(%28)
%30 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%29, %17)
%31 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%15, %16)
%32 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%13, %14)
%33 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%30, %12)
%34 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%0, %7)
%35 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%32, %0)
%36 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%11, %8)
%37 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%36, %10, %26)
%38 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%37, %9, %25)
%39 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%38, %8)
%40 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%39, %4)
%41 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %7)
%42 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%3, %5)
%43 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%3, %4)
%44 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%43, %2)
%45 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%44, %34)
%46 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%35, %45, %24)
%47 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%1, %33)
%48 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%46, %47, %23)
%49 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%48, %31, %22)
%50 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%49, %42, %21)
%51 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%50, %40, %20)
%52 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::sub(%51, %41, %19)
%53 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%52, %0)
return (%53, %43, %42, %38, %36, %34, %33, %31, %30)
"""), ("autogen-23", """graph(%0 : Float(32, 2, 256, 28, 28, strides=[401408, 200704, 784, 28, 1], requires_grad=0, device=cuda:0),
%1 : Float(32, 2, 1, 256, strides=[512, 256, 512, 1], requires_grad=0, device=cuda:0)):
%2 : NoneType = prim::Constant()
%3 : int[] = prim::Constant[value=[1]]()
%4 : int[] = prim::Constant[value=[32, 2, 256, 1, 1]]()
%5 : int[] = prim::Constant[value=[32, 512, 1, 1]]()
%6 : int[] = prim::Constant[value=[32, 512]]()
%7 : bool = prim::Constant[value=0]()
%8 : int = prim::Constant[value=1]()
%9 : Float(32, 2, 1, 256, strides=[512, 256, 256, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%1, %8, %7)
%10 : Float(32, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %6)
%11 : Float(32, 512, 1, 1, strides=[512, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%10, %5)
%12 : Float(32, 2, 256, 1, 1, strides=[512, 256, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%11, %4)
%13 : Float(32, 2, 256, 28, 28, strides=[401408, 200704, 784, 28, 1], requires_grad=0, device=cuda:0) = aten::mul(%0, %12)
%14 : Float(32, 256, 28, 28, strides=[200704, 784, 28, 1], requires_grad=0, device=cuda:0) = aten::sum(%13, %3, %7, %2)
return (%14)
"""), ("autogen-24", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1024, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int,
%7 : float):
%8 : int[] = prim::Constant[value=[1024, 3072]]()
%9 : int[] = prim::Constant[value=[1, 1024, 3072]]()
%10 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %9)
%11 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::pow(%10, %7)
%12 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%11, %3)
%13 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%10, %12, %6)
%14 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%13, %2)
%15 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::tanh(%14)
%16 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%15, %1, %5)
%17 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%10, %0)
%18 : Float(1, 1024, 3072, strides=[3145728, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%17, %16)
%19 : Float(1024, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%18, %8)
return (%19)
"""), ("autogen-25", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0),
%3 : Float(16, 128, 1, strides=[128, 1, 1], requires_grad=0, device=cuda:0),
%4 : Double(requires_grad=0, device=cuda:0),
%5 : int,
%6 : int,
%7 : int):
%8 : int[] = prim::Constant[value=[2048, 768]]()
%9 : NoneType = prim::Constant()
%10 : bool = prim::Constant[value=1]()
%11 : int[] = prim::Constant[value=[-1]]()
%12 : Float(16, 128, 1, strides=[128, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%3, %4, %7)
%13 : Float(16, 128, 1, strides=[128, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%2, %11, %10, %9)
%14 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %13, %6)
%15 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%1, %14)
%16 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::div(%15, %12)
%17 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%16, %0, %5)
%18 : Float(2048, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%17, %8)
return (%18)
"""), ("autogen-26", """graph(%0 : Float(1, 8, 2048, 2048, strides=[8, 1, 16384, 8], requires_grad=0, device=cuda:0),
%1 : Float(8, 2048, 2048, strides=[4194304, 2048, 1], requires_grad=0, device=cuda:0),
%2 : int):
%3 : bool = prim::Constant[value=0]()
%4 : int = prim::Constant[value=-1]()
%5 : int[] = prim::Constant[value=[8, 2048, 2048]]()
%6 : int[] = prim::Constant[value=[1, 8, 2048, 2048]]()
%7 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %6)
%8 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::add(%7, %0, %2)
%9 : Float(8, 2048, 2048, strides=[4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%8, %5)
%10 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %6)
%11 : Float(1, 8, 2048, 2048, strides=[33554432, 4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%10, %4, %3)
return (%11)
"""), ("autogen-27", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0),
%3 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : float = prim::Constant[value=9.9999999999999998e-13]()
%8 : int[] = prim::Constant[value=[768]]()
%9 : int[] = prim::Constant[value=[512, 768]]()
%10 : int[] = prim::Constant[value=[1, 512, 768]]()
%11 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %10)
%12 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %3, %6)
%13 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %9)
%14 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %10)
%15 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%14, %2, %5)
%16 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0), %17 : Tensor, %18 : Tensor = aten::native_layer_norm(%15, %8, %0, %1, %7)
%19 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %9)
return (%19, %16)
"""), ("autogen-28", """graph(%0 : Float(128, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(128, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0),
%3 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0),
%4 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[512, 128]]()
%8 : float = prim::Constant[value=9.9999999999999998e-13]()
%9 : int[] = prim::Constant[value=[128]]()
%10 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%3, %4, %6)
%11 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%10, %2, %5)
%12 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0), %13 : Tensor, %14 : Tensor = aten::native_layer_norm(%11, %9, %0, %1, %8)
%15 : Float(512, 128, strides=[128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %7)
return (%15)
"""), ("autogen-29", """graph(%0 : Float(720, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0),
%1 : Float(720, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0),
%2 : Float(1, 12, 60, 64, 64, 1, strides=[64, 245760, 4096, 64, 1, 64], requires_grad=0, device=cuda:0),
%3 : Float(1, 12, 60, 64, 64, 1, strides=[64, 245760, 4096, 64, 1, 64], requires_grad=0, device=cuda:0),
%4 : int,
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[720, 64, 64]]()
%8 : int[] = prim::Constant[value=[1, 12, 60, 64, 64]]()
%9 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %8)
%10 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%2, %8)
%11 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %8)
%12 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %8)
%13 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::add(%12, %11, %6)
%14 : Float(720, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %7)
%15 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%14, %8)
%16 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::add(%15, %10, %5)
%17 : Float(720, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %7)
%18 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%17, %8)
%19 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::add(%18, %9, %4)
%20 : Float(720, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%19, %7)
%21 : Float(1, 12, 60, 64, 64, strides=[2949120, 245760, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%20, %8)
return (%21)
"""), ("autogen-30", """graph(%0 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0),
%3 : Float(4096, 256, strides=[256, 1], requires_grad=0, device=cuda:0),
%4 : int):
%5 : int[] = prim::Constant[value=[4096, 256]]()
%6 : float = prim::Constant[value=9.9999999999999998e-13]()
%7 : int[] = prim::Constant[value=[256]]()
%8 : int[] = prim::Constant[value=[1, 4096, 256]]()
%9 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %8)
%10 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %9, %4)
%11 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0), %12 : Tensor, %13 : Tensor = aten::native_layer_norm(%10, %7, %0, %1, %6)
%14 : Float(4096, 256, strides=[256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%11, %5)
return (%14)
"""), ("autogen-31", """graph(%0 : Float(1, 64, 64, 256, strides=[1048576, 16384, 256, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[4096, 256]]()
%2 : int[] = prim::Constant[value=[1, 4096, 256]]()
%3 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %2)
%4 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %2)
%5 : Float(4096, 256, strides=[256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %1)
return (%5)
"""), ("autogen-32", """graph(%0 : Float(1, 12, 64, 64, 64, strides=[3145728, 262144, 4096, 64, 1], requires_grad=0, device=cuda:0),
%1 : Float(1, 4096, strides=[4096, 1], requires_grad=0, device=cuda:0)):
%2 : int[] = prim::Constant[value=[1, 12, 4096, 64]]()
%3 : int[] = prim::Constant[value=[1, 1, 4096, 1]]()
%4 : Float(1, 1, 4096, 1, strides=[4096, 4096, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %3)
%5 : Float(1, 12, 4096, 64, strides=[3145728, 262144, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %2)
%6 : Float(1, 12, 4096, 64, strides=[3145728, 262144, 64, 1], requires_grad=0, device=cuda:0) = aten::mul(%5, %4)
return (%6, %4)
"""), ("autogen-33", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(12, 64, 4096, strides=[262144, 4096, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 1, 1, 4096, strides=[4096, 4096, 4096, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[12, 64, 4096]]()
%8 : bool = prim::Constant[value=0]()
%9 : int = prim::Constant[value=-1]()
%10 : int[] = prim::Constant[value=[1, 12, 64, 4096]]()
%11 : Float(1, 1, 1, 4096, strides=[4096, 4096, 4096, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %4, %6)
%12 : Float(1, 1, 1, 4096, strides=[4096, 4096, 4096, 1], requires_grad=0, device=cuda:0) = aten::mul(%11, %2)
%13 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %10)
%14 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::mul(%13, %0)
%15 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::add(%14, %12, %5)
%16 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%15, %9, %8)
%17 : Float(12, 64, 4096, strides=[262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %7)
return (%17)
"""), ("autogen-34", """graph(%0 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0),
%3 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : float = prim::Constant[value=9.9999999999999995e-07]()
%8 : int[] = prim::Constant[value=[384]]()
%9 : int[] = prim::Constant[value=[1576, 384]]()
%10 : int[] = prim::Constant[value=[8, 197, 384]]()
%11 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %10)
%12 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %3, %6)
%13 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %9)
%14 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %10)
%15 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %14, %5)
%16 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0), %17 : Tensor, %18 : Tensor = aten::native_layer_norm(%15, %8, %0, %1, %7)
%19 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %9)
return (%19, %15)
"""), ("autogen-35", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0),
%4 : Float(2048, 512, strides=[512, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int,
%7 : int):
%8 : int[] = prim::Constant[value=[2048, 512]]()
%9 : NoneType = prim::Constant()
%10 : bool = prim::Constant[value=1]()
%11 : int[] = prim::Constant[value=[-1]]()
%12 : int[] = prim::Constant[value=[1, 2048, 512]]()
%13 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %12)
%14 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::add(%3, %13, %7)
%15 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::pow(%14, %6)
%16 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%15, %11, %10, %9)
%17 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%16, %2, %5)
%18 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::rsqrt(%17)
%19 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %18)
%20 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%1, %19)
%21 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%20, %0)
%22 : Float(2048, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%21, %8)
return (%22)
"""), ("autogen-36", """graph(%0 : Float(32, 512, 28, 28, strides=[401408, 784, 28, 1], requires_grad=0, device=cuda:0),
%1 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(512, strides=[1], requires_grad=0, device=cuda:0)):
%5 : bool = prim::Constant[value=1]()
%6 : int[] = prim::Constant[value=[2, 3]]()
%7 : NoneType = prim::Constant()
%8 : int[] = prim::Constant[value=[1]]()
%9 : int[] = prim::Constant[value=[32, 2, 256, 28, 28]]()
%10 : float = prim::Constant[value=1.0000000000000001e-05]()
%11 : float = prim::Constant[value=0.10000000000000001]()
%12 : bool = prim::Constant[value=0]()
%13 : Float(32, 512, 28, 28, strides=[401408, 784, 28, 1], requires_grad=0, device=cuda:0), %14 : Tensor, %15 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %12, %11, %10)
%16 : Float(32, 512, 28, 28, strides=[401408, 784, 28, 1], requires_grad=0, device=cuda:0) = aten::relu(%13)
%17 : Float(32, 2, 256, 28, 28, strides=[401408, 200704, 784, 28, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %9)
%18 : Float(32, 256, 28, 28, strides=[200704, 784, 28, 1], requires_grad=0, device=cuda:0) = aten::sum(%17, %8, %12, %7)
%19 : Float(32, 256, 1, 1, strides=[256, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%18, %6, %5, %7)
return (%19, %17)
"""), ("autogen-37", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(720, 64, 192, strides=[12288, 192, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 1, 60, 64, 192, strides=[737280, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[1, 12, 60, 64, 192]]()
%8 : Float(1, 1, 60, 64, 192, strides=[737280, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %4, %6)
%9 : Float(1, 1, 60, 64, 192, strides=[737280, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::mul(%8, %2)
%10 : Float(1, 12, 60, 64, 192, strides=[8847360, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %7)
%11 : Float(1, 12, 60, 64, 192, strides=[8847360, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::mul(%10, %0)
%12 : Float(1, 12, 60, 64, 192, strides=[8847360, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %9, %5)
return (%12)
"""), ("autogen-38", """graph(%0 : Float(1, 4096, 256, strides=[2097152, 512, 1], requires_grad=0, device=cuda:0),
%1 : Float(256, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(256, strides=[1], requires_grad=0, device=cuda:0)):
%3 : int[] = prim::Constant[value=[4096, 256]]()
%4 : float = prim::Constant[value=9.9999999999999998e-13]()
%5 : int[] = prim::Constant[value=[256]]()
%6 : Float(1, 4096, 256, strides=[1048576, 256, 1], requires_grad=0, device=cuda:0), %7 : Tensor, %8 : Tensor = aten::native_layer_norm(%0, %5, %1, %2, %4)
%9 : Float(4096, 256, strides=[256, 1], requires_grad=0, device=cuda:0) = aten::reshape(%6, %3)
return (%9)
"""), ("autogen-39", """graph(%0 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0),
%1 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0),
%2 : int,
%3 : int,
%4 : int):
%5 : NoneType = prim::Constant()
%6 : bool = prim::Constant[value=1]()
%7 : int[] = prim::Constant[value=[-1]]()
%8 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%0, %1, %4)
%9 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::exp(%8)
%10 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::sum(%9, %7, %6, %5)
%11 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::log(%10)
%12 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %1, %3)
%13 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%0, %12, %2)
%14 : Float(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::exp(%13)
return (%14)
"""), ("autogen-40", """graph(%0 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%1 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%6 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%8 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%9 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%10 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%11 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%12 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%13 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%14 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%15 : int,
%16 : int):
%17 : float = prim::Constant[value=0.001]()
%18 : float = prim::Constant[value=0.01]()
%19 : bool = prim::Constant[value=0]()
%20 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %21 : Tensor, %22 : Tensor = aten::native_batch_norm(%10, %11, %12, %13, %14, %19, %18, %17)
%23 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %24 : Tensor, %25 : Tensor = aten::native_batch_norm(%5, %6, %7, %8, %9, %19, %18, %17)
%26 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%23, %20, %16)
%27 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %28 : Tensor, %29 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %19, %18, %17)
%30 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%27, %26, %15)
return (%30)
"""), ("autogen-41", """graph(%0 : Float(12, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[1, 12, 1, 64, 64]]()
%2 : int[] = prim::Constant[value=[12, 64, 64]]()
%3 : int = prim::Constant[value=2]()
%4 : int[] = prim::Constant[value=[1, 12, 64, 64]]()
%5 : Float(1, 12, 64, 64, strides=[49152, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %4)
%6 : Float(1, 12, 1, 64, 64, strides=[49152, 4096, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::unsqueeze(%5, %3)
%7 : Float(1, 12, 64, 64, strides=[49152, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%6, %4)
%8 : Float(12, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %2)
%9 : Float(1, 12, 64, 64, strides=[49152, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%8, %4)
%10 : Float(1, 12, 1, 64, 64, strides=[49152, 4096, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %1)
return (%10)
"""), ("autogen-42", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(3072, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(512, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0),
%6 : int,
%7 : int,
%8 : float,
%9 : int):
%10 : int[] = prim::Constant[value=[512, 3072]]()
%11 : int[] = prim::Constant[value=[1, 512, 3072]]()
%12 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%5, %11)
%13 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%12, %4, %9)
%14 : Float(512, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %10)
%15 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%14, %11)
%16 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::pow(%15, %8)
%17 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%16, %3)
%18 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%15, %17, %7)
%19 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%18, %2)
%20 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::tanh(%19)
%21 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%20, %1, %6)
%22 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%15, %0)
%23 : Float(1, 512, 3072, strides=[1572864, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%22, %21)
%24 : Float(512, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%23, %10)
return (%24)
"""), ("autogen-43", """graph(%0 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%1 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%6 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%8 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%9 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%10 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%11 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%12 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%13 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%14 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%15 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0),
%16 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%17 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%18 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%19 : Float(80, strides=[1], requires_grad=0, device=cuda:0),
%20 : int,
%21 : int,
%22 : int):
%23 : float = prim::Constant[value=0.001]()
%24 : float = prim::Constant[value=0.01]()
%25 : bool = prim::Constant[value=0]()
%26 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %27 : Tensor, %28 : Tensor = aten::native_batch_norm(%15, %16, %17, %18, %19, %25, %24, %23)
%29 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %30 : Tensor, %31 : Tensor = aten::native_batch_norm(%10, %11, %12, %13, %14, %25, %24, %23)
%32 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%29, %26, %22)
%33 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %34 : Tensor, %35 : Tensor = aten::native_batch_norm(%5, %6, %7, %8, %9, %25, %24, %23)
%36 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%33, %32, %21)
%37 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0), %38 : Tensor, %39 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %25, %24, %23)
%40 : Float(32, 80, 14, 14, strides=[15680, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%37, %36, %20)
return (%40)
"""), ("autogen-44", """graph(%0 : Float(128, 1024, 7, 7, strides=[50176, 49, 7, 1], requires_grad=0, device=cuda:0),
%1 : Float(1024, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1024, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(1024, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(1024, strides=[1], requires_grad=0, device=cuda:0)):
%5 : NoneType = prim::Constant()
%6 : int[] = prim::Constant[value=[2, 3]]()
%7 : float = prim::Constant[value=1.0000000000000001e-05]()
%8 : float = prim::Constant[value=0.10000000000000001]()
%9 : bool = prim::Constant[value=0]()
%10 : Float(128, 1024, 7, 7, strides=[50176, 49, 7, 1], requires_grad=0, device=cuda:0), %11 : Tensor, %12 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %9, %8, %7)
%13 : Float(128, 1024, 7, 7, strides=[50176, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::relu(%10)
%14 : Float(128, 1024, strides=[1024, 1], requires_grad=0, device=cuda:0) = aten::mean(%13, %6, %9, %5)
return (%14)
"""), ("autogen-45", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Double(requires_grad=0, device=cuda:0),
%5 : Double(requires_grad=0, device=cuda:0),
%6 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(4096, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%8 : int,
%9 : int,
%10 : int):
%11 : float = prim::Constant[value=9.9999999999999998e-13]()
%12 : int[] = prim::Constant[value=[768]]()
%13 : int[] = prim::Constant[value=[4096, 768]]()
%14 : int[] = prim::Constant[value=[1, 4096, 768]]()
%15 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %14)
%16 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%15, %6, %10)
%17 : Float(4096, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%16, %13)
%18 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%17, %14)
%19 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%18, %5)
%20 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%19, %18)
%21 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%20, %3, %9)
%22 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%18, %4)
%23 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%22, %21)
%24 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::tanh(%23)
%25 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%24, %3, %8)
%26 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%18, %2)
%27 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0) = aten::mul(%26, %25)
%28 : Float(1, 4096, 768, strides=[3145728, 768, 1], requires_grad=0, device=cuda:0), %29 : Tensor, %30 : Tensor = aten::native_layer_norm(%27, %12, %0, %1, %11)
%31 : Float(4096, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%28, %13)
return (%31)
"""), ("autogen-46", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(3072, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(4096, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0),
%6 : int,
%7 : int,
%8 : int):
%9 : int[] = prim::Constant[value=[4096, 3072]]()
%10 : int[] = prim::Constant[value=[1, 4096, 3072]]()
%11 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%5, %10)
%12 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %4, %8)
%13 : Float(4096, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %9)
%14 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %10)
%15 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %3)
%16 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%15, %14)
%17 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%16, %1, %7)
%18 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %2)
%19 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%18, %17)
%20 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::tanh(%19)
%21 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::add(%20, %1, %6)
%22 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %0)
%23 : Float(1, 4096, 3072, strides=[12582912, 3072, 1], requires_grad=0, device=cuda:0) = aten::mul(%22, %21)
%24 : Float(4096, 3072, strides=[3072, 1], requires_grad=0, device=cuda:0) = aten::reshape(%23, %9)
return (%24)
"""), ("autogen-47", """graph(%0 : Float(1, 12, 4096, 64, strides=[3145728, 64, 768, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[768, 64, 64]]()
%2 : int[] = prim::Constant[value=[1, 12, 64, 64, 64]]()
%3 : Float(1, 12, 64, 64, 64, strides=[768, 64, 49152, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %2)
%4 : Float(768, 64, 64, strides=[4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %1)
return (%4, %3)
"""), ("autogen-48", """graph(%0 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0),
%3 : Float(2048, 512, strides=[512, 1], requires_grad=0, device=cuda:0),
%4 : int,
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[2048, 512]]()
%8 : NoneType = prim::Constant()
%9 : bool = prim::Constant[value=1]()
%10 : int[] = prim::Constant[value=[-1]]()
%11 : int[] = prim::Constant[value=[1, 2048, 512]]()
%12 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %11)
%13 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %12, %6)
%14 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::pow(%13, %5)
%15 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%14, %10, %9, %8)
%16 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%15, %1, %4)
%17 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::rsqrt(%16)
%18 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%13, %17)
%19 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%0, %18)
%20 : Float(2048, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%19, %7)
return (%20, %13)
"""), ("autogen-49", """graph(%0 : Long(requires_grad=0, device=cuda:0),
%1 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0),
%2 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0),
%3 : int,
%4 : int):
%5 : NoneType = prim::Constant()
%6 : bool = prim::Constant[value=0]()
%7 : int[] = prim::Constant[value=[1]]()
%8 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%1, %2, %4)
%9 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::div(%8, %0)
%10 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::pow(%9, %3)
%11 : Float(96, 128, 128, strides=[16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mean(%10, %7, %6, %5)
%12 : Float(96, 128, strides=[128, 1], requires_grad=0, device=cuda:0) = aten::mean(%11, %7, %6, %5)
%13 : Float(96, strides=[1], requires_grad=0, device=cuda:0) = aten::mean(%12, %7, %6, %5)
return (%13)
"""), ("autogen-50", """graph(%0 : Float(1, 12, 1, 4096, 64, 1, strides=[64, 262144, 64, 64, 1, 64], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[1, 12, 1, 4096, 64]]()
%2 : Float(1, 12, 1, 4096, 64, strides=[3145728, 262144, 262144, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %1)
%3 : Float(1, 12, 1, 4096, 64, strides=[3145728, 262144, 262144, 64, 1], requires_grad=0, device=cuda:0) = aten::neg(%2)
return (%3, %2)
"""), ("autogen-51", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(12, 512, 512, strides=[262144, 512, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 512, strides=[512, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : bool = prim::Constant[value=0]()
%8 : int = prim::Constant[value=-1]()
%9 : int[] = prim::Constant[value=[1, 12, 512, 512]]()
%10 : int[] = prim::Constant[value=[1, 1, 1, 512]]()
%11 : int[] = prim::Constant[value=[1, 1, 512]]()
%12 : Float(1, 1, 512, strides=[512, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %11)
%13 : Float(1, 1, 1, 512, strides=[512, 512, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %10)
%14 : Float(1, 1, 1, 512, strides=[512, 512, 512, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %13, %6)
%15 : Float(1, 1, 1, 512, strides=[512, 512, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %2)
%16 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %9)
%17 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::div(%16, %0)
%18 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::add(%17, %15, %5)
%19 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%18, %8, %7)
return (%19, %15)
"""), ("autogen-52", """graph(%0 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0),
%1 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0),
%6 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%8 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%9 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%10 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0),
%11 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%12 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%13 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%14 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%15 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0),
%16 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%17 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%18 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%19 : Float(64, strides=[1], requires_grad=0, device=cuda:0),
%20 : int,
%21 : int,
%22 : int):
%23 : float = prim::Constant[value=1.0000000000000001e-05]()
%24 : float = prim::Constant[value=0.10000000000000001]()
%25 : bool = prim::Constant[value=0]()
%26 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0), %27 : Tensor, %28 : Tensor = aten::native_batch_norm(%15, %16, %17, %18, %19, %25, %24, %23)
%29 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0), %30 : Tensor, %31 : Tensor = aten::native_batch_norm(%10, %11, %12, %13, %14, %25, %24, %23)
%32 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0), %33 : Tensor, %34 : Tensor = aten::native_batch_norm(%5, %6, %7, %8, %9, %25, %24, %23)
%35 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0), %36 : Tensor, %37 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %25, %24, %23)
%38 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%35, %32, %22)
%39 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%38, %29, %21)
%40 : Float(96, 64, 14, 14, strides=[12544, 196, 14, 1], requires_grad=0, device=cuda:0) = aten::add(%39, %26, %20)
return (%40)
"""), ("autogen-53", """graph(%0 : Float(128, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(128, strides=[1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Double(requires_grad=0, device=cuda:0),
%5 : Double(requires_grad=0, device=cuda:0),
%6 : Float(128, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(512, 128, strides=[128, 1], requires_grad=0, device=cuda:0),
%8 : int,
%9 : int,
%10 : float,
%11 : int):
%12 : float = prim::Constant[value=1.0000000000000001e-05]()
%13 : int[] = prim::Constant[value=[128]]()
%14 : int[] = prim::Constant[value=[512, 128]]()
%15 : int[] = prim::Constant[value=[1, 512, 128]]()
%16 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %15)
%17 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%16, %6, %11)
%18 : Float(512, 128, strides=[128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%17, %14)
%19 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%18, %15)
%20 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::pow(%19, %10)
%21 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%20, %5)
%22 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%19, %21, %9)
%23 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%22, %4)
%24 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::tanh(%23)
%25 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%24, %3, %8)
%26 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%19, %2)
%27 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%26, %25)
%28 : Float(1, 512, 128, strides=[65536, 128, 1], requires_grad=0, device=cuda:0), %29 : Tensor, %30 : Tensor = aten::native_layer_norm(%27, %13, %0, %1, %12)
%31 : Float(512, 128, strides=[128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%28, %14)
return (%31)
"""), ("autogen-54", """graph(%0 : Float(32, 1000, 13, 13, strides=[169000, 169, 13, 1], requires_grad=0, device=cuda:0)):
%1 : NoneType = prim::Constant()
%2 : bool = prim::Constant[value=1]()
%3 : int[] = prim::Constant[value=[-1, -2]]()
%4 : Float(32, 1000, 13, 13, strides=[169000, 169, 13, 1], requires_grad=0, device=cuda:0) = aten::relu(%0)
%5 : Float(32, 1000, 1, 1, strides=[1000, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%4, %3, %2, %1)
return (%5)
"""), ("autogen-55", """graph(%0 : Float(96, strides=[1], requires_grad=0, device=cuda:0),
%1 : Long(requires_grad=0, device=cuda:0),
%2 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0),
%3 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0),
%4 : Float(96, strides=[1], requires_grad=0, device=cuda:0),
%5 : Double(requires_grad=0, device=cuda:0),
%6 : int,
%7 : int,
%8 : int,
%9 : int):
%10 : NoneType = prim::Constant()
%11 : bool = prim::Constant[value=0]()
%12 : int[] = prim::Constant[value=[1]]()
%13 : Float(96, strides=[1], requires_grad=0, device=cuda:0) = aten::add(%4, %5, %9)
%14 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %3, %8)
%15 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::div(%14, %1)
%16 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::pow(%15, %7)
%17 : Float(96, 128, 128, strides=[16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mean(%16, %12, %11, %10)
%18 : Float(96, 128, strides=[128, 1], requires_grad=0, device=cuda:0) = aten::mean(%17, %12, %11, %10)
%19 : Float(96, strides=[1], requires_grad=0, device=cuda:0) = aten::mean(%18, %12, %11, %10)
%20 : Float(96, strides=[1], requires_grad=0, device=cuda:0) = aten::sub(%0, %19, %6)
%21 : Float(96, strides=[1], requires_grad=0, device=cuda:0) = aten::div(%20, %13)
return (%21)
"""), ("autogen-56", """graph(%0 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0),
%3 : Float(384, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : float = prim::Constant[value=9.9999999999999995e-07]()
%8 : int[] = prim::Constant[value=[384]]()
%9 : int[] = prim::Constant[value=[1576, 384]]()
%10 : int[] = prim::Constant[value=[8, 197, 384]]()
%11 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %10)
%12 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %3, %6)
%13 : Float(1576, 384, strides=[384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %9)
%14 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::reshape(%13, %10)
%15 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %14, %5)
%16 : Float(8, 197, 384, strides=[75648, 384, 1], requires_grad=0, device=cuda:0), %17 : Tensor, %18 : Tensor = aten::native_layer_norm(%15, %8, %0, %1, %7)
return (%16, %17, %18)
"""), ("autogen-57", """graph(%0 : Float(32, 960, 7, 7, strides=[47040, 49, 7, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[32, 960]]()
%2 : NoneType = prim::Constant()
%3 : bool = prim::Constant[value=1]()
%4 : int[] = prim::Constant[value=[-1, -2]]()
%5 : Float(32, 960, 1, 1, strides=[960, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%0, %4, %3, %2)
%6 : Float(32, 960, strides=[960, 1], requires_grad=0, device=cuda:0) = aten::reshape(%5, %1)
return (%6)
"""), ("autogen-59", """graph(%0 : Long(1, 12, 4096, strides=[49152, 4096, 1], requires_grad=0, device=cuda:0),
%1 : Long(requires_grad=0, device=cuda:0),
%2 : Long(1, 12, 1, 4096, strides=[49152, 4096, 4096, 1], requires_grad=0, device=cuda:0),
%3 : Long(1, 12, 1, 1, strides=[1, 0, 1, 1], requires_grad=0, device=cuda:0),
%4 : int,
%5 : int):
%6 : int[] = prim::Constant[value=[1, 12, 4096]]()
%7 : Long(1, 12, 1, 4096, strides=[49152, 4096, 4096, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %3, %5)
%8 : Long(1, 12, 4096, strides=[49152, 4096, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %6)
%9 : Long(1, 12, 4096, strides=[49152, 4096, 1], requires_grad=0, device=cuda:0) = aten::mul(%8, %1)
%10 : Long(1, 12, 4096, strides=[49152, 4096, 1], requires_grad=0, device=cuda:0) = aten::add(%9, %0, %4)
return (%10)
"""), ("autogen-60", """graph(%0 : Float(requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Float(1, 12, 4096, 64, strides=[3145728, 262144, 64, 1], requires_grad=0, device=cuda:0),
%3 : int,
%4 : int):
%5 : NoneType = prim::Constant()
%6 : bool = prim::Constant[value=1]()
%7 : int[] = prim::Constant[value=[-1]]()
%8 : int[] = prim::Constant[value=[1, 12, 64, 64, 64]]()
%9 : Float(1, 12, 64, 64, 64, strides=[3145728, 262144, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::reshape(%2, %8)
%10 : Float(1, 12, 64, 64, 64, strides=[3145728, 262144, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::pow(%9, %4)
%11 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%10, %7, %6, %5)
%12 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %1, %3)
%13 : Float(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::rsqrt(%12)
%14 : Float(1, 12, 64, 64, 64, strides=[3145728, 262144, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::mul(%9, %13)
%15 : Float(1, 12, 64, 64, 64, strides=[3145728, 262144, 4096, 64, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %0)
return (%15, %9)
"""), ("autogen-61", """graph(%0 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(2048, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%3 : int,
%4 : int):
%5 : int[] = prim::Constant[value=[2048, 768]]()
%6 : int[] = prim::Constant[value=[16, 128, 768]]()
%7 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%2, %6)
%8 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%7, %1, %4)
%9 : Float(2048, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%8, %5)
%10 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %6)
%11 : Float(16, 128, 768, strides=[98304, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%0, %10, %3)
%12 : Float(2048, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%11, %5)
return (%12, %11)
"""), ("autogen-62", """graph(%0 : Float(32, 2048, 7, 7, strides=[100352, 49, 7, 1], requires_grad=0, device=cuda:0),
%1 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%3 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%5 : Float(32, 2048, 7, 7, strides=[100352, 49, 7, 1], requires_grad=0, device=cuda:0),
%6 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%7 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%8 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%9 : Float(2048, strides=[1], requires_grad=0, device=cuda:0),
%10 : int):
%11 : int[] = prim::Constant[value=[32, 2048]]()
%12 : NoneType = prim::Constant()
%13 : bool = prim::Constant[value=1]()
%14 : int[] = prim::Constant[value=[-1, -2]]()
%15 : float = prim::Constant[value=1.0000000000000001e-05]()
%16 : float = prim::Constant[value=0.10000000000000001]()
%17 : bool = prim::Constant[value=0]()
%18 : Float(32, 2048, 7, 7, strides=[100352, 49, 7, 1], requires_grad=0, device=cuda:0), %19 : Tensor, %20 : Tensor = aten::native_batch_norm(%5, %6, %7, %8, %9, %17, %16, %15)
%21 : Float(32, 2048, 7, 7, strides=[100352, 49, 7, 1], requires_grad=0, device=cuda:0), %22 : Tensor, %23 : Tensor = aten::native_batch_norm(%0, %1, %2, %3, %4, %17, %16, %15)
%24 : Float(32, 2048, 7, 7, strides=[100352, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::add(%21, %18, %10)
%25 : Float(32, 2048, 7, 7, strides=[100352, 49, 7, 1], requires_grad=0, device=cuda:0) = aten::relu(%24)
%26 : Float(32, 2048, 1, 1, strides=[2048, 1, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%25, %14, %13, %12)
%27 : Float(32, 2048, strides=[2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%26, %11)
return (%27)
"""), ("autogen-63", """graph(%0 : Float(480, 1, 1, 3, strides=[13, 3, 3, 1], requires_grad=0, device=cuda:0),
%1 : Long(requires_grad=0, device=cuda:0),
%2 : Float(480, 1, 64, 2, 64, 2, strides=[16384, 16384, 64, 8192, 1, 4096], requires_grad=0, device=cuda:0),
%3 : int,
%4 : int):
%5 : int[] = prim::Constant[value=[480, 128, 128, 1]]()
%6 : int[] = prim::Constant[value=[480, 128, 128]]()
%7 : int[] = prim::Constant[value=[480, 1, 128, 128]]()
%8 : Float(480, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%2, %7)
%9 : Float(480, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sigmoid(%8)
%10 : Float(480, 128, 128, strides=[16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %6)
%11 : Float(480, 128, 128, strides=[16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%1, %10, %4)
%12 : Float(480, 128, 128, strides=[16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%1, %11, %3)
%13 : Float(480, 128, 128, 1, strides=[16384, 128, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%12, %5)
%14 : Float(480, 128, 128, 3, strides=[49152, 384, 3, 1], requires_grad=0, device=cuda:0) = aten::mul(%13, %0)
return (%14, %13)
"""), ("autogen-64", """graph(%0 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%1 : Double(requires_grad=0, device=cuda:0),
%2 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%5 : Double(requires_grad=0, device=cuda:0),
%6 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0),
%7 : Double(requires_grad=0, device=cuda:0),
%8 : int,
%9 : int,
%10 : int,
%11 : int):
%12 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%6, %7)
%13 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %5)
%14 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%13, %3, %11)
%15 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::mul(%2, %14)
%16 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%0, %1, %10)
%17 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%16, %15, %9)
%18 : Double(204, 204, 26, strides=[5304, 26, 1], requires_grad=0, device=cuda:0) = aten::add(%17, %12, %8)
return (%18)
"""), ("autogen-65", """graph(%0 : Float(20005, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(2048, 20005, strides=[20005, 1], requires_grad=0, device=cuda:0),
%2 : int):
%3 : int[] = prim::Constant[value=[2048, 20005]]()
%4 : int[] = prim::Constant[value=[16, 128, 20005]]()
%5 : Float(16, 128, 20005, strides=[2560640, 20005, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %4)
%6 : Float(16, 128, 20005, strides=[2560640, 20005, 1], requires_grad=0, device=cuda:0) = aten::add(%5, %0, %2)
%7 : Float(2048, 20005, strides=[20005, 1], requires_grad=0, device=cuda:0) = aten::reshape(%6, %3)
%8 : Float(16, 128, 20005, strides=[2560640, 20005, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %4)
return (%8)
"""), ("autogen-66", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 1024, 768, strides=[786432, 768, 1], requires_grad=0, device=cuda:0),
%3 : Float(1024, 768, strides=[768, 1], requires_grad=0, device=cuda:0),
%4 : int):
%5 : int[] = prim::Constant[value=[1024, 768]]()
%6 : float = prim::Constant[value=1.0000000000000001e-05]()
%7 : int[] = prim::Constant[value=[768]]()
%8 : int[] = prim::Constant[value=[1, 1024, 768]]()
%9 : Float(1, 1024, 768, strides=[786432, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %8)
%10 : Float(1, 1024, 768, strides=[786432, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %9, %4)
%11 : Float(1, 1024, 768, strides=[786432, 768, 1], requires_grad=0, device=cuda:0), %12 : Tensor, %13 : Tensor = aten::native_layer_norm(%10, %7, %0, %1, %6)
%14 : Float(1, 1024, 768, strides=[786432, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%11, %8)
%15 : Float(1024, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%14, %5)
return (%15)
"""), ("autogen-67", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(720, 64, 192, strides=[12288, 192, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 60, 64, 1, strides=[3840, 64, 1, 1], requires_grad=0, device=cuda:0),
%5 : Float(1, 60, 1, 192, strides=[11520, 192, 1, 1], requires_grad=0, device=cuda:0),
%6 : int,
%7 : int):
%8 : int[] = prim::Constant[value=[1, 12, 60, 64, 192]]()
%9 : int = prim::Constant[value=1]()
%10 : Float(1, 60, 64, 192, strides=[737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::mul(%4, %5)
%11 : Float(1, 1, 60, 64, 192, strides=[737280, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::unsqueeze(%10, %9)
%12 : Float(1, 1, 60, 64, 192, strides=[737280, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %11, %7)
%13 : Float(1, 1, 60, 64, 192, strides=[737280, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::mul(%12, %2)
%14 : Float(1, 12, 60, 64, 192, strides=[8847360, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %8)
%15 : Float(1, 12, 60, 64, 192, strides=[8847360, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::mul(%14, %0)
%16 : Float(1, 12, 60, 64, 192, strides=[8847360, 737280, 12288, 192, 1], requires_grad=0, device=cuda:0) = aten::add(%15, %13, %6)
return (%16, %11)
"""), ("autogen-68", """graph(%0 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%2 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0),
%3 : Float(768, strides=[1], requires_grad=0, device=cuda:0),
%4 : Float(1, 512, 768, 1, 1, strides=[768, 768, 1, 768, 768], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[512, 768]]()
%8 : float = prim::Constant[value=9.9999999999999998e-13]()
%9 : int[] = prim::Constant[value=[768]]()
%10 : int[] = prim::Constant[value=[1, 512, 768]]()
%11 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %10)
%12 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%11, %3, %6)
%13 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0) = aten::add(%2, %12, %5)
%14 : Float(1, 512, 768, strides=[393216, 768, 1], requires_grad=0, device=cuda:0), %15 : Tensor, %16 : Tensor = aten::native_layer_norm(%13, %9, %0, %1, %8)
%17 : Float(512, 768, strides=[768, 1], requires_grad=0, device=cuda:0) = aten::reshape(%14, %7)
return (%17, %14)
"""), ("autogen-69", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(12, 64, 4096, strides=[262144, 4096, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 4096, strides=[4096, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : int[] = prim::Constant[value=[12, 64, 4096]]()
%8 : bool = prim::Constant[value=0]()
%9 : int = prim::Constant[value=-1]()
%10 : int[] = prim::Constant[value=[1, 12, 64, 4096]]()
%11 : int[] = prim::Constant[value=[1, 1, 1, 4096]]()
%12 : Float(1, 1, 1, 4096, strides=[4096, 4096, 4096, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %11)
%13 : Float(1, 1, 1, 4096, strides=[4096, 4096, 4096, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %12, %6)
%14 : Float(1, 1, 1, 4096, strides=[4096, 4096, 4096, 1], requires_grad=0, device=cuda:0) = aten::mul(%13, %2)
%15 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %10)
%16 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::mul(%15, %0)
%17 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::add(%16, %14, %5)
%18 : Float(1, 12, 64, 4096, strides=[3145728, 262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%17, %9, %8)
%19 : Float(12, 64, 4096, strides=[262144, 4096, 1], requires_grad=0, device=cuda:0) = aten::reshape(%18, %7)
return (%19, %12)
"""), ("autogen-70", """graph(%0 : Long(1, 12, 64, 64, strides=[49152, 4096, 64, 1], requires_grad=0, device=cuda:0),
%1 : Long(1, 12, 64, 128, strides=[98304, 8192, 128, 1], requires_grad=0, device=cuda:0)):
%2 : int[] = prim::Constant[value=[1, 12, 64, 64, 1]]()
%3 : int[] = prim::Constant[value=[1, 12, 64, 1, 128]]()
%4 : Long(1, 12, 64, 1, 128, strides=[98304, 8192, 128, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %3)
%5 : Long(1, 12, 64, 64, 1, strides=[49152, 4096, 64, 1, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %2)
%6 : Bool(1, 12, 64, 64, 128, strides=[6291456, 524288, 8192, 128, 1], requires_grad=0, device=cuda:0) = aten::ne(%5, %4)
return (%6)
"""), ("autogen-71", """graph(%0 : Float(512, strides=[1], requires_grad=0, device=cuda:0),
%1 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : int,
%4 : int):
%5 : int[] = prim::Constant[value=[2048, 512]]()
%6 : NoneType = prim::Constant()
%7 : bool = prim::Constant[value=1]()
%8 : int[] = prim::Constant[value=[-1]]()
%9 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::pow(%1, %4)
%10 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::mean(%9, %8, %7, %6)
%11 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::add(%10, %2, %3)
%12 : Float(1, 2048, 1, strides=[2048, 1, 1], requires_grad=0, device=cuda:0) = aten::rsqrt(%11)
%13 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%1, %12)
%14 : Float(1, 2048, 512, strides=[1048576, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%0, %13)
%15 : Float(2048, 512, strides=[512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%14, %5)
return (%15)
"""), ("autogen-72", """graph(%0 : Long(2232, strides=[1], requires_grad=0, device=cuda:0),
%1 : Long(2232, strides=[1], requires_grad=0, device=cuda:0),
%2 : Long(requires_grad=0, device=cuda:0),
%3 : Long(1, 12, 62, 3, strides=[2232, 186, 3, 1], requires_grad=0, device=cuda:0),
%4 : int,
%5 : int):
%6 : int[] = prim::Constant[value=[2232]]()
%7 : Long(2232, strides=[1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %6)
%8 : Long(2232, strides=[1], requires_grad=0, device=cuda:0) = aten::mul(%1, %2)
%9 : Long(2232, strides=[1], requires_grad=0, device=cuda:0) = aten::add(%7, %8, %5)
%10 : Long(2232, strides=[1], requires_grad=0, device=cuda:0) = aten::add(%7, %0, %4)
return (%10, %9)
"""), ("autogen-73", """graph(%0 : Long(requires_grad=0, device=cuda:0),
%1 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0),
%2 : Long(requires_grad=0, device=cuda:0),
%3 : Float(96, 1, 1, 128, 128, strides=[81920, 16384, 16384, 128, 1], requires_grad=0, device=cuda:0),
%4 : Float(96, 1, 3, 128, 128, strides=[245760, 49152, 1, 384, 3], requires_grad=0, device=cuda:0),
%5 : Float(96, 1, 1, 128, 128, strides=[81920, 16384, 16384, 128, 1], requires_grad=0, device=cuda:0),
%6 : Float(96, 1, 3, 128, 128, strides=[245760, 49152, 1, 384, 3], requires_grad=0, device=cuda:0),
%7 : Float(96, 1, 1, 128, 128, strides=[81920, 16384, 16384, 128, 1], requires_grad=0, device=cuda:0),
%8 : Float(96, 1, 3, 128, 128, strides=[245760, 49152, 1, 384, 3], requires_grad=0, device=cuda:0),
%9 : Float(96, 1, 1, 128, 128, strides=[81920, 16384, 16384, 128, 1], requires_grad=0, device=cuda:0),
%10 : Float(96, 1, 3, 128, 128, strides=[245760, 49152, 1, 384, 3], requires_grad=0, device=cuda:0),
%11 : Float(96, 1, 1, 128, 128, strides=[81920, 16384, 16384, 128, 1], requires_grad=0, device=cuda:0),
%12 : Float(96, 1, 3, 128, 128, strides=[245760, 49152, 1, 384, 3], requires_grad=0, device=cuda:0),
%13 : int,
%14 : int,
%15 : int,
%16 : int,
%17 : int,
%18 : int,
%19 : int,
%20 : int,
%21 : int,
%22 : int):
%23 : int[] = prim::Constant[value=[96, 1, 128, 128]]()
%24 : int[] = prim::Constant[value=[96, 3, 128, 128]]()
%25 : Float(96, 3, 128, 128, strides=[245760, 1, 384, 3], requires_grad=0, device=cuda:0) = aten::reshape(%12, %24)
%26 : Float(96, 1, 128, 128, strides=[81920, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%11, %23)
%27 : Float(96, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %26, %22)
%28 : Float(96, 3, 128, 128, strides=[245760, 1, 384, 3], requires_grad=0, device=cuda:0) = aten::reshape(%10, %24)
%29 : Float(96, 1, 128, 128, strides=[81920, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%9, %23)
%30 : Float(96, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %29, %21)
%31 : Float(96, 3, 128, 128, strides=[245760, 1, 384, 3], requires_grad=0, device=cuda:0) = aten::reshape(%8, %24)
%32 : Float(96, 1, 128, 128, strides=[81920, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%7, %23)
%33 : Float(96, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %32, %20)
%34 : Float(96, 3, 128, 128, strides=[245760, 1, 384, 3], requires_grad=0, device=cuda:0) = aten::reshape(%6, %24)
%35 : Float(96, 1, 128, 128, strides=[81920, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%5, %23)
%36 : Float(96, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %35, %19)
%37 : Float(96, 3, 128, 128, strides=[245760, 1, 384, 3], requires_grad=0, device=cuda:0) = aten::reshape(%4, %24)
%38 : Float(96, 1, 128, 128, strides=[81920, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::reshape(%3, %23)
%39 : Float(96, 1, 128, 128, strides=[16384, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::sub(%2, %38, %18)
%40 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::div(%1, %0)
%41 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%40, %39)
%42 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%41, %37, %17)
%43 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%42, %36)
%44 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%43, %34, %16)
%45 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%44, %33)
%46 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%45, %31, %15)
%47 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%46, %30)
%48 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%47, %28, %14)
%49 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%48, %27)
%50 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::add(%49, %25, %13)
%51 : Float(96, 3, 128, 128, strides=[49152, 16384, 128, 1], requires_grad=0, device=cuda:0) = aten::mul(%50, %0)
return (%51)
"""), ("autogen-74", """graph(%0 : Long(200, 200, strides=[204, 1], requires_grad=0, device=cuda:0),
%1 : Long(requires_grad=0, device=cuda:0),
%2 : int,
%3 : int):
%4 : Long(200, 200, strides=[200, 1], requires_grad=0, device=cuda:0) = aten::sub(%0, %1, %3)
%5 : Bool(200, 200, strides=[200, 1], requires_grad=0, device=cuda:0) = aten::ge(%4, %2)
return (%5, %4)
"""), ("autogen-75", """graph(%0 : Double(requires_grad=0, device=cuda:0),
%1 : Float(12, 512, 512, strides=[262144, 512, 1], requires_grad=0, device=cuda:0),
%2 : Double(requires_grad=0, device=cuda:0),
%3 : Double(requires_grad=0, device=cuda:0),
%4 : Float(1, 1, 1, 512, strides=[512, 512, 512, 1], requires_grad=0, device=cuda:0),
%5 : int,
%6 : int):
%7 : bool = prim::Constant[value=0]()
%8 : int = prim::Constant[value=-1]()
%9 : int[] = prim::Constant[value=[1, 12, 512, 512]]()
%10 : Float(1, 1, 1, 512, strides=[512, 512, 512, 1], requires_grad=0, device=cuda:0) = aten::sub(%3, %4, %6)
%11 : Float(1, 1, 1, 512, strides=[512, 512, 512, 1], requires_grad=0, device=cuda:0) = aten::mul(%10, %2)
%12 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::reshape(%1, %9)
%13 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::div(%12, %0)
%14 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::add(%13, %11, %5)
%15 : Float(1, 12, 512, 512, strides=[3145728, 262144, 512, 1], requires_grad=0, device=cuda:0) = aten::_softmax(%14, %8, %7)
return (%15, %11)
"""), ("autogen-76", """graph(%0 : Float(2048, 2048, strides=[2048, 1], requires_grad=0, device=cuda:0)):
%1 : int[] = prim::Constant[value=[2048, 2048]]()
%2 : int[] = prim::Constant[value=[1, 2048, 2048]]()
%3 : Float(1, 2048, 2048, strides=[4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%0, %2)
%4 : Float(1, 2048, 2048, strides=[4194304, 2048, 1], requires_grad=0, device=cuda:0) = aten::relu(%3)
%5 : Float(2048, 2048, strides=[2048, 1], requires_grad=0, device=cuda:0) = aten::reshape(%4, %1)
return (%5)
""")]
|
from string import whitespace
import json
# From https://gist.github.com/pib/240957
# with adjustments to handle [0 1 2] (a . b) and (1bar ...)
atom_end = set('()[]"\'') | set(whitespace)
def parse(sexp):
stack, i, length = [[]], 0, len(sexp)
while i < length:
c = sexp[i]
#print c, stack
reading = type(stack[-1])
if reading == list:
if c == '(': stack.append([])
elif c == ')':
stack[-2].append(stack.pop())
if stack[-1][0] == ('quote',): stack[-2].append(stack.pop())
elif c == '[': stack.append([])
elif c == ']':
stack[-2].append(stack.pop())
elif c == '"': stack.append('')
elif c == "'": stack.append([('quote',)])
elif c in whitespace: pass
else: stack.append((c,))
elif reading == str:
if c == '"':
stack[-2].append(stack.pop())
if stack[-1][0] == ('quote',): stack[-2].append(stack.pop())
elif c == '\\':
i += 1
stack[-1] += sexp[i]
else: stack[-1] += c
elif reading == tuple:
if c in atom_end:
atom = stack.pop()
if atom[0] == ".": continue
try:
stack[-1].append(int(atom[0]))
except ValueError:
stack[-1].append(atom[0])
if stack[-1][0] == ('quote',): stack[-2].append(stack.pop())
continue
else: stack[-1] = ((stack[-1][0] + c),)
i += 1
return stack.pop()
nodemap = {}
nodes = []
links = []
data = []
for i in ["melpa", "gnu-elpa", "marmalade", "orgmode"]:
data += parse(open(i).read())[0][1:]
core = set(["erc", "emacs", "sql", "thingatpt", "gnus", "ede", "semantic", "cl", "ido", "timeclock", "cl-lib", "eieio", "json",
# These are some very commonly used libraries
#"dash", "s", "f", "helm", "auto-complete", "org", "popup", "evil"
])
flag = False
name = None
def lookup(m,i):
if i not in m:
if flag:
# Indicates that we've found a dependency on
# a library which didn't show up in any of our repositories;
# and the library isn't in the core set
pass
nodes.append({"name": i})
nodemap[i] = len(nodemap)
return m[i]
for i in data:
name = i[0]
if name in core: continue
lookup(nodemap,name)
flag = True
for i in data:
# print i
name = i[0]
if name in core: continue
namei = lookup(nodemap,name)
deps = i[1][1]
if deps == "nil": continue
for dep in map(lambda x: x[0],deps):
if dep in core: continue
links.append({"source": lookup(nodemap,dep), "target": namei})
print json.dumps({"nodes": nodes, "links": links})
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from distutils.spawn import find_executable
from distutils import sysconfig, log
import setuptools
import setuptools.command.build_py
import setuptools.command.develop
import setuptools.command.build_ext
from collections import namedtuple
from contextlib import contextmanager
import glob
import os
import multiprocessing
import shlex
import subprocess
import sys
from textwrap import dedent
TOP_DIR = os.path.realpath(os.path.dirname(__file__))
SRC_DIR = os.path.join(TOP_DIR, 'caffe2')
CMAKE_BUILD_DIR = os.path.join(TOP_DIR, '.setuptools-cmake-build')
install_requires = []
setup_requires = []
tests_require = []
################################################################################
# Pre Check
################################################################################
CMAKE = find_executable('cmake')
assert CMAKE, 'Could not find "cmake" executable!'
NINJA = find_executable('ninja')
MAKE = find_executable('make')
assert NINJA or MAKE, \
'Could not find neither "ninja" nor "make" executable!'
################################################################################
# utils functions
################################################################################
@contextmanager
def cd(path):
if not os.path.isabs(path):
raise RuntimeError('Can only cd to absolute path, got: {}'.format(path))
orig_path = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(orig_path)
################################################################################
# Version
################################################################################
try:
git_version = subprocess.check_output(['git', 'describe', '--tags', 'HEAD'],
cwd=TOP_DIR).decode('ascii').strip()
except (OSError, subprocess.CalledProcessError):
git_version = None
with open(os.path.join(SRC_DIR, 'VERSION_NUMBER')) as version_file:
VersionInfo = namedtuple('VersionInfo', ['version', 'git_version'])(
version=version_file.read().strip(),
git_version=git_version
)
################################################################################
# Customized commands
################################################################################
class Caffe2Command(setuptools.Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
class create_version(Caffe2Command):
def run(self):
with open(os.path.join(SRC_DIR, 'version.py'), 'w') as f:
f.write(dedent('''
version = '{version}'
git_version = '{git_version}'
'''.format(**dict(VersionInfo._asdict()))))
class cmake_build(Caffe2Command):
"""
Compiles everything when `python setup.py build` is run using cmake.
Custom args can be passed to cmake by specifying the `CMAKE_ARGS`
environment variable. E.g. to build without cuda support run:
`CMAKE_ARGS=-DUSE_CUDA=Off python setup.py build`
The number of CPUs used by `make`/`ninja` can be specified by passing
`-j<ncpus>` to `setup.py build`. By default all CPUs are used.
"""
user_options = [
(str('jobs='), str('j'),
str('Specifies the number of jobs to use with make or ninja'))
]
built = False
def initialize_options(self):
self.jobs = multiprocessing.cpu_count()
def finalize_options(self):
self.jobs = int(self.jobs)
def run(self):
if cmake_build.built:
return
cmake_build.built = True
if not os.path.exists(CMAKE_BUILD_DIR):
os.makedirs(CMAKE_BUILD_DIR)
with cd(CMAKE_BUILD_DIR):
# configure
cmake_args = [
find_executable('cmake'),
'-DBUILD_SHARED_LIBS=OFF',
'-DPYTHON_EXECUTABLE:FILEPATH={}'.format(sys.executable),
'-DPYTHON_INCLUDE_DIR={}'.format(sysconfig.get_python_inc()),
'-DBUILD_TEST=OFF',
'-DBUILD_BENCHMARK=OFF',
'-DBUILD_BINARY=OFF',
]
if NINJA:
cmake_args.extend(['-G', 'Ninja'])
if 'CMAKE_ARGS' in os.environ:
extra_cmake_args = shlex.split(os.environ['CMAKE_ARGS'])
# prevent crossfire with downstream scripts
del os.environ['CMAKE_ARGS']
log.info('Extra cmake args: {}'.format(extra_cmake_args))
cmake_args.append(TOP_DIR)
subprocess.check_call(cmake_args)
build_args = [NINJA or MAKE]
# control the number of concurrent jobs
if self.jobs is not None:
build_args.extend(['-j', str(self.jobs)])
subprocess.check_call(build_args)
class build_py(setuptools.command.build_py.build_py):
def run(self):
self.run_command('create_version')
self.run_command('cmake_build')
for d in ['caffe', 'caffe2']:
for src in glob.glob(
os.path.join(CMAKE_BUILD_DIR, d, 'proto', '*.py')):
dst = os.path.join(
TOP_DIR, os.path.relpath(src, CMAKE_BUILD_DIR))
self.copy_file(src, dst)
setuptools.command.build_py.build_py.run(self)
class build_ext(setuptools.command.build_ext.build_ext):
def get_outputs(self):
return [os.path.join(self.build_lib, d)
for d in ['caffe', 'caffe2']]
def run(self):
self.run_command('cmake_build')
setuptools.command.build_ext.build_ext.run(self)
def build_extensions(self):
i = 0
while i < len(self.extensions):
ext = self.extensions[i]
fullname = self.get_ext_fullname(ext.name)
filename = self.get_ext_filename(fullname)
src = os.path.join(CMAKE_BUILD_DIR, filename)
if not os.path.exists(src):
del self.extensions[i]
else:
dst = os.path.join(os.path.realpath(self.build_lib), filename)
self.copy_file(src, dst)
i += 1
class develop(setuptools.command.develop.develop):
def run(self):
self.run_command('build_py')
setuptools.command.develop.develop.run(self)
cmdclass = {
'create_version': create_version,
'cmake_build': cmake_build,
'build_py': build_py,
'build_ext': build_ext,
'develop': develop,
}
################################################################################
# Extensions
################################################################################
ext_modules = [
setuptools.Extension(
name=str('caffe2.python.caffe2_pybind11_state'),
sources=[]),
setuptools.Extension(
name=str('caffe2.python.caffe2_pybind11_state_gpu'),
sources=[]),
]
################################################################################
# Packages
################################################################################
packages = setuptools.find_packages()
install_requires.extend(['protobuf',
'numpy',
'future',
'hypothesis',
'requests',
'scipy',
'six',])
################################################################################
# Test
################################################################################
setup_requires.append('pytest-runner')
tests_require.extend(['pytest-cov', 'hypothesis'])
################################################################################
# Final
################################################################################
setuptools.setup(
name='caffe2',
version=VersionInfo.version,
description='Caffe2',
ext_modules=ext_modules,
cmdclass=cmdclass,
packages=packages,
install_requires=install_requires,
setup_requires=setup_requires,
tests_require=tests_require,
author='jiayq',
author_email='[email protected]',
url='https://caffe2.ai',
)
|
## @package optimizer_test_util
# Module caffe2.python.optimizer_test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
from caffe2.python import brew, core, workspace, cnn, optimizer
from caffe2.proto import caffe2_pb2
from caffe2.python.modeling.initializers import (
Initializer, PseudoFP16Initializer)
from caffe2.python.model_helper import ModelHelper
class OptimizerTestBase(object):
"""
This is an abstract base class.
Don't inherit from unittest.TestCase, and don't name it 'Test*'.
Do, however, do these things in classes which inherit from this.
"""
def _createDense(self, dtype=core.DataType.FLOAT):
perfect_model = np.array([2, 6, 5, 0, 1]).astype(np.float32)
np.random.seed(123) # make test deterministic
numpy_dtype = np.float32 if dtype == core.DataType.FLOAT else np.float16
initializer = Initializer if dtype == core.DataType.FLOAT else \
PseudoFP16Initializer
data = np.random.randint(
2,
size=(20, perfect_model.size)).astype(numpy_dtype)
label = np.dot(data, perfect_model)[:, np.newaxis]
model = ModelHelper(name="test", arg_scope={'order': 'NCHW'})
out = brew.fc(
model,
'data', 'fc', perfect_model.size, 1, ('ConstantFill', {}),
('ConstantFill', {}), axis=0,
WeightInitializer=initializer, BiasInitializer=initializer
)
if dtype == core.DataType.FLOAT16:
out = model.HalfToFloat(out, out + "_fp32")
sq = model.SquaredL2Distance([out, 'label'])
loss = model.AveragedLoss(sq, "avg_loss")
grad_map = model.AddGradientOperators([loss])
self.assertIsInstance(grad_map['fc_w'], core.BlobReference)
return (model, perfect_model, data, label)
def testDense(self):
model, perfect_model, data, label = self._createDense()
optimizer = self.build_optimizer(model)
workspace.FeedBlob('data', data[0])
workspace.FeedBlob('label', label[0])
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net, True)
for _ in range(2000):
idx = np.random.randint(data.shape[0])
workspace.FeedBlob('data', data[idx])
workspace.FeedBlob('label', label[idx])
workspace.RunNet(model.net.Proto().name)
np.testing.assert_allclose(
perfect_model[np.newaxis, :],
workspace.FetchBlob('fc_w'),
atol=1e-2
)
self.check_optimizer(optimizer)
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
def testGPUDense(self, dtype=core.DataType.FLOAT):
device_opt = core.DeviceOption(caffe2_pb2.CUDA, 0)
with core.DeviceScope(device_opt):
model, _perfect_model, data, label = self._createDense(dtype)
if dtype == core.DataType.FLOAT16:
fc_fp32_for_host = model.HalfToFloat('fc', 'fc_fp32_for_host')
model.CopyGPUToCPU(fc_fp32_for_host, 'fc_cpu')
else:
model.CopyGPUToCPU('fc', 'fc_cpu')
workspace.FeedBlob('data', data[0])
workspace.FeedBlob('label', label[0])
# Add some CPU ops
brew.fc(model, 'fc_cpu', 'fc2', dim_in=1, dim_out=10, axis=0)
# Create optimizer in default device scope
self.build_optimizer(model)
if self._skip_gpu:
return
# Run net to see it does not crash
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net, True)
workspace.RunNet(model.net.Proto().name)
def testSparse(self):
# to test duplicated indices we assign two indices to each weight and
# thus each weight might count once or twice
DUPLICATION = 2
perfect_model = np.array([2, 6, 5, 0, 1]).astype(np.float32)
np.random.seed(123) # make test deterministic
data = np.random.randint(
2,
size=(20, perfect_model.size * DUPLICATION)).astype(np.float32)
label = np.dot(data, np.repeat(perfect_model, DUPLICATION))
model = cnn.CNNModelHelper("NCHW", name="test")
# imitate what model wrapper does
w = model.param_init_net.ConstantFill(
[], 'w', shape=[perfect_model.size], value=0.0)
model.params.append(w)
picked = model.net.Gather([w, 'indices'], 'gather')
out = model.ReduceFrontSum(picked, 'sum')
sq = model.SquaredL2Distance([out, 'label'])
loss = model.AveragedLoss(sq, "avg_loss")
grad_map = model.AddGradientOperators([loss])
self.assertIsInstance(grad_map['w'], core.GradientSlice)
optimizer = self.build_optimizer(model)
workspace.CreateBlob('indices')
workspace.CreateBlob('label')
for indices_type in [np.int32, np.int64]:
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net, True)
for _ in range(2000):
idx = np.random.randint(data.shape[0])
# transform into indices of binary features
indices = np.repeat(np.arange(perfect_model.size),
DUPLICATION)[data[idx] == 1]
if indices.size == 0:
continue
workspace.FeedBlob(
'indices',
indices.reshape((indices.size,)).astype(indices_type)
)
workspace.FeedBlob('label',
np.array(label[idx]).astype(np.float32))
workspace.RunNet(model.net.Proto().name)
np.testing.assert_allclose(
perfect_model,
workspace.FetchBlob('w'),
atol=1e-2
)
self.check_optimizer(optimizer)
class LRModificationTestBase(object):
"""
This is an abstract base class.
Don't inherit from unittest.TestCase, and don't name it 'Test*'.
Do, however, do these things in classes which inherit from this.
"""
def _gradient_ratio_reference(self, model, params, max_gradient_norm):
from caffe2.python import core
sum_squared_norms = 0.0
for param in params:
grad = (
model.param_to_grad[param]
if not isinstance(
model.param_to_grad[param],
core.GradientSlice,
) else model.param_to_grad[param].values
)
val = workspace.FetchBlob(grad)
sum_squared_norms += np.power(np.linalg.norm(val), 2.0)
global_norm = np.sqrt(sum_squared_norms)
clip_norm = max_gradient_norm
norm_ratio = clip_norm / np.maximum(clip_norm, global_norm)
return norm_ratio
def test_global_norm_based_gradient_clipping(self):
max_gradient_norm = 1.0
model, perfect_model, data, label = self._createDense()
opt = self.build_optimizer(model, max_gradient_norm=max_gradient_norm)
params = []
for param in model.GetParams(top_scope=True):
if param in model.param_to_grad:
if not isinstance(
model.param_to_grad[param],
core.GradientSlice,
):
params.append(param)
workspace.FeedBlob('data', data[0])
workspace.FeedBlob('label', label[0])
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net, True)
self.assertIsNotNone(opt._lr_multiplier)
# Run net once
idx = np.random.randint(data.shape[0])
workspace.FeedBlob('data', data[idx])
workspace.FeedBlob('label', label[idx])
workspace.RunNet(model.net.Proto().name)
reference = self._gradient_ratio_reference(
model,
params,
max_gradient_norm,
)
norm_ratio = workspace.FetchBlob(
'norm_clipped_grad_update/norm_ratio')
np.testing.assert_almost_equal(norm_ratio, reference)
self.assertTrue(
reference < 1.0, "Bad test, gradient not being scaled."
)
def test_lr_injection(self):
model, perfect_model, data, label = self._createDense()
opt = self.build_optimizer(
model, max_gradient_norm=1, allow_lr_injection=True
)
workspace.FeedBlob('data', data[0])
workspace.FeedBlob('label', label[0])
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net, True)
# Test LR injection initialized properly
self.assertIsNotNone(opt._lr_multiplier)
self.assertEqual(optimizer.get_lr_injection(), 1)
# Test that we're able to modify the value of the lr_injection
optimizer.set_lr_injection(0)
self.assertEqual(optimizer.get_lr_injection(), 0)
# Test that setting the lr_injector properly propogates to the
# lr_multiplier. Here, we have both lr_injector and norm_ratio that
# affect the lr_multiplier
workspace.RunNet(model.net.Proto().name)
self.assertEqual(workspace.FetchBlob('lr_multiplier'), 0)
|
## @package muji
# Module caffe2.python.muji
"""muji.py does multi-gpu training for caffe2 with no need to change the c++
side code. Everything is defined on the computation graph level.
Currently, here are the assumptions: we only support the following use cases:
- 2 gpus, where peer access is enabled between them.
- 4 gpus, where peer access are enabled between all of them.
- 8 gpus, where peer access are enabled in two groups,
between {1, 2, 3, 4} and {5, 6, 7, 8}.
"""
from caffe2.proto import caffe2_pb2
def OnGPU(gpu_id):
"""A utility function that returns a device option protobuf of the
specified gpu id.
"""
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = gpu_id
return device_option
def OnCPU():
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CPU
return device_option
def Allreduce(net, blobs, reduced_affix="_reduced", gpu_indices=None):
"""The general Allreduce interface that reroutes the function calls.
"""
if gpu_indices is None:
gpu_indices = list(range(len(blobs)))
if len(gpu_indices) != len(blobs):
raise RuntimeError(
"gpu_indices length and blobs length mismatch: %d vs %d" %
(len(gpu_indices), len(blobs))
)
if len(blobs) == 2:
return Allreduce2(net, blobs, reduced_affix, gpu_indices)
elif len(blobs) == 4:
return Allreduce4(net, blobs, reduced_affix, gpu_indices)
elif len(blobs) == 8:
return Allreduce8(net, blobs, reduced_affix, gpu_indices)
else:
return AllreduceFallback(net, blobs, reduced_affix, gpu_indices)
def Allreduce2(net, blobs, reduced_affix, gpu_indices):
"""Allreduce for 2 gpus.
Algorithm: 0r <- 0 + 1, 1r <- 0r, where r means "reduced"
"""
a, b = blobs
gpu_a, gpu_b = gpu_indices
a_reduced = net.Add([a, b], a + reduced_affix, device_option=OnGPU(gpu_a))
b_reduced = a_reduced.Copy(
[],
b + reduced_affix,
device_option=OnGPU(gpu_b)
)
return a_reduced, b_reduced
def Allreduce4(net, blobs, reduced_affix, gpu_indices):
"""Allreduce for 4 gpus.
Algorithm: 2 level reduction.
0r <- 0 + 1, 2r <- 2 + 3
0r <- 0r + 2r
2r <- 0r,
1r <- 0r, 3r <- 2r
"""
a, b, c, d = blobs
gpu_a, gpu_b, gpu_c, gpu_d = gpu_indices
# a_reduced <- a+b, c_reduced <- c + d
a_reduced = net.Add(
[a, b],
str(a) + reduced_affix,
device_option=OnGPU(gpu_a)
)
c_reduced = net.Add(
[c, d],
str(c) + reduced_affix,
device_option=OnGPU(gpu_c)
)
# a_reduced <- a_reduced + c_reduced
a_reduced = a_reduced.Add(c_reduced, a_reduced, device_option=OnGPU(gpu_a))
# broadcast a_reduced to c_reduced
c_reduced = a_reduced.Copy([], c_reduced, device_option=OnGPU(gpu_c))
# broadcast to b and d
b_reduced = a_reduced.Copy(
[],
str(b) + reduced_affix,
device_option=OnGPU(gpu_b)
)
d_reduced = c_reduced.Copy(
[],
str(d) + reduced_affix,
device_option=OnGPU(gpu_d)
)
return a_reduced, b_reduced, c_reduced, d_reduced
def Allreduce8(net, blobs, reduced_affix, gpu_indices):
"""Allreduce for 8 gpus.
Algorithm: 3 level reduction.
0r <- 0 + 1, 2r <- 2 + 3, 4r <- 4 + 5, 6r <- 6 + 7
0r <- 0r + 2r, 4r <- 4r + 6r
0r <- 0r + 4r
4r <- 0r
2r <- 0r, 6r <- 4r
1r <- 0r, 3r <- 2r, 5r <- 4r, 7r <- 6r
"""
reduced = [None] * 8
# Reduction level 1
for i in [0, 2, 4, 6]:
reduced[i] = net.Add(
[blobs[i], blobs[i + 1]],
blobs[i] + reduced_affix,
device_option=OnGPU(gpu_indices[i])
)
# Reduction level 2
for i in [0, 4]:
reduced[i] = net.Add(
[reduced[i], reduced[i + 2]],
str(blobs[i]) + reduced_affix,
device_option=OnGPU(gpu_indices[i])
)
# Reduction level 3: this involves a copy.
reduced_4_copy = reduced[4].Copy(
[],
str(reduced[4]) + '_copy',
device_option=OnGPU(gpu_indices[0])
)
reduced[0] = reduced[0].Add(
reduced_4_copy,
reduced[0],
device_option=OnGPU(gpu_indices[0])
)
# Broadcast level 1
reduced[4] = reduced[0].Copy(
[],
reduced[4],
device_option=OnGPU(gpu_indices[4])
)
# Broadcast level 2
for i in [2, 6]:
reduced[i] = reduced[i - 2].Copy(
[],
reduced[i],
device_option=OnGPU(gpu_indices[i])
)
# Broadcast level 3
for i in [1, 3, 5, 7]:
reduced[i] = reduced[i - 1].Copy(
[],
blobs[i] + reduced_affix,
device_option=OnGPU(gpu_indices[i])
)
return reduced
def AllreduceFallback(net, blobs, reduced_affix, gpu_indices):
"""A fallback option for Allreduce with no assumption on p2p.
Algorithm: a flat operation on gpu 0
0r <- 0
0r <- 0r + i for i in gpu_indices[1:]
ir <- 0r for i in gpu_indices[1:]
"""
reduced = [None] * len(gpu_indices)
# copy first
reduced[0] = net.Copy(
blobs[0],
blobs[0] + reduced_affix,
device_option=OnGPU(gpu_indices[0])
)
# do temp copy and add
temp_name = reduced[0] + '_temp_copy'
for i in range(1, len(gpu_indices)):
temp = net.Copy(
blobs[i],
temp_name,
device_option=OnGPU(gpu_indices[0])
)
reduced[0] = reduced[0].Add(
temp,
reduced[0],
device_option=OnGPU(gpu_indices[0])
)
# Broadcast to everyone else
for i in range(1, len(gpu_indices)):
reduced[i] = net.Copy(
reduced[0],
blobs[i] + reduced_affix,
device_option=OnGPU(gpu_indices[i])
)
return reduced
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import caffe2.python._import_c_extension as C
CAFFE2_NO_OPERATOR_SCHEMA = C.define_caffe2_no_operator_schema
build_options = C.get_build_options()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from future.utils import viewkeys
from multiprocessing import Process, Queue
import numpy as np
import os
import shutil
import tempfile
import unittest
from hypothesis import assume, given
import hypothesis.strategies as st
from caffe2.proto import caffe2_pb2
from caffe2.python import brew, core, cnn, data_parallel_model, dyndep, \
model_helper, optimizer, rnn_cell, workspace, data_parallel_model_utils
from caffe2.python.test_util import TestCase
dyndep.InitOpsLibrary("@/caffe2/caffe2/distributed:file_store_handler_ops")
class TemporaryDirectory:
def __enter__(self):
self.tmpdir = tempfile.mkdtemp()
return self.tmpdir
def __exit__(self, type, value, traceback):
shutil.rmtree(self.tmpdir)
# Note(jiayq): we are yet to find out why Travis gives out an error in gloo
# like:
# RuntimeError: [enforce fail at /home/travis/build/caffe2/caffe2/third_party/gloo/gloo/transport/tcp/device.cc:113] ifa != nullptr. Unable to find interface for: [127.0.1.1]
# See for example https://travis-ci.org/caffe2/caffe2/jobs/262433866
# As a result, we will check if this is travis, and if yes, disable it.
@unittest.skipIf(os.environ.get("TRAVIS"), "DPMTest has a known issue with Travis.")
class DataParallelModelTest(TestCase):
def run_model(self, devices, gpu):
'''
Helper function for test_equiv
'''
def input_builder_fun(model):
return None
def model_build_fun(model, loss_scale):
fc = model.FC("data", "fc", 16, 1,
("ConstantFill", {}), ("ConstantFill", {}))
fc_fl = model.FlattenToVec(fc, "fc_fl")
sigm = model.Sigmoid(fc_fl, "sigm")
sq = model.SquaredL2Distance([sigm, "label"], "sq")
loss = model.AveragedLoss(sq, "loss")
loss = model.Scale(loss, scale=loss_scale)
# For testing explicit sync
model.param_init_net.UniformFill([], ["sync_num"], shape=[1])
return [loss]
def add_optimizer(model):
return optimizer.build_sgd(
model,
0.1,
policy="fixed",
max_gradient_norm=5.0,
allow_lr_injection=True,
)
workspace.ResetWorkspace()
model = cnn.CNNModelHelper(
order="NHWC",
name="test{}".format(devices),
)
data_parallel_model.Parallelize(
model,
input_builder_fun=input_builder_fun,
forward_pass_builder_fun=model_build_fun,
optimizer_builder_fun=add_optimizer,
devices=devices,
cpu_device=not gpu,
shared_model=not gpu,
combine_spatial_bn=not gpu,
)
data_parallel_model.AddBlobSync(model, ["sync_num"])
# Light test for LR names
lr_names = data_parallel_model.GetLearningRateBlobNames(model)
self.assertGreater(len(lr_names), 0)
np.random.seed(2603)
# Each run has same input, independent of number of gpus
batch_size = 64
for i in range(0, 10):
full_data = np.random.rand(batch_size, 16)
full_labels = np.round(full_data[:, 0])
batch_per_device = batch_size // len(devices)
for (j, g) in enumerate(devices):
st = j * batch_per_device
en = st + batch_per_device
data = full_data[st:en, :].astype(np.float32)
labels = full_labels[st:en].astype(np.float32)
with core.DeviceScope(core.DeviceOption(model._device_type, g)):
workspace.FeedBlob(
"{}_{}/data".format(model._device_prefix, g), data
)
workspace.FeedBlob(
"{}_{}/label".format(model._device_prefix, g), labels
)
if i == 0:
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
workspace.FeedBlob(
model._device_prefix + "_0/sync_num",
np.array([i * 2]).astype(np.float32),
device_option=core.DeviceOption(model._device_type, 0))
workspace.RunNet(model.net.Proto().name)
# Test AddBlobSync
for j in model._devices:
sync = workspace.FetchBlob(
model._device_prefix + "_{}/sync_num".format(j))[0]
self.assertTrue(abs(sync - i * 2) < 0.01)
return workspace.FetchBlob("{}_0/fc_w".format(model._device_prefix))
def run_test_locally(self, fn, device_option=None, **kwargs):
# Queue for assertion errors on subprocesses
queue = Queue()
# Capture any exception thrown by the subprocess
def run_fn(*args, **kwargs):
try:
if device_option is None:
fn(*args, **kwargs)
workspace.ResetWorkspace()
else:
with core.DeviceScope(device_option):
fn(*args, **kwargs)
workspace.ResetWorkspace()
except Exception as ex:
queue.put(ex)
# Start N processes in the background
procs = []
for i in range(kwargs['comm_size']):
kwargs['comm_rank'] = i
proc = Process(
target=run_fn,
kwargs=kwargs)
proc.start()
procs.append(proc)
# Test complete, join background processes
while len(procs) > 0:
proc = procs.pop(0)
while proc.is_alive():
proc.join(1)
# Raise exception if we find any.
# Note that the following is executed ALSO after
# the last process was joined, so if ANY exception
# was raised, it will be re-raised here.
if not queue.empty():
raise queue.get()
def test_equiv(self):
'''
Test that the model produces exactly same results given
total batchsize, independent of number of GPUs.
'''
for gpu in [True, False]:
if gpu and (not workspace.has_gpu_support or
workspace.NumCudaDevices() < 2):
continue
result_2gpus = self.run_model([0, 1], gpu=gpu)
result_1gpus = self.run_model([0], gpu=gpu)
self.assertTrue(np.allclose(result_1gpus, result_2gpus))
if not gpu or workspace.NumCudaDevices() >= 4:
result_4gpus = self.run_model(list(range(4)), gpu=gpu)
self.assertTrue(np.allclose(result_1gpus, result_4gpus))
if not gpu or workspace.NumCudaDevices() >= 8:
result_8gpus = self.run_model(list(range(8)), gpu=gpu)
self.assertTrue(np.allclose(result_1gpus, result_8gpus))
if not gpu or workspace.NumCudaDevices() >= 16:
result_16gpus = self.run_model(list(range(16)), gpu=gpu)
self.assertTrue(np.allclose(result_1gpus, result_16gpus))
def test_checkpoint_params(self):
def add_input_ops(model):
pass
def add_model_ops(model, loss_scale):
model.NHWC2NCHW("data", "data_nchw")
model.Conv("data_nchw", 'conv1', 3, 64,
weight_init=("MSRAFill", {}), kernel=7,
stride=2, pad=3, no_bias=0)
model.SpatialBN('conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3, is_test=False)
model.Relu('conv1_spatbn_relu', 'conv1_spatbn_relu')
model.MaxPool('conv1_spatbn_relu', 'pool1', kernel=3, stride=2)
model.FC('pool1', 'fc', dim_in=(64 * 56 * 56), dim_out=100)
model.Sigmoid('fc', 'fc_sigm')
model.Softmax('fc_sigm', 'softmax')
model.LabelCrossEntropy(['softmax', 'label'], 'xent')
loss = model.AveragedLoss('xent', 'loss')
# Add a duplicate param init to ensure it does not cause issues
model.param_init_net.ConstantFill(
[], ["fc_w"], shape=((64 * 56 * 56), 1000)
)
return [loss]
def add_optimizer(model):
optimizer.build_sgd(model, 0.1, policy="fixed", momentum=0.9)
model = cnn.CNNModelHelper(
order="NHWC",
name="test",
)
data_parallel_model.Parallelize_CPU(
model,
input_builder_fun=add_input_ops,
forward_pass_builder_fun=add_model_ops,
optimizer_builder_fun=add_optimizer,
devices=[1, 2, 3],
)
# Only gpu_1 params should be returned (gpu_1 is the first gpu)
checkpoint_params = data_parallel_model.GetCheckpointParams(model)
for p in model.GetParams("cpu_1/"):
self.assertTrue(p in checkpoint_params)
self.assertTrue(p + "_momentum" in checkpoint_params)
for p in model.GetParams("cpu_2/"):
self.assertFalse(p in checkpoint_params)
self.assertTrue(
core.BlobReference("cpu_1/fc_w_momentum") in checkpoint_params)
for c in model.GetComputedParams("cpu_1/"):
self.assertTrue(c in checkpoint_params)
for c in model.GetComputedParams("cpu_2/"):
self.assertFalse(c in checkpoint_params)
self.assertFalse(core.BlobReference("cpu_1/data") in checkpoint_params)
self.assertTrue(core.BlobReference("optimizer_iteration") in checkpoint_params)
def test_net_conversion_and_append_net(self):
other = model_helper.ModelHelper()
fc1 = brew.fc(other, "data", "other_fc1", dim_in=3*227*227, dim_out=10)
fc2 = brew.fc(other, fc1, "other_fc2", dim_in=10, dim_out=10)
brew.fc(other, fc2, "other_fc3", dim_in=10, dim_out=10)
def add_input_ops(model):
model.net.UniformFill([], ["data"], shape=[4, 227, 227, 3])
model.net.UniformFill([], ["label"], shape=[4])
def add_model_ops(model, loss_scale):
model.NHWC2NCHW("data", "data_nchw")
model.Conv("data_nchw", 'conv1', 3, 64,
weight_init=("MSRAFill", {}), kernel=7,
stride=2, pad=3, no_bias=0)
model.SpatialBN('conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3, is_test=False)
model.Relu('conv1_spatbn_relu', 'conv1_spatbn_relu')
model.MaxPool('conv1_spatbn_relu', 'pool1', kernel=3, stride=2)
model.FC('pool1', 'fc', dim_in=(64 * 56 * 56), dim_out=10)
# Append the net and param_init_net of the other model
appendnet = data_parallel_model.ConvertNetForDevice(other.net)
model.net.AppendNet(appendnet)
model.param_init_net.AppendNet(
data_parallel_model.ConvertNetForDevice(other.param_init_net))
model.Sigmoid('fc', 'fc_sigm')
model.Softmax('fc_sigm', 'softmax')
loss = model.AveragedLoss('softmax', 'loss')
return [loss]
def add_optimizer(model):
optimizer.build_sgd(model, 0.1, policy="fixed", momentum=0.9)
model = cnn.CNNModelHelper(
order="NCHW",
name="test",
)
data_parallel_model.Parallelize_CPU(
model,
input_builder_fun=add_input_ops,
forward_pass_builder_fun=add_model_ops,
optimizer_builder_fun=add_optimizer,
devices=range(4)
)
# Just create and run net and confirm no exception is thrown
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
workspace.RunNet(model.net)
def test_synchronization_barrier(self):
def run(comm_rank, comm_size, tmpdir):
def add_input_ops(model):
pass
def add_model_ops(model, loss_scale):
return []
def add_optimizer(model):
pass
store_handler = "store_handler"
workspace.RunOperatorOnce(
core.CreateOperator(
"FileStoreHandlerCreate",
[],
[store_handler],
path=tmpdir))
rendezvous = dict(
kv_handler=store_handler,
shard_id=comm_rank,
num_shards=comm_size,
engine='GLOO',
)
model = cnn.CNNModelHelper(
order="NHWC",
name="test",
)
data_parallel_model.Parallelize_CPU(
model,
input_builder_fun=add_input_ops,
forward_pass_builder_fun=add_model_ops,
optimizer_builder_fun=add_optimizer,
devices=[1, 2, 3],
rendezvous=rendezvous
)
data_parallel_model.RunInitNet(model)
for _ in range(2):
data_parallel_model.Synchronize(model)
with TemporaryDirectory() as tmpdir:
self.run_test_locally(
run,
comm_size=2,
device_option=None,
tmpdir=tmpdir)
def test_device_scope_check(self):
with self.assertRaises(AssertionError):
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
data_parallel_model.Parallelize_GPU(None, None, None)
class RecurrentNetworkParallelTest(TestCase):
def run_model(self, devices, gpu):
'''
Helper function for test_equiv
'''
def input_builder_fun(model):
return None
def model_build_fun(model, loss_scale):
workspace.FeedBlob(
core.ScopedBlobReference("seq_lengths"),
np.array([self.T] * self.batch_per_device, dtype=np.int32)
)
model.param_init_net.ConstantFill(
[],
"hidden_init",
value=0.0,
shape=[1, self.batch_per_device, self.hidden_dim]
)
model.param_init_net.ConstantFill(
[],
"cell_init",
value=0.0,
shape=[1, self.batch_per_device, self.hidden_dim]
)
output, _last_hidden, _, _last_state, = rnn_cell.LSTM(
model=model,
input_blob="data",
seq_lengths="seq_lengths",
initial_states=("hidden_init", "cell_init"),
dim_in=self.input_dim,
dim_out=self.hidden_dim,
scope="partest",
)
# A silly loss function
loss = model.AveragedLoss(
model.Sub([output, "target"], "dist"),
"loss",
)
loss = model.Scale(loss, "loss_scaled", scale=loss_scale)
return [loss]
def param_update_fun(model):
ITER = model.Iter("ITER")
LR = model.net.LearningRate(
[ITER],
"LR",
base_lr=(-0.1),
policy="fixed",
)
ONE = model.param_init_net.ConstantFill(
[], "ONE", shape=[1], value=1.0,
)
for param in model.GetParams():
param_grad = model.param_to_grad[param]
model.WeightedSum([param, ONE, param_grad, LR], param)
assert len(model.GetParams()) == len(model.params) // len(model._devices)
workspace.ResetWorkspace()
model = cnn.CNNModelHelper(
name="recurrent_test{}".format(devices),
)
self.T = 8
self.batch_size = 64
self.input_dim = 8
self.hidden_dim = 31
self.batch_per_device = self.batch_size // len(devices)
data_parallel_model.Parallelize(
model,
input_builder_fun=input_builder_fun,
forward_pass_builder_fun=model_build_fun,
param_update_builder_fun=param_update_fun,
devices=devices,
optimize_gradient_memory=True,
cpu_device=not gpu,
)
# Change all initialization to be ConstantFills so that
# the everything is deterministic
for op in model.param_init_net.Proto().op:
if op.type.endswith('Fill'):
op.type = 'ConstantFill'
# Each run has same input, independent of number of gpus
np.random.seed(20150210)
for i in range(0, 10):
full_data = np.random.rand(self.T, self.batch_size, self.input_dim)
full_target = np.random.rand(
self.T, self.batch_size, self.hidden_dim
)
for (j, g) in enumerate(devices):
st = j * self.batch_per_device
en = st + self.batch_per_device
data = full_data[:, st:en, :].astype(np.float32)
targets = full_target[:, st:en, :].astype(np.float32)
with core.DeviceScope(core.DeviceOption(model._device_type, g)):
workspace.FeedBlob(
"{}_{}/data".format(model._device_prefix, g), data
)
workspace.FeedBlob(
"{}_{}/target".format(model._device_prefix, g), targets
)
if i == 0:
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
workspace.RunNet(model.net.Proto().name)
return workspace.FetchBlob("{}_0/partest/i2h_w".format(model._device_prefix))
def test_equiv_recurrent(self):
'''
Test that the model produces exactly same results given
total batchsize, independent of number of GPUs/CPUs.
'''
for gpu in [True, False]:
if gpu and not workspace.has_gpu_support:
continue
result_2gpus = self.run_model([0, 1], gpu)
result_1gpus = self.run_model([0], gpu)
self.assertTrue(np.allclose(result_1gpus, result_2gpus))
if not gpu or workspace.NumCudaDevices() >= 4:
result_4gpus = self.run_model(list(range(4)), gpu)
self.assertTrue(np.allclose(result_1gpus, result_4gpus))
if not gpu or workspace.NumCudaDevices() >= 8:
result_8gpus = self.run_model(list(range(8)), gpu)
self.assertTrue(np.allclose(result_1gpus, result_8gpus))
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support.")
@unittest.skipIf(workspace.NumCudaDevices() < 2, "Need at least 2 GPUs.")
class SparseDataParallelModelTest(TestCase):
'''
Create and run the model. We try with both storing indices for gather
on CPU and on GPU
'''
def run_model(self, V, gpu_devices, cpu_indices):
def input_builder_fun(model):
return None
def model_build_fun(model, loss_scale):
if cpu_indices:
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
gathered_cpu = model.net.Gather(
[self.vecs, 'indices'], 'gathered_cpu')
gathered = model.CopyCPUToGPU(gathered_cpu, "gathered")
else:
gpu_vecs = model.param_init_net.CopyCPUToGPU(
self.vecs, "gpuvecs",
)
model.params.append(gpu_vecs)
gathered = model.net.Gather([gpu_vecs, 'indices'], 'gathered')
flattened = model.Flatten(gathered, "flattened")
fc = model.FC(flattened, "fc", 16 * 16, 1,
("ConstantFill", {}), ("ConstantFill", {}))
fc_fl = model.FlattenToVec(fc, "fc_fl")
sigm = model.Sigmoid(fc_fl, "sigm")
sq = model.SquaredL2Distance([sigm, "label"], "sq")
loss = model.AveragedLoss(sq, "loss")
loss = model.Scale(loss, scale=loss_scale)
return [loss]
def param_update_fun(model):
ONE = model.param_init_net.ConstantFill(
[], "ONE", shape=[1], value=1.0,
)
LR = model.CopyCPUToGPU(self.LR, "LR")
for param in model.GetParams():
param_grad = model.param_to_grad[param]
if not isinstance(param_grad, core.GradientSlice):
model.WeightedSum([param, ONE, param_grad, LR], param)
else:
param_momentum = model.param_init_net.ConstantFill(
[param],
param + '_momentum',
value=0.0,
)
model.net.SparseMomentumSGDUpdate(
[
param_grad.values,
param_momentum,
LR,
param,
param_grad.indices,
],
[
param_grad.values, param_momentum, param
],
momentum=0.1,
nesterov=0,
)
workspace.ResetWorkspace()
model = cnn.CNNModelHelper(
order="NHWC",
name="sparse_test{}".format(gpu_devices),
)
with core.NameScope("cpu"):
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
self.ITER = model.Iter("ITER")
self.LR = model.net.LearningRate(
[self.ITER],
"LR",
base_lr=(-0.1),
policy="fixed",
)
self.vecs = model.param_init_net.UniformFill(
[], "vecs", shape=[V, 16])
if cpu_indices:
model.params.append(self.vecs)
self.ONE_CPU = model.param_init_net.ConstantFill(
[], "ONE_CPU", shape=[1], value=1.0,
)
data_parallel_model.Parallelize_GPU(
model,
input_builder_fun=input_builder_fun,
forward_pass_builder_fun=model_build_fun,
param_update_builder_fun=param_update_fun,
devices=gpu_devices,
)
# Update the vecs
if cpu_indices:
with core.NameScope("cpu"):
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
for param in model.GetParams():
param_grad = model.param_to_grad[param]
model.ScatterWeightedSum([param, self.ONE_CPU,
param_grad.indices,
param_grad.values,
self.LR],
self.vecs)
else:
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
model.CopyGPUToCPU("gpu_0/gpuvecs", self.vecs)
np.random.seed(2603)
# Each run has same input, independent of number of gpus
batch_size = 64
for i in range(0, 10):
full_indices = np.random.permutation(V)[:batch_size * 16].reshape(
batch_size, 16
)
full_labels = full_indices[:, 0] % 2
batch_per_device = batch_size // len(gpu_devices)
for (j, g) in enumerate(gpu_devices):
st = j * batch_per_device
en = st + batch_per_device
indices = full_indices[st:en, :].astype(np.int32)
labels = full_labels[st:en].astype(np.float32)
device_for_indices = core.DeviceOption(caffe2_pb2.CPU)
if not cpu_indices:
device_for_indices = core.DeviceOption(caffe2_pb2.CUDA, g)
with core.DeviceScope(device_for_indices):
workspace.FeedBlob("gpu_{}/indices".format(g), indices)
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, g)):
workspace.FeedBlob("gpu_{}/label".format(g), labels)
if i == 0:
workspace.RunNetOnce(model.param_init_net)
# Force vecs to be same on all runs
orig_vecs = np.random.rand(V, 16).astype(np.float32)
workspace.FeedBlob(
self.vecs,
orig_vecs
)
if not cpu_indices:
for g in gpu_devices:
workspace.FeedBlob(
"gpu_{}/gpuvecs".format(g),
orig_vecs,
device_option=core.DeviceOption(caffe2_pb2.CUDA, g),
)
workspace.CreateNet(model.net)
workspace.RunNet(model.net.Proto().name)
if len(gpu_devices) == 2:
if not cpu_indices:
idx = workspace.FetchBlob("gpu_0/indices")
idx = list(idx.flatten())
n = len(idx)
nu = len(set(idx))
assert n == nu, "We cannot have duplicate indices"
# Sanity check to see the vecs were updated
self.assertFalse(
np.allclose(workspace.FetchBlob(self.vecs), orig_vecs))
return [workspace.FetchBlob(self.vecs if cpu_indices else "gpu_0/gpuvecs"),
workspace.FetchBlob("gpu_0/fc_w")]
def _test_equiv_sparse(self, cpu_indices):
'''
Test that the model produces exactly same results given
total batchsize, independent of number of GPUs.
'''
V = 10000
result_2gpus = self.run_model(V, [0, 1], cpu_indices)
result_1gpus = self.run_model(V, [0], cpu_indices)
self.assertTrue(np.allclose(result_1gpus[0], result_2gpus[0]))
self.assertTrue(np.allclose(result_1gpus[1], result_2gpus[1]))
if workspace.NumCudaDevices() >= 4:
result_4gpus = self.run_model(V, list(range(4)), cpu_indices)
self.assertTrue(np.allclose(result_1gpus[0], result_4gpus[0]))
self.assertTrue(np.allclose(result_1gpus[1], result_4gpus[1]))
if workspace.NumCudaDevices() >= 8:
result_8gpus = self.run_model(V, list(range(8)), cpu_indices)
self.assertTrue(np.allclose(result_1gpus[0], result_8gpus[0]))
self.assertTrue(np.allclose(result_1gpus[1], result_8gpus[1]))
def test_equiv_sparse(self):
self._test_equiv_sparse(True)
self._test_equiv_sparse(False)
@unittest.skipIf(workspace.NumCudaDevices() < 2, "Need at least 2 GPUs.")
class ParallelizeBMUFTest(TestCase):
def _run_model(self, gpu_devices):
'''
Helper function for test_equiv
'''
def input_builder_fun(model):
return None
def _model_build_fun(self, model, loss_scale):
fc = model.FC(
"data", "fc", 16, 1, ("ConstantFill", {}), ("ConstantFill", {})
)
fc_fl = model.FlattenToVec(fc, "fc_fl")
sigm = model.Sigmoid(fc_fl, "sigm")
sq = model.SquaredL2Distance([sigm, "label"], "sq")
loss = model.AveragedLoss(sq, "loss")
loss = model.Scale(loss, scale=loss_scale)
return [loss]
def _param_update_fun(self, model):
ITER = model.Iter("ITER")
LR = model.net.LearningRate(
[ITER],
"LR",
base_lr=(-0.1),
policy="fixed",
)
ONE = model.param_init_net.ConstantFill(
[], "ONE", shape=[1], value=1.0,
)
for param in model.GetParams():
grad = model.param_to_grad[param]
model.WeightedSum([param, ONE, grad, LR], param)
def _generate_data(self, devices, device_type, device_prefix):
np.random.seed(26)
# Each run has same input, independent of number of gpus
batch_size = 64
for _ in range(0, 10):
full_data = np.random.rand(batch_size, 16)
full_labels = np.round(full_data[:, 0])
batch_per_device = batch_size // len(devices)
for (j, g) in enumerate(devices):
st = j * batch_per_device
en = st + batch_per_device
data = full_data[st:en, :].astype(np.float32)
labels = full_labels[st:en].astype(np.float32)
with core.DeviceScope(core.DeviceOption(device_type, g)):
workspace.FeedBlob("{}_{}/data".format(device_prefix, g), data)
workspace.FeedBlob("{}_{}/label".format(device_prefix, g), labels)
@given(
cpu_device=st.booleans()
)
def test_parallelize_bmuf(self, cpu_device):
assume(cpu_device or workspace.has_gpu_support)
workspace.ResetWorkspace()
model = cnn.CNNModelHelper(
order="NHWC",
name="test"
)
devices = [0, 1]
def input_builder_fun(model):
return None
if not cpu_device:
device_type = caffe2_pb2.CUDA
device_prefix = "gpu"
else:
device_type = caffe2_pb2.CPU
device_prefix = "cpu"
self._generate_data(devices, device_type, device_prefix)
data_parallel_model.Parallelize_BMUF(
model,
input_builder_fun,
self._model_build_fun,
self._param_update_fun,
devices=devices,
cpu_device=cpu_device
)
data_parallel_model.RunInitNet(model)
# Check initial momentum params are zeros
self.assertEqual(
list(viewkeys(model._device_grouped_blobs)), ['fc_w', 'fc_b']
)
self.assertEqual(workspace.FetchBlob('{}_0/fc_b_v'.format(device_prefix)), 0)
np.testing.assert_equal(
workspace.FetchBlob('{}_0/fc_w_v'.format(device_prefix)),
np.zeros(16).astype(np.float32).reshape(1, 16)
)
# Run the algorithm for one iteration to have non-zero params.
data_parallel_model.RunNet(model, 1)
# Save iteration momentum and post local update params
v_b_ = workspace.FetchBlob('{}_0/fc_b_v'.format(device_prefix))
v_w_ = workspace.FetchBlob('{}_0/fc_w_v'.format(device_prefix))
workspace.RunNetOnce(model.net)
b_0_ = workspace.FetchBlob('{}_0/fc_b'.format(device_prefix))
w_0_ = workspace.FetchBlob('{}_0/fc_w'.format(device_prefix))
b_1_ = workspace.FetchBlob('{}_1/fc_b'.format(device_prefix))
w_1_ = workspace.FetchBlob('{}_1/fc_w'.format(device_prefix))
# Compute block gradients.
b_g_ = workspace.FetchBlob('{}_0/fc_b_g'.format(device_prefix))
w_g_ = workspace.FetchBlob('{}_0/fc_w_g'.format(device_prefix))
workspace.RunNetOnce(model._global_model_param_updates_net)
g_b = (b_0_ + b_1_) / 2 - b_g_
g_w = (w_0_ + w_1_) / 2 - w_g_
v_b = workspace.FetchBlob('{}_0/fc_b_v'.format(device_prefix))
v_w = workspace.FetchBlob('{}_0/fc_w_v'.format(device_prefix))
w_g = workspace.FetchBlob('{}_0/fc_w_g'.format(device_prefix))
b_g = workspace.FetchBlob('{}_0/fc_b_g'.format(device_prefix))
w_0 = workspace.FetchBlob('{}_0/fc_w'.format(device_prefix))
b_0 = workspace.FetchBlob('{}_0/fc_b'.format(device_prefix))
w_1 = workspace.FetchBlob('{}_1/fc_w'.format(device_prefix))
b_1 = workspace.FetchBlob('{}_1/fc_b'.format(device_prefix))
# Check momentum update step
np.testing.assert_equal(v_b, 0.5 * v_b_ + g_b)
np.testing.assert_equal(v_w, 0.5 * v_w_ + g_w)
np.testing.assert_equal(w_g, w_0)
np.testing.assert_equal(w_g, w_1)
np.testing.assert_equal(b_g, b_0)
np.testing.assert_equal(b_g, b_1)
# Check params update step
np.testing.assert_equal(w_0, w_g_ + v_w)
np.testing.assert_equal(b_0, b_g_ + v_b)
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support.")
@unittest.skipIf(workspace.NumCudaDevices() < 2, "Need at least 2 GPUs.")
class SparseDataParallelModelTestWithSharedIndices(TestCase):
'''
Create and run the model. We try with both storing indices for gather
on CPU and on GPU
'''
def run_model(self, V, gpu_devices):
def input_builder_fun(model):
return None
def model_build_fun(model, loss_scale):
gpu_vecs_gathered = []
gpu_vecs = []
for num, vec in enumerate(self.vecs):
gpu_vec = model.param_init_net.CopyCPUToGPU(
vec, 'gpuvec_{}'.format(num),
)
if num != 2:
model.params.append(gpu_vec)
gpu_vecs.append(gpu_vec)
for num, gpu_vec in enumerate(gpu_vecs):
gpu_vec_gathered = model.net.Gather(
[gpu_vec, 'indices'],
['gpu_vec_gathered_{}'.format(num)]
)
gpu_vecs_gathered.append(gpu_vec_gathered)
assert len(gpu_vecs_gathered) == 3
fc = model.net.FC(
[
gpu_vecs_gathered[2],
gpu_vecs_gathered[0],
gpu_vecs_gathered[1],
],
['fc'],
)
_, loss = model.net.SoftmaxWithLoss(
[fc, 'label'],
['ce_loss', 'avg_loss'],
only_loss=True,
)
loss = model.Scale(loss, scale=loss_scale)
model.net.Print(loss, [], limit=10)
return [loss]
def param_update_fun(model):
ONE = model.param_init_net.ConstantFill(
[], "ONE", shape=[1], value=1.0,
)
LR = model.CopyCPUToGPU(self.LR, "LR")
for param in model.GetParams():
param_grad = model.param_to_grad[param]
if not isinstance(param_grad, core.GradientSlice):
model.WeightedSum([param, ONE, param_grad, LR], param)
else:
model.net.ScatterWeightedSum(
[
param,
ONE,
param_grad.indices,
param_grad.values,
ONE,
],
param,
)
workspace.ResetWorkspace()
model = cnn.CNNModelHelper(
order="NHWC",
name="sparse_test{}".format(gpu_devices),
)
batch_size = 32
batch_per_device = batch_size // len(gpu_devices)
with core.NameScope("cpu"):
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
self.ITER = model.Iter("ITER")
self.LR = model.net.LearningRate(
[self.ITER],
"LR",
base_lr=(-0.1),
policy="fixed",
)
'''
self.vecs consists of 3 big blobs on which we call Gather:
1) FC weights, shape=(V, 16)
2) FC bias, shape=(V)
3) FC input, shape=(batch_per_device, 16)
'''
self.vecs = [
model.param_init_net.UniformFill(
[], "vec_{}".format(num), shape=[V, 16])
for num in range(2)
]
self.vecs.append(
model.param_init_net.UniformFill(
[],
"vec_2", shape=[batch_per_device, 16]
)
)
self.ONE_CPU = model.param_init_net.ConstantFill(
[], "ONE_CPU", shape=[1], value=1.0,
)
data_parallel_model.Parallelize_GPU(
model,
input_builder_fun=input_builder_fun,
forward_pass_builder_fun=model_build_fun,
param_update_builder_fun=param_update_fun,
devices=gpu_devices,
)
# Update the vecs
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
for num, vec in enumerate(self.vecs[:-1]):
model.CopyGPUToCPU("gpu_0/gpuvec_{}".format(num), vec)
# Each run has same input, independent of number of gpus
for i in range(0, 10):
np.random.seed(2603)
full_indices = np.random.permutation(V)[:batch_size].reshape(
batch_size
)
full_labels = full_indices[:] % batch_per_device
for (j, g) in enumerate(gpu_devices):
st = j * batch_per_device
en = st + batch_per_device
indices = full_indices[st:en].astype(np.int32)
labels = full_labels[st:en].astype(np.int32)
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, g)):
workspace.FeedBlob("gpu_{}/indices".format(g), indices)
workspace.FeedBlob("gpu_{}/label".format(g), labels)
if i == 0:
workspace.RunNetOnce(model.param_init_net)
# Force vecs to be same on all runs
orig_vecs = [
np.random.rand(V, 16).astype(np.float32),
np.random.rand(V).astype(np.float32),
np.random.rand(V, 16).astype(np.float32),
]
for vec, orig_vec in zip(self.vecs, orig_vecs):
workspace.FeedBlob(
vec,
orig_vec
)
for g in gpu_devices:
for num, orig_vec in enumerate(orig_vecs):
workspace.FeedBlob(
"gpu_{}/gpuvec_{}".format(g, num),
orig_vec,
device_option=core.DeviceOption(
caffe2_pb2.CUDA, g),
)
workspace.CreateNet(model.net)
workspace.RunNet(model.net.Proto().name)
idx = workspace.FetchBlob('gpu_0/indices')
grad_slices = [
workspace.FetchBlob(
'gpu_{}/gpu_vec_gathered_{}_grad'.format(g, num))
for g in gpu_devices for num in range(2)
]
for grad_slice in grad_slices:
# print (len(idx), len(grad_slice))
assert len(idx) == len(grad_slice), (
'Number of indices {} is not same as number of gradient '
'slices {}. This might lead to illegal memory access'.format(
len(idx), len(grad_slice)
)
)
def test_sparse_shared_indices_gpu(self):
'''
Test that the model has same number of indices and gradient rows
given total batchsize, independent of number of GPUs.
'''
V = 10000
self.run_model(V, [0, 1])
self.run_model(V, [0])
if workspace.NumCudaDevices() >= 4:
self.run_model(V, list(range(4)))
if workspace.NumCudaDevices() >= 8:
self.run_model(V, list(range(8)))
@unittest.skipIf(workspace.has_gpu_support, "No GPU support")
@unittest.skipIf(workspace.NumCudaDevices() < 4, "Test requires at least 4 GPUs")
class DeviceShiftTest(TestCase):
def create_model(self):
def input_builder_fun(model):
model.param_init_net.UniformFill([], ["data"], shape=[32, 8])
def model_build_fun(model, loss_scale):
fc1 = brew.fc(model, "data", "fc1", dim_in=8, dim_out=8)
fc2 = brew.fc(model, fc1, "fc2", dim_in=8, dim_out=8)
fc3 = brew.fc(model, fc2, "fc3", dim_in=8, dim_out=8)
fc4 = brew.fc(model, fc3, "fc4", dim_in=8, dim_out=8)
fc5 = brew.fc(model, fc4, "fc5", dim_in=8, dim_out=8)
loss = model.net.SumElements([fc5], ["loss"])
return [loss]
def add_optimizer(model):
return optimizer.build_sgd(model, 0.1, policy="fixed")
model = model_helper.ModelHelper()
data_parallel_model.Parallelize(
model,
input_builder_fun=input_builder_fun,
forward_pass_builder_fun=model_build_fun,
optimizer_builder_fun=add_optimizer,
devices=[0, 1, 2, 3],
)
return model
def test_activation_blobs(self):
model = self.create_model()
activations = data_parallel_model_utils.GetActivationBlobs(model)
self.assertEqual(activations, ["fc1", "fc2", "fc3", "fc4", "fc5", "loss"])
def test_shift_gpu(self):
model = self.create_model()
data_parallel_model_utils.ShiftActivationDevices(
model,
activations=["fc4", "fc5"],
shifts={0: 4, 1: 4, 2: 5, 3: 5},
)
for op in model.param_init_net.Proto().op:
for outp in op.output:
prefix = outp.split("/")[0]
if outp.split("/")[-1] in set(['fc4_w', 'fc5_w', 'fc4_b', 'fc5_b']):
if prefix == 'gpu_0' or prefix == 'gpu_1':
self.assertEqual(op.device_option.cuda_gpu_id, 4)
else:
self.assertEqual(op.device_option.cuda_gpu_id, 5)
if outp.split("/")[-1] in set(['fc1_w', 'fc2_w', 'fc3_b', 'fc3_w']):
gpu_id = int(prefix.split("_")[-1])
self.assertEqual(gpu_id, op.device_option.cuda_gpu_id)
# Test that we can run the net
if workspace.NumCudaDevices() >= 6:
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
workspace.RunNet(model.net.Proto().name)
if __name__ == "__main__":
import unittest
unittest.main()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from caffe2.python import core, workspace
from caffe2.proto import caffe2_pb2
from caffe2.python.test_util import TestCase
import unittest
core.GlobalInit(["caffe2", "--caffe2_cpu_numa_enabled=1"])
def build_test_net(net_name):
net = core.Net(net_name)
net.Proto().type = "async_scheduling"
numa_device_option = caffe2_pb2.DeviceOption()
numa_device_option.device_type = caffe2_pb2.CPU
numa_device_option.numa_node_id = 0
net.ConstantFill([], "output_blob_0", shape=[1], value=3.14,
device_option=numa_device_option)
numa_device_option.numa_node_id = 1
net.ConstantFill([], "output_blob_1", shape=[1], value=3.14,
device_option=numa_device_option)
gpu_device_option = caffe2_pb2.DeviceOption()
gpu_device_option.device_type = caffe2_pb2.CUDA
gpu_device_option.cuda_gpu_id = 0
net.CopyCPUToGPU("output_blob_0", "output_blob_0_gpu",
device_option=gpu_device_option)
net.CopyCPUToGPU("output_blob_1", "output_blob_1_gpu",
device_option=gpu_device_option)
return net
@unittest.skipIf(not workspace.IsNUMAEnabled(), "NUMA is not enabled")
@unittest.skipIf(workspace.GetNumNUMANodes() < 2, "Not enough NUMA nodes")
@unittest.skipIf(not workspace.has_gpu_support, "No GPU support")
class NUMATest(TestCase):
def test_numa(self):
net = build_test_net("test_numa")
workspace.RunNetOnce(net)
self.assertEqual(workspace.GetBlobNUMANode("output_blob_0"), 0)
self.assertEqual(workspace.GetBlobNUMANode("output_blob_1"), 1)
if __name__ == '__main__':
unittest.main()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import hypothesis.strategies as st
import numpy as np
import numpy.testing as npt
import unittest
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
from caffe2.python import (
layer_model_instantiator,
core,
schema,
workspace,
)
from caffe2.python.layers.layers import (
InstantiationContext,
)
from caffe2.python.layers.tags import Tags
from caffe2.python.layer_test_util import (
LayersTestCase,
OpSpec,
)
from caffe2.python.layers.layers import (
IdList,
set_request_only,
is_request_only_scalar,
get_key,
)
import logging
logger = logging.getLogger(__name__)
class TestLayers(LayersTestCase):
def testAddLoss(self):
input_record_LR = self.new_record(
schema.Struct(
('label', schema.Scalar((np.float64, (1, )))),
('logit', schema.Scalar((np.float32, (2, )))),
('weight', schema.Scalar((np.float64, (1, ))))
)
)
loss_LR = self.model.BatchLRLoss(input_record_LR)
self.model.add_loss(loss_LR)
assert 'unnamed' in self.model.loss
self.assertEqual(
schema.Scalar((np.float32, tuple())), self.model.loss.unnamed
)
self.assertEqual(loss_LR, self.model.loss.unnamed)
self.model.add_loss(loss_LR, 'addLoss')
assert 'addLoss' in self.model.loss
self.assertEqual(
schema.Scalar((np.float32, tuple())), self.model.loss.addLoss
)
self.assertEqual(loss_LR, self.model.loss.addLoss)
self.model.add_loss(
schema.Scalar(
dtype=np.float32, blob=core.BlobReference('loss_blob_1')
), 'addLoss'
)
assert 'addLoss_auto_0' in self.model.loss
self.assertEqual(
schema.Scalar((np.float32, tuple())), self.model.loss.addLoss_auto_0
)
assert core.BlobReference('loss_blob_1') in self.model.loss.field_blobs()
self.model.add_loss(
schema.Struct(
(
'structName', schema.Scalar(
dtype=np.float32,
blob=core.BlobReference('loss_blob_2')
)
)
), 'addLoss'
)
assert 'addLoss_auto_1' in self.model.loss
self.assertEqual(
schema.Struct(('structName', schema.Scalar((np.float32, tuple())))),
self.model.loss.addLoss_auto_1
)
assert core.BlobReference('loss_blob_2') in self.model.loss.field_blobs()
loss_in_tuple_0 = schema.Scalar(
dtype=np.float32, blob=core.BlobReference('loss_blob_in_tuple_0')
)
loss_in_tuple_1 = schema.Scalar(
dtype=np.float32, blob=core.BlobReference('loss_blob_in_tuple_1')
)
loss_tuple = schema.NamedTuple(
'loss_in_tuple', * [loss_in_tuple_0, loss_in_tuple_1]
)
self.model.add_loss(loss_tuple, 'addLoss')
assert 'addLoss_auto_2' in self.model.loss
self.assertEqual(
schema.Struct(
('loss_in_tuple_0', schema.Scalar((np.float32, tuple()))),
('loss_in_tuple_1', schema.Scalar((np.float32, tuple())))
), self.model.loss.addLoss_auto_2
)
assert core.BlobReference('loss_blob_in_tuple_0')\
in self.model.loss.field_blobs()
assert core.BlobReference('loss_blob_in_tuple_1')\
in self.model.loss.field_blobs()
def testAddOutputSchema(self):
# add the first field
self.model.add_output_schema('struct', schema.Struct())
expected_output_schema = schema.Struct(('struct', schema.Struct()))
self.assertEqual(
self.model.output_schema,
expected_output_schema,
)
# add the second field
self.model.add_output_schema('scalar', schema.Scalar(np.float64))
expected_output_schema = schema.Struct(
('struct', schema.Struct()),
('scalar', schema.Scalar(np.float64)),
)
self.assertEqual(
self.model.output_schema,
expected_output_schema,
)
# overwrite a field should raise
with self.assertRaises(AssertionError):
self.model.add_output_schema('scalar', schema.Struct())
def _test_net(self, net, ops_list):
"""
Helper function to assert the net contains some set of operations and
then to run the net.
Inputs:
net -- the network to test and run
ops_list -- the list of operation specifications to check for
in the net
"""
ops_output = self.assertNetContainOps(net, ops_list)
workspace.RunNetOnce(net)
return ops_output
def testFCWithoutBias(self):
output_dims = 2
fc_without_bias = self.model.FCWithoutBias(
self.model.input_feature_schema.float_features, output_dims)
self.model.output_schema = fc_without_bias
self.assertEqual(
schema.Scalar((np.float32, (output_dims, ))),
fc_without_bias
)
train_init_net, train_net = self.get_training_nets()
init_ops = self.assertNetContainOps(
train_init_net,
[
OpSpec("UniformFill", None, None),
]
)
mat_mul_spec = OpSpec(
"MatMul",
[
self.model.input_feature_schema.float_features(),
init_ops[0].output[0],
],
fc_without_bias.field_blobs()
)
self.assertNetContainOps(train_net, [mat_mul_spec])
predict_net = self.get_predict_net()
self.assertNetContainOps(predict_net, [mat_mul_spec])
def testSparseLookupSumPooling(self):
record = schema.NewRecord(self.model.net, schema.Struct(
('sparse', schema.Struct(
('sparse_feature_0', schema.List(
schema.Scalar(np.int64,
metadata=schema.Metadata(categorical_limit=1000)))),
)),
))
embedding_dim = 64
embedding_after_pooling = self.model.SparseLookup(
record.sparse.sparse_feature_0, [embedding_dim], 'Sum')
self.model.output_schema = schema.Struct()
self.assertEqual(
schema.Scalar((np.float32, (embedding_dim, ))),
embedding_after_pooling
)
train_init_net, train_net = self.get_training_nets()
init_ops = self.assertNetContainOps(
train_init_net,
[
OpSpec("UniformFill", None, None),
OpSpec("ConstantFill", None, None),
]
)
sparse_lookup_op_spec = OpSpec(
'SparseLengthsSum',
[
init_ops[0].output[0],
record.sparse.sparse_feature_0.items(),
record.sparse.sparse_feature_0.lengths(),
],
[embedding_after_pooling()]
)
self.assertNetContainOps(train_net, [sparse_lookup_op_spec])
predict_net = self.get_predict_net()
self.assertNetContainOps(predict_net, [sparse_lookup_op_spec])
@given(
use_hashing=st.booleans(),
modulo=st.integers(min_value=100, max_value=200),
)
def testSparseFeatureHashIdList(self, use_hashing, modulo):
record = schema.NewRecord(
self.model.net,
schema.List(schema.Scalar(
np.int64,
metadata=schema.Metadata(categorical_limit=60000)
))
)
output_schema = self.model.SparseFeatureHash(
record,
modulo=modulo,
use_hashing=use_hashing)
self.model.output_schema = output_schema
self.assertEqual(len(self.model.layers), 1)
self.assertEqual(output_schema._items.metadata.categorical_limit,
modulo)
train_init_net, train_net = self.get_training_nets()
@given(
use_hashing=st.booleans(),
modulo=st.integers(min_value=100, max_value=200),
)
def testSparseFeatureHashIdScoreList(self, use_hashing, modulo):
record = schema.NewRecord(self.model.net,
schema.Map(schema.Scalar(np.int64,
metadata=schema.Metadata(
categorical_limit=60000)),
np.float32))
output_schema = self.model.SparseFeatureHash(
record,
modulo=modulo,
use_hashing=use_hashing)
self.model.output_schema = output_schema
self.assertEqual(len(self.model.layers), 1)
self.assertEqual(output_schema._items.keys.metadata.categorical_limit,
modulo)
train_init_net, train_net = self.get_training_nets()
def testSparseLookupIncorrectPositionWeightedOnIdList(self):
'''
Currently the implementation of SparseLookup assumed input is id_score_list
when use PositionWeighted.
'''
record = schema.NewRecord(self.model.net, schema.Struct(
('sparse', schema.Struct(
('sparse_feature_0', schema.List(
schema.Scalar(np.int64,
metadata=schema.Metadata(categorical_limit=1000)))),
)),
))
embedding_dim = 64
with self.assertRaises(AssertionError):
self.model.SparseLookup(
record.sparse.sparse_feature_0, [embedding_dim], 'PositionWeighted')
def testSparseLookupPositionWeightedOnIdList(self):
record = schema.NewRecord(self.model.net, schema.Struct(
('sparse', schema.Struct(
('sparse_feature_0', schema.List(
schema.Scalar(np.int64,
metadata=schema.Metadata(categorical_limit=1000)))),
)),
))
# convert id_list to id_score_list with PositionWeighted layer
sparse_segment = record.sparse.sparse_feature_0
pos_w_layer = self.model.PositionWeighted(sparse_segment)
sparse_segment = schema.Map(
keys=get_key(sparse_segment),
values=pos_w_layer.position_weights,
lengths_blob=sparse_segment.lengths
)
embedding_dim = 64
embedding_after_pooling = self.model.SparseLookup(
sparse_segment, [embedding_dim], 'PositionWeighted')
self.model.output_schema = schema.Struct()
self.assertEqual(
schema.Scalar((np.float32, (embedding_dim, ))),
embedding_after_pooling
)
train_init_net, train_net = self.get_training_nets()
self.assertNetContainOps(
train_init_net,
[
OpSpec("ConstantFill", None, None), # position_weights/pos_w
OpSpec("UniformFill", None, None),
OpSpec("ConstantFill", None, None),
]
)
self.assertNetContainOps(train_net, [
OpSpec("LengthsRangeFill", None, None),
OpSpec("Gather", None, None),
OpSpec("SparseLengthsWeightedSum", None, None),
])
predict_net = self.get_predict_net()
self.assertNetContainOps(predict_net, [
OpSpec("LengthsRangeFill", None, None),
OpSpec("Gather", None, None),
OpSpec("SparseLengthsWeightedSum", None, None),
])
def testSparseLookupPositionWeightedOnIdScoreList(self):
record = schema.NewRecord(self.model.net, schema.Struct(
('sparse', schema.Struct(
('id_score_list_0', schema.Map(
schema.Scalar(
np.int64,
metadata=schema.Metadata(
categorical_limit=1000
),
),
np.float32
)),
)),
))
embedding_dim = 64
embedding_after_pooling = self.model.SparseLookup(
record.sparse.id_score_list_0, [embedding_dim], 'PositionWeighted')
self.model.output_schema = schema.Struct()
self.assertEqual(
schema.Scalar((np.float32, (embedding_dim, ))),
embedding_after_pooling
)
train_init_net, train_net = self.get_training_nets()
init_ops = self.assertNetContainOps(
train_init_net,
[
OpSpec("UniformFill", None, None),
OpSpec("ConstantFill", None, None),
]
)
sparse_lookup_op_spec = OpSpec(
'SparseLengthsWeightedSum',
[
init_ops[0].output[0],
record.sparse.id_score_list_0.values(),
record.sparse.id_score_list_0.keys(),
record.sparse.id_score_list_0.lengths(),
],
[embedding_after_pooling()]
)
self.assertNetContainOps(train_net, [sparse_lookup_op_spec])
predict_net = self.get_predict_net()
self.assertNetContainOps(predict_net, [sparse_lookup_op_spec])
def testPairwiseDotProductWithAllEmbeddings(self):
embedding_dim = 64
N = 5
record = schema.NewRecord(self.model.net, schema.Struct(
('all_embeddings', schema.Scalar(
((np.float32, (N, embedding_dim)))
)),
))
current = self.model.PairwiseDotProduct(
record, N * N)
self.assertEqual(
schema.Scalar((np.float32, (N * N, ))),
current
)
train_init_net, train_net = self.get_training_nets()
self.assertNetContainOps(train_init_net, [])
self.assertNetContainOps(train_net, [
OpSpec("BatchMatMul", None, None),
OpSpec("Flatten", None, None),
])
def testPairwiseDotProductWithXandYEmbeddings(self):
embedding_dim = 64
record = schema.NewRecord(self.model.net, schema.Struct(
('x_embeddings', schema.Scalar(
((np.float32, (5, embedding_dim)))
)),
('y_embeddings', schema.Scalar(
((np.float32, (6, embedding_dim)))
)),
))
current = self.model.PairwiseDotProduct(
record, 5 * 6)
self.assertEqual(
schema.Scalar((np.float32, (5 * 6, ))),
current
)
train_init_net, train_net = self.get_training_nets()
self.assertNetContainOps(train_init_net, [])
self.assertNetContainOps(train_net, [
OpSpec("BatchMatMul", None, None),
OpSpec("Flatten", None, None),
])
def testPairwiseDotProductWithXandYEmbeddingsAndGather(self):
embedding_dim = 64
output_idx = [1, 3, 5]
output_idx_blob = self.model.add_global_constant(
str(self.model.net.NextScopedBlob('pairwise_dot_product_gather')),
output_idx,
dtype=np.int32,
)
indices_to_gather = schema.Scalar(
(np.int32, len(output_idx)),
output_idx_blob,
)
record = schema.NewRecord(self.model.net, schema.Struct(
('x_embeddings', schema.Scalar(
((np.float32, (5, embedding_dim)))
)),
('y_embeddings', schema.Scalar(
((np.float32, (6, embedding_dim)))
)),
('indices_to_gather', indices_to_gather),
))
current = self.model.PairwiseDotProduct(
record, len(output_idx))
# This assert is not necessary,
# output size is passed into PairwiseDotProduct
self.assertEqual(
schema.Scalar((np.float32, (len(output_idx), ))),
current
)
train_init_net, train_net = self.get_training_nets()
self.assertNetContainOps(train_init_net, [])
self.assertNetContainOps(train_net, [
OpSpec("BatchMatMul", None, None),
OpSpec("Flatten", None, None),
OpSpec("BatchGather", None, None),
])
def testPairwiseDotProductIncorrectInput(self):
embedding_dim = 64
record = schema.NewRecord(self.model.net, schema.Struct(
('x_embeddings', schema.Scalar(
((np.float32, (5, embedding_dim)))
)),
))
with self.assertRaises(AssertionError):
self.model.PairwiseDotProduct(
record, 25)
record = schema.NewRecord(self.model.net, schema.Struct(
('all_embeddings', schema.List(np.float32))
))
with self.assertRaises(AssertionError):
self.model.PairwiseDotProduct(
record, 25)
def testConcat(self):
embedding_dim = 64
input_record = self.new_record(schema.Struct(
('input1', schema.Scalar((np.float32, (embedding_dim, )))),
('input2', schema.Scalar((np.float32, (embedding_dim, )))),
('input3', schema.Scalar((np.float32, (embedding_dim, )))),
))
output = self.model.Concat(input_record)
self.assertEqual(
schema.Scalar((np.float32, ((len(input_record.fields) * embedding_dim, )))),
output
)
# Note that in Concat layer we assume first dimension is batch.
# so input is B * embedding_dim
# add_axis=1 make it B * 1 * embedding_dim
# concat on axis=1 make it B * N * embedding_dim
output = self.model.Concat(input_record, axis=1, add_axis=1)
self.assertEqual(
schema.Scalar((np.float32, ((len(input_record.fields), embedding_dim)))),
output
)
def testSamplingTrain(self):
output_dims = 1000
indices = self.new_record(schema.Scalar((np.int32, (10,))))
sampling_prob = self.new_record(schema.Scalar((np.float32, (10, ))))
sampled_fc = self.model.SamplingTrain(
schema.Struct(
('input', self.model.input_feature_schema.float_features),
('indices', indices),
('sampling_prob', sampling_prob),
),
"FC",
output_dims,
)
self.model.output_schema = sampled_fc
# Check that we don't add prediction layer into the model
self.assertEqual(1, len(self.model.layers))
self.assertEqual(
schema.Scalar((np.float32, (output_dims, ))),
sampled_fc
)
train_init_net, train_net = self.get_training_nets()
init_ops = self.assertNetContainOps(
train_init_net,
[
OpSpec("UniformFill", None, None),
OpSpec("UniformFill", None, None),
]
)
sampled_fc_layer = self.model.layers[0]
gather_w_spec = OpSpec(
"Gather",
[
init_ops[0].output[0],
indices(),
],
[
sampled_fc_layer._prediction_layer.train_param_blobs[0]
]
)
gather_b_spec = OpSpec(
"Gather",
[
init_ops[1].output[0],
indices(),
],
[
sampled_fc_layer._prediction_layer.train_param_blobs[1]
]
)
train_fc_spec = OpSpec(
"FC",
[
self.model.input_feature_schema.float_features(),
] + sampled_fc_layer._prediction_layer.train_param_blobs,
sampled_fc.field_blobs()
)
log_spec = OpSpec("Log", [sampling_prob()], [None])
sub_spec = OpSpec(
"Sub",
[sampled_fc.field_blobs()[0], None],
sampled_fc.field_blobs()
)
train_ops = self.assertNetContainOps(
train_net,
[gather_w_spec, gather_b_spec, train_fc_spec, log_spec, sub_spec])
self.assertEqual(train_ops[3].output[0], train_ops[4].input[1])
predict_net = self.get_predict_net()
self.assertNetContainOps(
predict_net,
[
OpSpec(
"FC",
[
self.model.input_feature_schema.float_features(),
init_ops[0].output[0],
init_ops[1].output[0],
],
sampled_fc.field_blobs()
)
]
)
def testBatchLRLoss(self):
input_record = self.new_record(schema.Struct(
('label', schema.Scalar((np.float64, (1,)))),
('logit', schema.Scalar((np.float32, (2,)))),
('weight', schema.Scalar((np.float64, (1,))))
))
loss = self.model.BatchLRLoss(input_record)
self.assertEqual(schema.Scalar((np.float32, tuple())), loss)
def testMarginRankLoss(self):
input_record = self.new_record(schema.Struct(
('pos_prediction', schema.Scalar((np.float32, (1,)))),
('neg_prediction', schema.List(np.float32)),
))
pos_items = np.array([0.1, 0.2, 0.3], dtype=np.float32)
neg_lengths = np.array([1, 2, 3], dtype=np.int32)
neg_items = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype=np.float32)
schema.FeedRecord(
input_record,
[pos_items, neg_lengths, neg_items]
)
loss = self.model.MarginRankLoss(input_record)
self.run_train_net_forward_only()
self.assertEqual(schema.Scalar((np.float32, tuple())), loss)
def testBatchMSELoss(self):
input_record = self.new_record(schema.Struct(
('label', schema.Scalar((np.float64, (1,)))),
('prediction', schema.Scalar((np.float32, (2,)))),
))
loss = self.model.BatchMSELoss(input_record)
self.assertEqual(schema.Scalar((np.float32, tuple())), loss)
def testBatchSigmoidCrossEntropyLoss(self):
input_record = self.new_record(schema.Struct(
('label', schema.Scalar((np.float32, (32,)))),
('prediction', schema.Scalar((np.float32, (32,))))
))
loss = self.model.BatchSigmoidCrossEntropyLoss(input_record)
self.assertEqual(schema.Scalar((np.float32, tuple())), loss)
def testBatchSoftmaxLoss(self):
input_record = self.new_record(schema.Struct(
('label', schema.Scalar((np.float32, tuple()))),
('prediction', schema.Scalar((np.float32, (32,))))
))
loss = self.model.BatchSoftmaxLoss(input_record)
self.assertEqual(schema.Struct(
('softmax', schema.Scalar((np.float32, (32,)))),
('loss', schema.Scalar(np.float32)),
), loss)
def testBatchSoftmaxLossWeight(self):
input_record = self.new_record(schema.Struct(
('label', schema.Scalar((np.float32, tuple()))),
('prediction', schema.Scalar((np.float32, (32,)))),
('weight', schema.Scalar((np.float64, (1,))))
))
loss = self.model.BatchSoftmaxLoss(input_record)
self.assertEqual(schema.Struct(
('softmax', schema.Scalar((np.float32, (32,)))),
('loss', schema.Scalar(np.float32)),
), loss)
@given(
X=hu.arrays(dims=[2, 5]),
)
def testBatchNormalization(self, X):
input_record = self.new_record(schema.Scalar((np.float32, (5,))))
schema.FeedRecord(input_record, [X])
bn_output = self.model.BatchNormalization(input_record)
self.assertEqual(schema.Scalar((np.float32, (5,))), bn_output)
self.model.output_schema = schema.Struct()
train_init_net, train_net = self.get_training_nets()
init_ops = self.assertNetContainOps(
train_init_net,
[
OpSpec("ConstantFill", None, None),
OpSpec("ConstantFill", None, None),
OpSpec("ConstantFill", None, None),
OpSpec("ConstantFill", None, None),
]
)
input_blob = input_record.field_blobs()[0]
output_blob = bn_output.field_blobs()[0]
expand_dims_spec = OpSpec(
"ExpandDims",
[input_blob],
None,
)
train_bn_spec = OpSpec(
"SpatialBN",
[None, init_ops[0].output[0], init_ops[1].output[0],
init_ops[2].output[0], init_ops[3].output[0]],
[output_blob, init_ops[2].output[0], init_ops[3].output[0], None, None],
{'is_test': 0, 'order': 'NCHW', 'momentum': 0.9},
)
test_bn_spec = OpSpec(
"SpatialBN",
[None, init_ops[0].output[0], init_ops[1].output[0],
init_ops[2].output[0], init_ops[3].output[0]],
[output_blob],
{'is_test': 1, 'order': 'NCHW', 'momentum': 0.9},
)
squeeze_spec = OpSpec(
"Squeeze",
[output_blob],
[output_blob],
)
self.assertNetContainOps(
train_net,
[expand_dims_spec, train_bn_spec, squeeze_spec]
)
eval_net = self.get_eval_net()
self.assertNetContainOps(
eval_net,
[expand_dims_spec, test_bn_spec, squeeze_spec]
)
predict_net = self.get_predict_net()
self.assertNetContainOps(
predict_net,
[expand_dims_spec, test_bn_spec, squeeze_spec]
)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
schema.FeedRecord(input_record, [X])
workspace.RunNetOnce(eval_net)
schema.FeedRecord(input_record, [X])
workspace.RunNetOnce(predict_net)
@given(
X=hu.arrays(dims=[5, 2]),
num_to_collect=st.integers(min_value=1, max_value=10),
)
def testLastNWindowCollector(self, X, num_to_collect):
input_record = self.new_record(schema.Scalar(np.float32))
schema.FeedRecord(input_record, [X])
last_n = self.model.LastNWindowCollector(input_record, num_to_collect)
self.run_train_net_forward_only()
output_record = schema.FetchRecord(last_n.last_n)
start = max(0, 5 - num_to_collect)
npt.assert_array_equal(X[start:], output_record())
num_visited = schema.FetchRecord(last_n.num_visited)
npt.assert_array_equal([5], num_visited())
def testUniformSampling(self):
input_record = self.new_record(schema.Scalar(np.int32))
input_array = np.array([3, 10, 11, 15, 20, 99], dtype=np.int32)
schema.FeedRecord(input_record, [input_array])
num_samples = 20
num_elements = 100
uniform_sampling_output = self.model.UniformSampling(
input_record, num_samples, num_elements)
self.model.loss = uniform_sampling_output
self.run_train_net()
samples = workspace.FetchBlob(uniform_sampling_output.samples())
sampling_prob = workspace.FetchBlob(
uniform_sampling_output.sampling_prob())
self.assertEqual(num_samples, len(samples))
np.testing.assert_array_equal(input_array, samples[:len(input_array)])
np.testing.assert_almost_equal(
np.array([float(num_samples) / num_elements] * num_samples,
dtype=np.float32),
sampling_prob
)
def testUniformSamplingWithIncorrectSampleSize(self):
input_record = self.new_record(schema.Scalar(np.int32))
num_samples = 200
num_elements = 100
with self.assertRaises(AssertionError):
self.model.UniformSampling(input_record, num_samples, num_elements)
def testGatherRecord(self):
indices = np.array([1, 3, 4], dtype=np.int32)
dense = np.array(list(range(20)), dtype=np.float32).reshape(10, 2)
lengths = np.array(list(range(10)), dtype=np.int32)
items = np.array(list(range(lengths.sum())), dtype=np.int64)
items_lengths = np.array(list(range(lengths.sum())), dtype=np.int32)
items_items = np.array(list(range(items_lengths.sum())), dtype=np.int64)
record = self.new_record(schema.Struct(
('dense', schema.Scalar(np.float32)),
('sparse', schema.Struct(
('list', schema.List(np.int64)),
('list_of_list', schema.List(schema.List(np.int64))),
)),
('empty_struct', schema.Struct())
))
indices_record = self.new_record(schema.Scalar(np.int32))
input_record = schema.Struct(
('indices', indices_record),
('record', record),
)
schema.FeedRecord(
input_record,
[indices, dense, lengths, items, lengths, items_lengths,
items_items])
gathered_record = self.model.GatherRecord(input_record)
self.assertTrue(schema.equal_schemas(gathered_record, record))
self.run_train_net_forward_only()
gathered_dense = workspace.FetchBlob(gathered_record.dense())
np.testing.assert_array_equal(
np.concatenate([dense[i:i + 1] for i in indices]), gathered_dense)
gathered_lengths = workspace.FetchBlob(
gathered_record.sparse.list.lengths())
np.testing.assert_array_equal(
np.concatenate([lengths[i:i + 1] for i in indices]),
gathered_lengths)
gathered_items = workspace.FetchBlob(
gathered_record.sparse.list.items())
offsets = lengths.cumsum() - lengths
np.testing.assert_array_equal(
np.concatenate([
items[offsets[i]: offsets[i] + lengths[i]]
for i in indices
]), gathered_items)
gathered_items_lengths = workspace.FetchBlob(
gathered_record.sparse.list_of_list.items.lengths())
np.testing.assert_array_equal(
np.concatenate([
items_lengths[offsets[i]: offsets[i] + lengths[i]]
for i in indices
]),
gathered_items_lengths
)
nested_offsets = []
nested_lengths = []
nested_offset = 0
j = 0
for l in lengths:
nested_offsets.append(nested_offset)
nested_length = 0
for _i in range(l):
nested_offset += items_lengths[j]
nested_length += items_lengths[j]
j += 1
nested_lengths.append(nested_length)
gathered_items_items = workspace.FetchBlob(
gathered_record.sparse.list_of_list.items.items())
np.testing.assert_array_equal(
np.concatenate([
items_items[nested_offsets[i]:
nested_offsets[i] + nested_lengths[i]]
for i in indices
]),
gathered_items_items
)
def testMapToRange(self):
input_record = self.new_record(schema.Scalar(np.int32))
indices_blob = self.model.MapToRange(input_record,
max_index=100).indices
self.model.output_schema = schema.Struct()
train_init_net, train_net = self.get_training_nets()
schema.FeedRecord(
input_record,
[np.array([10, 3, 20, 99, 15, 11, 3, 11], dtype=np.int32)]
)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
indices = workspace.FetchBlob(indices_blob())
np.testing.assert_array_equal(
np.array([1, 2, 3, 4, 5, 6, 2, 6], dtype=np.int32),
indices
)
schema.FeedRecord(
input_record,
[np.array([10, 3, 23, 35, 60, 15, 10, 15], dtype=np.int32)]
)
workspace.RunNetOnce(train_net)
indices = workspace.FetchBlob(indices_blob())
np.testing.assert_array_equal(
np.array([1, 2, 7, 8, 9, 5, 1, 5], dtype=np.int32),
indices
)
eval_net = self.get_eval_net()
schema.FeedRecord(
input_record,
[np.array([10, 3, 23, 35, 60, 15, 200], dtype=np.int32)]
)
workspace.RunNetOnce(eval_net)
indices = workspace.FetchBlob(indices_blob())
np.testing.assert_array_equal(
np.array([1, 2, 7, 8, 9, 5, 0], dtype=np.int32),
indices
)
schema.FeedRecord(
input_record,
[np.array([10, 3, 23, 15, 101, 115], dtype=np.int32)]
)
workspace.RunNetOnce(eval_net)
indices = workspace.FetchBlob(indices_blob())
np.testing.assert_array_equal(
np.array([1, 2, 7, 5, 0, 0], dtype=np.int32),
indices
)
predict_net = self.get_predict_net()
schema.FeedRecord(
input_record,
[np.array([3, 3, 20, 23, 151, 35, 60, 15, 200], dtype=np.int32)]
)
workspace.RunNetOnce(predict_net)
indices = workspace.FetchBlob(indices_blob())
np.testing.assert_array_equal(
np.array([2, 2, 3, 7, 0, 8, 9, 5, 0], dtype=np.int32),
indices
)
def testSelectRecordByContext(self):
float_features = self.model.input_feature_schema.float_features
float_array = np.array([1.0, 2.0], dtype=np.float32)
schema.FeedRecord(float_features, [float_array])
with Tags(Tags.EXCLUDE_FROM_PREDICTION):
log_float_features = self.model.Log(float_features, 1)
joined = self.model.SelectRecordByContext(
schema.Struct(
(InstantiationContext.PREDICTION, float_features),
(InstantiationContext.TRAINING, log_float_features),
# TODO: TRAIN_ONLY layers are also generated in eval
(InstantiationContext.EVAL, log_float_features),
)
)
# model.output_schema has to a struct
self.model.output_schema = schema.Struct((
'joined', joined
))
predict_net = layer_model_instantiator.generate_predict_net(self.model)
workspace.RunNetOnce(predict_net)
predict_output = schema.FetchRecord(predict_net.output_record())
npt.assert_array_equal(float_array,
predict_output['joined']())
eval_net = layer_model_instantiator.generate_eval_net(self.model)
workspace.RunNetOnce(eval_net)
eval_output = schema.FetchRecord(eval_net.output_record())
npt.assert_array_equal(np.log(float_array),
eval_output['joined']())
_, train_net = (
layer_model_instantiator.generate_training_nets_forward_only(
self.model
)
)
workspace.RunNetOnce(train_net)
train_output = schema.FetchRecord(train_net.output_record())
npt.assert_array_equal(np.log(float_array),
train_output['joined']())
def testFunctionalLayer(self):
def normalize(net, in_record, out_record):
mean = net.ReduceFrontMean(in_record(), 1)
net.Sub(
[in_record(), mean],
out_record(),
broadcast=1)
normalized = self.model.Functional(
self.model.input_feature_schema.float_features, 1,
normalize, name="normalizer")
# Attach metadata to one of the outputs and use it in FC
normalized.set_type((np.float32, 32))
self.model.output_schema = self.model.FC(normalized, 2)
predict_net = layer_model_instantiator.generate_predict_net(
self.model)
ops = predict_net.Proto().op
assert len(ops) == 3
assert ops[0].type == "ReduceFrontMean"
assert ops[1].type == "Sub"
assert ops[2].type == "FC"
assert len(ops[0].input) == 1
assert ops[0].input[0] ==\
self.model.input_feature_schema.float_features()
assert len(ops[1].output) == 1
assert ops[1].output[0] in ops[2].input
def testFunctionalLayerHelper(self):
mean = self.model.ReduceFrontMean(
self.model.input_feature_schema.float_features, 1)
normalized = self.model.Sub(
schema.Tuple(
self.model.input_feature_schema.float_features, mean),
1, broadcast=1)
# Attach metadata to one of the outputs and use it in FC
normalized.set_type((np.float32, (32,)))
self.model.output_schema = self.model.FC(normalized, 2)
predict_net = layer_model_instantiator.generate_predict_net(
self.model)
ops = predict_net.Proto().op
assert len(ops) == 3
assert ops[0].type == "ReduceFrontMean"
assert ops[1].type == "Sub"
assert ops[2].type == "FC"
assert len(ops[0].input) == 1
assert ops[0].input[0] ==\
self.model.input_feature_schema.float_features()
assert len(ops[1].output) == 1
assert ops[1].output[0] in ops[2].input
def testFunctionalLayerHelperAutoInference(self):
softsign = self.model.Softsign(
schema.Tuple(self.model.input_feature_schema.float_features),
1)
assert softsign.field_type().base == np.float32
assert softsign.field_type().shape == (32,)
self.model.output_schema = self.model.FC(softsign, 2)
predict_net = layer_model_instantiator.generate_predict_net(
self.model)
ops = predict_net.Proto().op
assert len(ops) == 2
assert ops[0].type == "Softsign"
assert ops[1].type == "FC"
assert len(ops[0].input) == 1
assert ops[0].input[0] ==\
self.model.input_feature_schema.float_features()
assert len(ops[0].output) == 1
assert ops[0].output[0] in ops[1].input
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support.")
def testHalfToFloatTypeInference(self):
input = self.new_record(schema.Scalar((np.float32, (32,))))
output = self.model.FloatToHalf(input, 1)
assert output.field_type().base == np.float16
assert output.field_type().shape == (32, )
output = self.model.HalfToFloat(output, 1)
assert output.field_type().base == np.float32
assert output.field_type().shape == (32, )
def testFunctionalLayerHelperAutoInferenceScalar(self):
loss = self.model.AveragedLoss(self.model.input_feature_schema, 1)
self.assertEqual(1, len(loss.field_types()))
self.assertEqual(np.float32, loss.field_types()[0].base)
self.assertEqual(tuple(), loss.field_types()[0].shape)
def testFunctionalLayerInputCoercion(self):
one = self.model.global_constants['ONE']
two = self.model.Add([one, one], 1)
self.model.loss = two
self.run_train_net()
data = workspace.FetchBlob(two.field_blobs()[0])
np.testing.assert_array_equal([2.0], data)
def testFunctionalLayerWithOutputNames(self):
k = 3
topk = self.model.TopK(
self.model.input_feature_schema,
output_names_or_num=['values', 'indices'],
k=k,
)
self.assertEqual(2, len(topk.field_types()))
self.assertEqual(np.float32, topk.field_types()[0].base)
self.assertEqual((k,), topk.field_types()[0].shape)
self.assertEqual(np.int32, topk.field_types()[1].base)
self.assertEqual((k,), topk.field_types()[1].shape)
self.assertEqual(['TopK/values', 'TopK/indices'], topk.field_blobs())
def testFunctionalLayerSameOperatorOutputNames(self):
Con1 = self.model.ConstantFill([], 1, value=1)
Con2 = self.model.ConstantFill([], 1, value=2)
self.assertNotEqual(str(Con1), str(Con2))
def testFunctionalLayerWithOutputDtypes(self):
loss = self.model.AveragedLoss(
self.model.input_feature_schema,
1,
output_dtypes=(np.float32, (1,)),
)
self.assertEqual(1, len(loss.field_types()))
self.assertEqual(np.float32, loss.field_types()[0].base)
self.assertEqual((1,), loss.field_types()[0].shape)
def testPropagateRequestOnly(self):
# test case when output is request only
input_record = self.new_record(schema.Struct(
('input1', schema.Scalar((np.float32, (32, )))),
('input2', schema.Scalar((np.float32, (64, )))),
('input3', schema.Scalar((np.float32, (16, )))),
))
set_request_only(input_record)
concat_output = self.model.Concat(input_record)
self.assertEqual(is_request_only_scalar(concat_output), True)
# test case when output is not request only
input_record2 = self.new_record(schema.Struct(
('input4', schema.Scalar((np.float32, (100, ))))
)) + input_record
concat_output2 = self.model.Concat(input_record2)
self.assertEqual(is_request_only_scalar(concat_output2), False)
def testSetRequestOnly(self):
input_record = schema.Scalar(np.int64)
schema.attach_metadata_to_scalars(
input_record,
schema.Metadata(
categorical_limit=100000000,
expected_value=99,
feature_specs=schema.FeatureSpec(
feature_ids=[1, 100, 1001]
)
)
)
set_request_only(input_record)
self.assertEqual(input_record.metadata.categorical_limit, 100000000)
self.assertEqual(input_record.metadata.expected_value, 99)
self.assertEqual(
input_record.metadata.feature_specs.feature_ids,
[1, 100, 1001]
)
@given(
X=hu.arrays(dims=[5, 5]), # Shape of X is irrelevant
)
def testDropout(self, X):
input_record = self.new_record(schema.Scalar((np.float32, (1,))))
schema.FeedRecord(input_record, [X])
d_output = self.model.Dropout(input_record)
self.assertEqual(schema.Scalar((np.float32, (1,))), d_output)
self.model.output_schema = schema.Struct()
train_init_net, train_net = self.get_training_nets()
input_blob = input_record.field_blobs()[0]
output_blob = d_output.field_blobs()[0]
train_d_spec = OpSpec(
"Dropout",
[input_blob],
[output_blob, None],
{'is_test': 0, 'ratio': 0.5}
)
test_d_spec = OpSpec(
"Dropout",
[input_blob],
[output_blob, None],
{'is_test': 1, 'ratio': 0.5}
)
self.assertNetContainOps(
train_net,
[train_d_spec]
)
eval_net = self.get_eval_net()
self.assertNetContainOps(
eval_net,
[test_d_spec]
)
predict_net = self.get_predict_net()
self.assertNetContainOps(
predict_net,
[test_d_spec]
)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
schema.FeedRecord(input_record, [X])
workspace.RunNetOnce(eval_net)
schema.FeedRecord(input_record, [X])
workspace.RunNetOnce(predict_net)
@given(
num_inputs=st.integers(1, 3),
batch_size=st.integers(5, 10)
)
def testMergeIdListsLayer(self, num_inputs, batch_size):
inputs = []
for _ in range(num_inputs):
lengths = np.random.randint(5, size=batch_size).astype(np.int32)
size = lengths.sum()
values = np.random.randint(1, 10, size=size).astype(np.int64)
inputs.append(lengths)
inputs.append(values)
input_schema = schema.Tuple(
*[schema.List(
schema.Scalar(dtype=np.int64, metadata=schema.Metadata(
categorical_limit=20
))) for _ in range(num_inputs)]
)
input_record = schema.NewRecord(self.model.net, input_schema)
schema.FeedRecord(input_record, inputs)
output_schema = self.model.MergeIdLists(input_record)
assert schema.equal_schemas(
output_schema, IdList,
check_field_names=False)
@given(
batch_size=st.integers(min_value=2, max_value=10),
input_dims=st.integers(min_value=5, max_value=10),
output_dims=st.integers(min_value=5, max_value=10),
bandwidth=st.floats(min_value=0.1, max_value=5),
)
def testRandomFourierFeatures(self, batch_size, input_dims, output_dims, bandwidth):
def _rff_hypothesis_test(rff_output, X, W, b, scale):
"""
Runs hypothesis test for Semi Random Features layer.
Inputs:
rff_output -- output of net after running random fourier features layer
X -- input data
W -- weight parameter from train_init_net
b -- bias parameter from train_init_net
scale -- value by which to scale the output vector
"""
output = workspace.FetchBlob(rff_output)
output_ref = scale * np.cos(np.dot(X, np.transpose(W)) + b)
npt.assert_allclose(output, output_ref, rtol=1e-3, atol=1e-3)
X = np.random.random((batch_size, input_dims)).astype(np.float32)
scale = np.sqrt(2.0 / output_dims)
input_record = self.new_record(schema.Scalar((np.float32, (input_dims,))))
schema.FeedRecord(input_record, [X])
input_blob = input_record.field_blobs()[0]
rff_output = self.model.RandomFourierFeatures(input_record,
output_dims,
bandwidth)
self.model.output_schema = schema.Struct()
self.assertEqual(
schema.Scalar((np.float32, (output_dims, ))),
rff_output
)
train_init_net, train_net = self.get_training_nets()
# Init net assertions
init_ops_list = [
OpSpec("GaussianFill", None, None),
OpSpec("UniformFill", None, None),
]
init_ops = self._test_net(train_init_net, init_ops_list)
W = workspace.FetchBlob(self.model.layers[0].w)
b = workspace.FetchBlob(self.model.layers[0].b)
# Operation specifications
fc_spec = OpSpec("FC", [input_blob, init_ops[0].output[0],
init_ops[1].output[0]], None)
cosine_spec = OpSpec("Cos", None, None)
scale_spec = OpSpec("Scale", None, rff_output.field_blobs(),
{'scale': scale})
ops_list = [
fc_spec,
cosine_spec,
scale_spec
]
# Train net assertions
self._test_net(train_net, ops_list)
_rff_hypothesis_test(rff_output(), X, W, b, scale)
# Eval net assertions
eval_net = self.get_eval_net()
self._test_net(eval_net, ops_list)
_rff_hypothesis_test(rff_output(), X, W, b, scale)
# Predict net assertions
predict_net = self.get_predict_net()
self._test_net(predict_net, ops_list)
_rff_hypothesis_test(rff_output(), X, W, b, scale)
@given(
batch_size=st.integers(min_value=2, max_value=10),
input_dims=st.integers(min_value=5, max_value=10),
output_dims=st.integers(min_value=5, max_value=10),
s=st.integers(min_value=0, max_value=3),
scale=st.floats(min_value=0.1, max_value=5),
set_weight_as_global_constant=st.booleans()
)
def testArcCosineFeatureMap(self, batch_size, input_dims, output_dims, s, scale,
set_weight_as_global_constant):
def _arc_cosine_hypothesis_test(ac_output, X, W, b, s):
"""
Runs hypothesis test for Arc Cosine layer.
Inputs:
ac_output -- output of net after running arc cosine layer
X -- input data
W -- weight parameter from train_init_net
b -- bias parameter from train_init_net
s -- degree parameter
"""
# Get output from net
net_output = workspace.FetchBlob(ac_output)
# Computing output directly
x_rand = np.matmul(X, np.transpose(W)) + b
x_pow = np.power(x_rand, s)
if s > 0:
h_rand_features = np.piecewise(x_rand,
[x_rand <= 0, x_rand > 0],
[0, 1])
else:
h_rand_features = np.piecewise(x_rand,
[x_rand <= 0, x_rand > 0],
[0, lambda x: x / (1 + x)])
output_ref = np.multiply(x_pow, h_rand_features)
# Comparing net output and computed output
npt.assert_allclose(net_output, output_ref, rtol=1e-3, atol=1e-3)
X = np.random.normal(size=(batch_size, input_dims)).astype(np.float32)
input_record = self.new_record(schema.Scalar((np.float32, (input_dims,))))
schema.FeedRecord(input_record, [X])
input_blob = input_record.field_blobs()[0]
ac_output = self.model.ArcCosineFeatureMap(
input_record,
output_dims,
s=s,
scale=scale,
set_weight_as_global_constant=set_weight_as_global_constant
)
self.model.output_schema = schema.Struct()
self.assertEqual(
schema.Scalar((np.float32, (output_dims, ))),
ac_output
)
train_init_net, train_net = self.get_training_nets()
# Run create_init_net to initialize the global constants, and W and b
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(self.model.create_init_net(name='init_net'))
if set_weight_as_global_constant:
W = workspace.FetchBlob(
self.model.global_constants['arc_cosine_feature_map_fixed_rand_W']
)
b = workspace.FetchBlob(
self.model.global_constants['arc_cosine_feature_map_fixed_rand_b']
)
else:
W = workspace.FetchBlob(self.model.layers[0].random_w)
b = workspace.FetchBlob(self.model.layers[0].random_b)
# Operation specifications
fc_spec = OpSpec("FC", [input_blob, None, None], None)
softsign_spec = OpSpec("Softsign", None, None)
relu_spec = OpSpec("Relu", None, None)
relu_spec_output = OpSpec("Relu", None, ac_output.field_blobs())
pow_spec = OpSpec("Pow", None, None, {'exponent': float(s - 1)})
mul_spec = OpSpec("Mul", None, ac_output.field_blobs())
if s == 0:
ops_list = [
fc_spec,
softsign_spec,
relu_spec_output,
]
elif s == 1:
ops_list = [
fc_spec,
relu_spec_output,
]
else:
ops_list = [
fc_spec,
relu_spec,
pow_spec,
mul_spec,
]
# Train net assertions
self._test_net(train_net, ops_list)
_arc_cosine_hypothesis_test(ac_output(), X, W, b, s)
# Eval net assertions
eval_net = self.get_eval_net()
self._test_net(eval_net, ops_list)
_arc_cosine_hypothesis_test(ac_output(), X, W, b, s)
# Predict net assertions
predict_net = self.get_predict_net()
self._test_net(predict_net, ops_list)
_arc_cosine_hypothesis_test(ac_output(), X, W, b, s)
@given(
batch_size=st.integers(min_value=2, max_value=10),
input_dims=st.integers(min_value=5, max_value=10),
output_dims=st.integers(min_value=5, max_value=10),
s=st.integers(min_value=0, max_value=3),
scale=st.floats(min_value=0.1, max_value=5),
set_weight_as_global_constant=st.booleans(),
use_struct_input=st.booleans(),
)
def testSemiRandomFeatures(self, batch_size, input_dims, output_dims, s, scale,
set_weight_as_global_constant, use_struct_input):
def _semi_random_hypothesis_test(srf_output, X_full, X_random, rand_w,
rand_b, s):
"""
Runs hypothesis test for Semi Random Features layer.
Inputs:
srf_output -- output of net after running semi random features layer
X_full -- full input data
X_random -- random-output input data
rand_w -- random-initialized weight parameter from train_init_net
rand_b -- random-initialized bias parameter from train_init_net
s -- degree parameter
"""
# Get output from net
net_output = workspace.FetchBlob(srf_output)
# Fetch learned parameter blobs
learned_w = workspace.FetchBlob(self.model.layers[0].learned_w)
learned_b = workspace.FetchBlob(self.model.layers[0].learned_b)
# Computing output directly
x_rand = np.matmul(X_random, np.transpose(rand_w)) + rand_b
x_learn = np.matmul(X_full, np.transpose(learned_w)) + learned_b
x_pow = np.power(x_rand, s)
if s > 0:
h_rand_features = np.piecewise(x_rand,
[x_rand <= 0, x_rand > 0],
[0, 1])
else:
h_rand_features = np.piecewise(x_rand,
[x_rand <= 0, x_rand > 0],
[0, lambda x: x / (1 + x)])
output_ref = np.multiply(np.multiply(x_pow, h_rand_features), x_learn)
# Comparing net output and computed output
npt.assert_allclose(net_output, output_ref, rtol=1e-3, atol=1e-3)
X_full = np.random.normal(size=(batch_size, input_dims)).astype(np.float32)
if use_struct_input:
X_random = np.random.normal(size=(batch_size, input_dims)).\
astype(np.float32)
input_data = [X_full, X_random]
input_record = self.new_record(schema.Struct(
('full', schema.Scalar(
(np.float32, (input_dims,))
)),
('random', schema.Scalar(
(np.float32, (input_dims,))
))
))
else:
X_random = X_full
input_data = [X_full]
input_record = self.new_record(schema.Scalar(
(np.float32, (input_dims,))
))
schema.FeedRecord(input_record, input_data)
srf_output = self.model.SemiRandomFeatures(
input_record,
output_dims,
s=s,
scale_random=scale,
scale_learned=scale,
set_weight_as_global_constant=set_weight_as_global_constant
)
self.model.output_schema = schema.Struct()
self.assertEqual(
schema.Struct(
('full', schema.Scalar(
(np.float32, (output_dims,))
)),
('random', schema.Scalar(
(np.float32, (output_dims,))
))
),
srf_output
)
init_ops_list = [
OpSpec("GaussianFill", None, None),
OpSpec("UniformFill", None, None),
OpSpec("GaussianFill", None, None),
OpSpec("UniformFill", None, None),
]
train_init_net, train_net = self.get_training_nets()
# Need to run to initialize the global constants for layer
workspace.RunNetOnce(self.model.create_init_net(name='init_net'))
if set_weight_as_global_constant:
# If weight params are global constants, they won't be in train_init_net
init_ops = self._test_net(train_init_net, init_ops_list[:2])
rand_w = workspace.FetchBlob(
self.model.global_constants['semi_random_features_fixed_rand_W']
)
rand_b = workspace.FetchBlob(
self.model.global_constants['semi_random_features_fixed_rand_b']
)
# Operation specifications
fc_random_spec = OpSpec("FC", [None, None, None], None)
fc_learned_spec = OpSpec("FC", [None, init_ops[0].output[0],
init_ops[1].output[0]], None)
else:
init_ops = self._test_net(train_init_net, init_ops_list)
rand_w = workspace.FetchBlob(self.model.layers[0].random_w)
rand_b = workspace.FetchBlob(self.model.layers[0].random_b)
# Operation specifications
fc_random_spec = OpSpec("FC", [None, init_ops[0].output[0],
init_ops[1].output[0]], None)
fc_learned_spec = OpSpec("FC", [None, init_ops[2].output[0],
init_ops[3].output[0]], None)
softsign_spec = OpSpec("Softsign", None, None)
relu_spec = OpSpec("Relu", None, None)
relu_output_spec = OpSpec("Relu", None, srf_output.random.field_blobs())
pow_spec = OpSpec("Pow", None, None, {'exponent': float(s - 1)})
mul_interim_spec = OpSpec("Mul", None, srf_output.random.field_blobs())
mul_spec = OpSpec("Mul", None, srf_output.full.field_blobs())
if s == 0:
ops_list = [
fc_learned_spec,
fc_random_spec,
softsign_spec,
relu_output_spec,
mul_spec,
]
elif s == 1:
ops_list = [
fc_learned_spec,
fc_random_spec,
relu_output_spec,
mul_spec,
]
else:
ops_list = [
fc_learned_spec,
fc_random_spec,
relu_spec,
pow_spec,
mul_interim_spec,
mul_spec,
]
# Train net assertions
self._test_net(train_net, ops_list)
_semi_random_hypothesis_test(srf_output.full(), X_full, X_random,
rand_w, rand_b, s)
# Eval net assertions
eval_net = self.get_eval_net()
self._test_net(eval_net, ops_list)
_semi_random_hypothesis_test(srf_output.full(), X_full, X_random,
rand_w, rand_b, s)
# Predict net assertions
predict_net = self.get_predict_net()
self._test_net(predict_net, ops_list)
_semi_random_hypothesis_test(srf_output.full(), X_full, X_random,
rand_w, rand_b, s)
def testConv(self):
batch_size = 50
H = 1
W = 10
C = 50
output_dims = 32
kernel_h = 1
kernel_w = 3
stride_h = 1
stride_w = 1
pad_t = 0
pad_b = 0
pad_r = None
pad_l = None
input_record = self.new_record(schema.Scalar((np.float32, (H, W, C))))
X = np.random.random((batch_size, H, W, C)).astype(np.float32)
schema.FeedRecord(input_record, [X])
conv = self.model.Conv(
input_record,
output_dims,
kernel_h=kernel_h,
kernel_w=kernel_w,
stride_h=stride_h,
stride_w=stride_w,
pad_t=pad_t,
pad_b=pad_b,
pad_r=pad_r,
pad_l=pad_l,
order='NHWC'
)
self.assertEqual(
schema.Scalar((np.float32, (output_dims,))),
conv
)
self.run_train_net_forward_only()
output_record = schema.FetchRecord(conv)
# check the number of output channels is the same as input in this example
assert output_record.field_types()[0].shape == (H, W, output_dims)
assert output_record().shape == (batch_size, H, W, output_dims)
train_init_net, train_net = self.get_training_nets()
# Init net assertions
init_ops = self.assertNetContainOps(
train_init_net,
[
OpSpec("XavierFill", None, None),
OpSpec("ConstantFill", None, None),
]
)
conv_spec = OpSpec(
"Conv",
[
input_record.field_blobs()[0],
init_ops[0].output[0],
init_ops[1].output[0],
],
conv.field_blobs()
)
# Train net assertions
self.assertNetContainOps(train_net, [conv_spec])
# Predict net assertions
predict_net = self.get_predict_net()
self.assertNetContainOps(predict_net, [conv_spec])
# Eval net assertions
eval_net = self.get_eval_net()
self.assertNetContainOps(eval_net, [conv_spec])
@given(
num=st.integers(min_value=10, max_value=100),
feed_weight=st.booleans(),
**hu.gcs
)
def testAdaptiveWeight(self, num, feed_weight, gc, dc):
input_record = self.new_record(schema.RawTuple(num))
data = np.random.random(num)
schema.FeedRecord(
input_record,
[np.array(x).astype(np.float32) for x in data]
)
weights = np.random.random(num) if feed_weight else None
result = self.model.AdaptiveWeight(input_record, weights=weights)
train_init_net, train_net = self.get_training_nets(True)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
result = workspace.FetchBlob(result())
if not feed_weight:
weights = 1. / num
expected = np.sum(weights * data + np.log(1. / 2. / weights))
npt.assert_allclose(expected, result, atol=1e-4, rtol=1e-4)
@given(num=st.integers(min_value=10, max_value=100), **hu.gcs)
def testConstantWeight(self, num, gc, dc):
input_record = self.new_record(schema.RawTuple(num))
data = np.random.random(num)
schema.FeedRecord(
input_record, [np.array(x).astype(np.float32) for x in data]
)
weights = np.random.random(num)
result = self.model.ConstantWeight(input_record, weights=weights)
train_init_net, train_net = self.get_training_nets(True)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
result = workspace.FetchBlob(result())
expected = np.sum(weights * data)
npt.assert_allclose(expected, result, atol=1e-4, rtol=1e-4)
@given(**hu.gcs)
def testHomotopyWeight(self, gc, dc):
input_record = self.new_record(schema.RawTuple(2))
data = np.random.random(2)
schema.FeedRecord(
input_record, [np.array(x).astype(np.float32) for x in data]
)
# ensure: quad_life > 2 * half_life
half_life = int(np.random.random() * 1e2 + 1)
quad_life = int(np.random.random() * 1e3 + 2 * half_life + 1)
result = self.model.HomotopyWeight(
input_record,
min_weight=0.,
max_weight=1.,
half_life=half_life,
quad_life=quad_life,
)
train_init_net, train_net = self.get_training_nets(True)
workspace.RunNetOnce(train_init_net)
workspace.CreateNet(train_net)
workspace.RunNet(train_net.Name(), num_iter=half_life)
half_life_result = workspace.FetchBlob(result())
workspace.RunNet(train_net.Name(), num_iter=quad_life - half_life)
quad_life_result = workspace.FetchBlob(result())
expected_half_life_result = 0.5 * data[0] + 0.5 * data[1]
expected_quad_life_result = 0.25 * data[0] + 0.75 * data[1]
npt.assert_allclose(
expected_half_life_result, half_life_result, atol=1e-2, rtol=1e-2
)
npt.assert_allclose(
expected_quad_life_result, quad_life_result, atol=1e-2, rtol=1e-2
)
def _testLabelSmooth(self, categories, binary_prob_label, bsz):
label = self.new_record(schema.Scalar((np.float32, (1, ))))
label_np = np.random.randint(categories, size=bsz).astype(np.float32)
schema.FeedRecord(label, [label_np])
smooth_matrix_shape = (
2 if binary_prob_label else (categories, categories)
)
smooth_matrix = np.random.random(smooth_matrix_shape)
smoothed_label = self.model.LabelSmooth(label, smooth_matrix)
train_init_net, train_net = self.get_training_nets(True)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
smoothed_label_np = workspace.FetchBlob(smoothed_label())
if binary_prob_label:
expected = np.array(
[
smooth_matrix[0] if x == 0.0 else smooth_matrix[1]
for x in label_np
]
)
else:
expected = np.array([smooth_matrix[int(x)] for x in label_np])
npt.assert_allclose(expected, smoothed_label_np, atol=1e-4, rtol=1e-4)
@given(
categories=st.integers(min_value=2, max_value=10),
bsz=st.integers(min_value=10, max_value=100),
**hu.gcs
)
def testLabelSmoothForCategoricalLabel(self, categories, bsz, gc, dc):
self._testLabelSmooth(categories, False, bsz)
@given(
bsz=st.integers(min_value=10, max_value=100),
**hu.gcs
)
def testLabelSmoothForBinaryProbLabel(self, bsz, gc, dc):
self._testLabelSmooth(2, True, bsz)
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import string
import argparse
import numpy as np
from caffe2.python.model_helper import ModelHelper
from caffe2.python.predictor import mobile_exporter
from caffe2.python import core, workspace, brew, utils
def parse_kwarg(kwarg_str):
key, value = map(string.strip, kwarg_str.split("=", 1))
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
pass
return key, value
def main(args):
# User defined keyword arguments
kwargs = {"order": "NCHW"}
kwargs.update(dict(args.kwargs))
model = ModelHelper(name=args.benchmark_name)
op_type = args.operator # assumes a brew type op name
input_name = args.input_name
output_name = args.output_name
iters = int(args.iters)
for i in range(iters):
input_blob_name = input_name + (str(i) if i > 0 and args.chain else '')
output_blob_name = output_name + str(i + 1)
add_op = getattr(brew, op_type)
add_op(model, input_blob_name, output_blob_name, **kwargs)
if args.chain:
input_name, output_name = output_name, input_name
workspace.RunNetOnce(model.param_init_net)
extra_init_net_ops = []
def make_blob_on_context(blob_name, blob_data, context):
if context.upper() != "CPU":
blob_name_modified = "{}_CPU".format(blob_name)
else: # CPU case is simple
blob_name_modified = blob_name
fill_op = core.CreateOperator(
"GivenTensorFill", [], [blob_name_modified],
arg=[
utils.MakeArgument("shape", blob_data.shape),
utils.MakeArgument("values", blob_data)
]
)
extra_init_net_ops.append(fill_op)
# We need to create CPU blobs and add some copy operations in
# the init_net
if context.upper() == "OPENGL":
copy_op = core.CreateOperator("CopyToOpenGL", [blob_name_modified],
[blob_name])
extra_init_net_ops.append(copy_op)
for unparsed_blob in args.blob:
name, unparsed_dims = unparsed_blob.split('=')
dims = [int(d) for d in unparsed_dims.split(',')]
np_input = np.random.rand(*dims).astype(np.float32)
make_blob_on_context(name, np_input, args.context)
init_net, predict_net = mobile_exporter.Export(
workspace, model.net, model.params
)
init_net.op.extend(extra_init_net_ops)
# Handle manual rewrite
if args.context.upper() == "OPENGL":
old_ops = [op for op in predict_net.op]
del predict_net.op[:]
for op in old_ops:
op.type = 'OpenGL{}'.format(op.type)
predict_net.op.extend(old_ops)
if args.debug:
print("init_net:")
for op in init_net.op:
print(" ", op.type, op.input, "-->", op.output)
print("predict_net:")
for op in predict_net.op:
print(" ", op.type, op.input, "-->", op.output)
with open(args.predict_net, 'wb') as f:
f.write(predict_net.SerializeToString())
with open(args.init_net, 'wb') as f:
f.write(init_net.SerializeToString())
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Utilitity to generate Caffe2 benchmark models.")
parser.add_argument("operator", help="Caffe2 operator to benchmark.")
parser.add_argument("-b", "--blob",
help="Instantiate a blob --blob name=dim1,dim2,dim3",
action='append')
parser.add_argument("--context", help="Context to run on.", default="CPU")
parser.add_argument("--kwargs", help="kwargs to pass to operator.",
nargs="*", type=parse_kwarg, default=[])
parser.add_argument("--init_net", help="Output initialization net.",
default="init_net.pb")
parser.add_argument("--predict_net", help="Output prediction net.",
default="predict_net.pb")
parser.add_argument("--benchmark_name",
help="Name of the benchmark network",
default="benchmark")
parser.add_argument("--input_name", help="Name of the input blob.",
default="data")
parser.add_argument("--output_name", help="Name of the output blob.",
default="output")
parser.add_argument("--iters",
help="Number of iterations to run the operator.",
default="1")
parser.add_argument("-d", "--debug", help="Print debug information.",
action='store_true')
parser.add_argument("-c", "--chain",
help="Chain ops together (create data dependencies)",
action='store_true')
args = parser.parse_args()
main(args)
|
# TODO(jiayq): as more and more tests are moving to hypothesis test, we
# can gradually remove this test script. DO NOT ADD MORE TESTS TO THIS
# FILE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import (
brew,
core,
device_checker,
gradient_checker,
model_helper,
test_util,
workspace,
)
from caffe2.python.gradient_checker import NetGradientChecker
from caffe2.python.net_builder import ops, NetBuilder
from caffe2.proto import caffe2_pb2
import unittest
if workspace.has_gpu_support and workspace.NumCudaDevices() > 0:
gpu_device_option = caffe2_pb2.DeviceOption()
gpu_device_option.device_type = caffe2_pb2.CUDA
cpu_device_option = caffe2_pb2.DeviceOption()
gpu_device_checker = device_checker.DeviceChecker(
0.01, [gpu_device_option]
)
device_checker = device_checker.DeviceChecker(
0.01, [gpu_device_option, cpu_device_option]
)
gpu_gradient_checkers = [
gradient_checker.GradientChecker(
0.005, 0.05, gpu_device_option, "gpu_checker_ws"
),
]
gradient_checkers = [
gradient_checker.GradientChecker(
0.005, 0.05, gpu_device_option, "gpu_checker_ws"
),
gradient_checker.GradientChecker(
0.01, 0.05, cpu_device_option, "cpu_checker_ws"
),
]
else:
cpu_device_option = caffe2_pb2.DeviceOption()
gpu_device_option = None
gpu_device_checker = device_checker.DeviceChecker(
0.01, []
)
device_checker = device_checker.DeviceChecker(0.01, [cpu_device_option])
gradient_checkers = [
gradient_checker.GradientChecker(
0.01, 0.05, cpu_device_option, "cpu_checker_ws"
)
]
gpu_gradient_checkers = []
class TestLRN(test_util.TestCase):
def setUp(self):
self.test_configs = [(6, 10), (3, 13), ]
def testLRN(self):
for input_size, depth in self.test_configs:
op = core.CreateOperator("LRN",
["X"],
["Y", "Y_scale"],
size=11,
alpha=0.001,
beta=0.5,
bias=2.0,
order="NHWC"
)
X = np.random.rand(2, input_size, input_size,
depth).astype(np.float32)
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestFlatten(test_util.TestCase):
def testFlatten(self):
op = core.CreateOperator("Flatten", ["X"], ["Y"])
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestConcat(test_util.TestCase):
def setUp(self):
self.test_configs = [
# input_size, depth1, depth2, depth3, depth4
(3, 2, 3, 4, 5),
(4, 5, 4, 3, 2),
]
def testConcatNHWC(self):
for input_size, d1, d2, d3, d4 in self.test_configs:
op = core.CreateOperator("Concat",
["X1", "X2", "X3", "X4"],
["Y", "Y_dims"],
order="NHWC"
)
Xs = [
np.random.rand(2, input_size, input_size,
d1).astype(np.float32),
np.random.rand(2, input_size, input_size,
d2).astype(np.float32),
np.random.rand(2, input_size, input_size,
d3).astype(np.float32),
np.random.rand(2, input_size, input_size, d4).astype(np.float32)
]
for i in range(4):
res = device_checker.CheckSimple(op, Xs, [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, Xs, i,
[0])
self.assertTrue(res)
def testConcatNCHW(self):
for input_size, d1, d2, d3, d4 in self.test_configs:
op = core.CreateOperator("Concat",
["X1", "X2", "X3", "X4"],
["Y", "Y_dims"],
order="NCHW"
)
Xs = [
np.random.rand(2, d1, input_size,
input_size).astype(np.float32),
np.random.rand(2, d2, input_size,
input_size).astype(np.float32),
np.random.rand(2, d3, input_size,
input_size).astype(np.float32),
np.random.rand(2, d4, input_size, input_size).astype(np.float32)
]
for i in range(4):
res = device_checker.CheckSimple(op, Xs, [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, Xs, i,
[0])
self.assertTrue(res)
class TestRelu(test_util.TestCase):
def setUp(self):
self.test_configs = [
# input size
# (0, 1),
(1, 1),
(2, 1),
(1, 3, 3, 1),
(2, 3, 3, 1),
(1, 5, 5, 3),
(2, 5, 5, 3),
]
def testRelu(self):
for input_size in self.test_configs:
op = core.CreateOperator("Relu", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32)
# go away from the origin point to avoid kink problems
X += 0.01 * np.sign(X)
X[X == 0] = 0.01
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestTanh(test_util.TestCase):
def setUp(self):
self.test_configs = [
# (0, 1),
(1, 1),
(2, 1),
(1, 2, 3, 4),
]
def testTanh(self):
for input_size in self.test_configs:
op = core.CreateOperator("Tanh", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32) - 0.5
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestAbs(test_util.TestCase):
def setUp(self):
self.test_configs = [
(1, 1),
(2, 3),
(2, 3, 4),
(2, 3, 4, 5),
]
def testAbs(self):
for input_size in self.test_configs:
op = core.CreateOperator("Abs", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32)
# go away from the origin point to avoid kink problems
X += 0.01 * np.sign(X)
X[X == 0] = 0.01
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestExp(test_util.TestCase):
def setUp(self):
self.test_configs = [
# (0, 1),
(1, 1),
(2, 1),
(1, 2, 3, 4),
]
def testExp(self):
for input_size in self.test_configs:
op = core.CreateOperator("Exp", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32) - 0.5
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestCos(test_util.TestCase):
def setUp(self):
self.test_configs = [
(1, 1),
(2, 3),
(2, 3, 4),
(2, 3, 4, 5),
]
def testCos(self):
for input_size in self.test_configs:
op = core.CreateOperator("Cos", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32) - 0.5
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestSin(test_util.TestCase):
def setUp(self):
self.test_configs = [
(1, 1),
(2, 3),
(2, 3, 4),
(2, 3, 4, 5),
]
def testSin(self):
for input_size in self.test_configs:
op = core.CreateOperator("Sin", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32) - 0.5
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestSigmoid(test_util.TestCase):
def setUp(self):
self.test_configs = [
# (0, 1),
(1, 1),
(2, 1),
(1, 2, 3, 4),
]
def testSigmoid(self):
for input_size in self.test_configs:
op = core.CreateOperator("Sigmoid", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32) - 0.5
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestSum(test_util.TestCase):
def setUp(self):
self.test_configs = [
# ((0, 1), False),
((1, 2, 3, 4), True),
((1, 2, 3, 4), False)]
def testSum(self):
for (input_size, in_place) in self.test_configs:
op = core.CreateOperator("Sum", ["X1", "X2"],
["Y" if not in_place else "X1"])
X1 = np.random.rand(*input_size).astype(np.float32) - 0.5
X2 = np.random.rand(*input_size).astype(np.float32) - 0.5
res = device_checker.CheckSimple(op, [X1, X2], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(
op, [X1, X2], 0, [0])
self.assertTrue(res)
class TestMakeTwoClass(test_util.TestCase):
def setUp(self):
self.test_configs = [
# input size
# (0, 1),
(1,),
(7,),
(1, 3),
(2, 5),
]
def testMakeTwoClass(self):
for input_size in self.test_configs:
op = core.CreateOperator("MakeTwoClass", ["X"], ["Y"])
X = np.random.rand(*input_size).astype(np.float32)
# step a little to avoid gradient problems
X[X < 0.01] += 0.01
X[X > 0.99] -= 0.01
res = device_checker.CheckSimple(op, [X], [0])
self.assertTrue(res)
for checker in gradient_checkers:
res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0])
self.assertTrue(res)
class TestNetGradientChecker(test_util.TestCase):
def test_net_gradient_checker(self):
model = model_helper.ModelHelper(name="test")
const = model.net.AddExternalInputs("const1", "const2")
fc = brew.fc(model, dim_in=3, dim_out=4, blob_in="X", blob_out="Y", axis=0)
dist = [model.net.SquaredL2Distance([fc, c]) for c in const]
losses = [model.net.AveragedLoss(d) for d in dist] # using two losses here
workspace.RunNetOnce(model.param_init_net)
NetGradientChecker.Check(
model.net,
outputs_with_grad=losses,
input_values={"X": np.array([1, 2, 3], dtype="float32"),
const[0]: np.array([1, 1, 1, 1], dtype="float32"),
const[1]: np.array([2, 2, 2, 2], dtype="float32")},
input_to_check="X",
)
def test_net_comparison(self):
# (a + b) * (c + d) == a * c + a * d + b * c + b * d
net1 = core.Net("net1")
a, b, c, d = net1.AddExternalInputs("a", "b", "c", "d")
a_b = net1.Sum([a, b], "a+b")
c_d = net1.Sum([c, d], "c+d")
x = net1.Mul([a_b, c_d], "x")
net2 = core.Net("net2")
ac = net2.Mul([a, c], "ac")
ad = net2.Mul([a, d], "ad")
bc = net2.Mul([b, c], "bc")
bd = net2.Mul([b, d], "bd")
y = net2.Sum([ac, ad, bc, bd], "y")
input_values = {blob: np.array([i], dtype=np.float32)
for i, blob in enumerate([a, b, c, d])}
NetGradientChecker.CompareNets(
[net1, net2], [[x], [y]], [0],
inputs_with_grads=[a, b, c, d],
input_values=input_values,
)
class TestIf(test_util.TestCase):
def testIf(self):
W_a_values = [2.0, 1.5]
B_a_values = [0.5]
W_b_values = [7.0, 3.5]
B_b_values = [1.5]
with NetBuilder(_use_control_ops=True) as init_nb:
W_a = ops.UniformFill([], "W_a", shape=[1, 2], min=-1., max=1.)
B_a = ops.ConstantFill([], "B_a", shape=[1], value=0.0)
W_b = ops.UniformFill([], "W_b", shape=[1, 2], min=-1., max=1.)
B_b = ops.ConstantFill([], "B_b", shape=[1], value=0.0)
W_gt_a = ops.GivenTensorFill(
[], "W_gt_a", shape=[1, 2], values=W_a_values)
B_gt_a = ops.GivenTensorFill([], "B_gt_a", shape=[1], values=B_a_values)
W_gt_b = ops.GivenTensorFill(
[], "W_gt_b", shape=[1, 2], values=W_b_values)
B_gt_b = ops.GivenTensorFill([], "B_gt_b", shape=[1], values=B_b_values)
params = [W_gt_a, B_gt_a, W_a, B_a, W_gt_b, B_gt_b, W_b, B_b]
with NetBuilder(_use_control_ops=True, initial_scope=params) as train_nb:
Y_pred = ops.ConstantFill([], "Y_pred", shape=[1], value=0.0)
Y_noise = ops.ConstantFill([], "Y_noise", shape=[1], value=0.0)
switch = ops.UniformFill(
[], "switch", shape=[1], min=-1., max=1., run_once=0)
zero = ops.ConstantFill([], "zero", shape=[1], value=0.0)
X = ops.GaussianFill(
[], "X", shape=[4096, 2], mean=0.0, std=1.0, run_once=0)
noise = ops.GaussianFill(
[], "noise", shape=[4096, 1], mean=0.0, std=1.0, run_once=0)
with ops.IfNet(ops.LT([switch, zero])):
Y_gt = ops.FC([X, W_gt_a, B_gt_a], "Y_gt")
ops.Add([Y_gt, noise], Y_noise)
ops.FC([X, W_a, B_a], Y_pred)
with ops.Else():
Y_gt = ops.FC([X, W_gt_b, B_gt_b], "Y_gt")
ops.Add([Y_gt, noise], Y_noise)
ops.FC([X, W_b, B_b], Y_pred)
dist = ops.SquaredL2Distance([Y_noise, Y_pred], "dist")
loss = dist.AveragedLoss([], ["loss"])
assert len(init_nb.get()) == 1, "Expected a single init net produced"
assert len(train_nb.get()) == 1, "Expected a single train net produced"
train_net = train_nb.get()[0]
gradient_map = train_net.AddGradientOperators([loss])
init_net = init_nb.get()[0]
ITER = init_net.ConstantFill(
[], "ITER", shape=[1], value=0, dtype=core.DataType.INT32)
train_net.Iter(ITER, ITER)
LR = train_net.LearningRate(ITER, "LR", base_lr=-0.1,
policy="step", stepsize=20, gamma=0.9)
ONE = init_net.ConstantFill([], "ONE", shape=[1], value=1.)
train_net.WeightedSum([W_a, ONE, gradient_map[W_a], LR], W_a)
train_net.WeightedSum([B_a, ONE, gradient_map[B_a], LR], B_a)
train_net.WeightedSum([W_b, ONE, gradient_map[W_b], LR], W_b)
train_net.WeightedSum([B_b, ONE, gradient_map[B_b], LR], B_b)
workspace.RunNetOnce(init_net)
workspace.CreateNet(train_net)
# print("Before training, W_a is: {}".format(workspace.FetchBlob("W_a")))
# print("Before training, B_a is: {}".format(workspace.FetchBlob("B_a")))
# print("Before training, W_b is: {}".format(workspace.FetchBlob("W_b")))
# print("Before training, B_b is: {}".format(workspace.FetchBlob("B_b")))
for _epoch in range(1000):
workspace.RunNet(train_net.Proto().name)
# print("After training, W_a is: {}".format(workspace.FetchBlob("W_a")))
# print("After training, B_a is: {}".format(workspace.FetchBlob("B_a")))
# print("After training, W_b is: {}".format(workspace.FetchBlob("W_b")))
# print("After training, B_b is: {}".format(workspace.FetchBlob("B_b")))
# print("Ground truth W_a is: {}".format(workspace.FetchBlob("W_gt_a")))
# print("Ground truth B_a is: {}".format(workspace.FetchBlob("B_gt_a")))
# print("Ground truth W_b is: {}".format(workspace.FetchBlob("W_gt_b")))
# print("Ground truth B_b is: {}".format(workspace.FetchBlob("B_gt_b")))
values_map = {
"W_a": W_a_values,
"B_a": B_a_values,
"W_b": W_b_values,
"B_b": B_b_values,
}
train_eps = 0.01
for blob_name, values in values_map.items():
trained_values = workspace.FetchBlob(blob_name)
if trained_values.ndim == 2:
self.assertEqual(trained_values.shape[0], 1)
trained_values = trained_values[0][:]
else:
self.assertEqual(trained_values.ndim, 1)
self.assertEqual(trained_values.size, len(values))
for idx in range(len(trained_values)):
self.assertTrue(abs(trained_values[idx] - values[idx]) < train_eps)
class TestWhile(test_util.TestCase):
def testWhile(self):
with NetBuilder(_use_control_ops=True) as nb:
ops.Copy(ops.Const(0), "i")
ops.Copy(ops.Const(1), "one")
ops.Copy(ops.Const(2), "two")
ops.Copy(ops.Const(2.0), "x")
ops.Copy(ops.Const(3.0), "y")
ops.Copy(ops.Const(2.0), "z")
# raises x to the power of 4 and y to the power of 2
# and z to the power of 3
with ops.WhileNet():
with ops.Condition():
ops.Add(["i", "one"], "i")
ops.LE(["i", "two"])
ops.Pow("x", "x", exponent=2.0)
with ops.IfNet(ops.LT(["i", "two"])):
ops.Pow("y", "y", exponent=2.0)
with ops.Else():
ops.Pow("z", "z", exponent=3.0)
ops.Add(["x", "y"], "x_plus_y")
ops.Add(["x_plus_y", "z"], "s")
assert len(nb.get()) == 1, "Expected a single net produced"
net = nb.get()[0]
net.AddGradientOperators(["s"])
workspace.RunNetOnce(net)
# (x^4)' = 4x^3
self.assertAlmostEqual(workspace.FetchBlob("x_grad"), 32)
self.assertAlmostEqual(workspace.FetchBlob("x"), 16)
# (y^2)' = 2y
self.assertAlmostEqual(workspace.FetchBlob("y_grad"), 6)
self.assertAlmostEqual(workspace.FetchBlob("y"), 9)
# (z^3)' = 3z^2
self.assertAlmostEqual(workspace.FetchBlob("z_grad"), 12)
self.assertAlmostEqual(workspace.FetchBlob("z"), 8)
if __name__ == '__main__':
workspace.GlobalInit(["python"])
unittest.main()
|
## @package attention
# Module caffe2.python.attention
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import brew
class AttentionType:
Regular, Recurrent, Dot, SoftCoverage = tuple(range(4))
def s(scope, name):
# We have to manually scope due to our internal/external blob
# relationships.
return "{}/{}".format(str(scope), str(name))
# c_i = \sum_j w_{ij}\textbf{s}_j
def _calc_weighted_context(
model,
encoder_outputs_transposed,
encoder_output_dim,
attention_weights_3d,
scope,
):
# [batch_size, encoder_output_dim, 1]
attention_weighted_encoder_context = brew.batch_mat_mul(
model,
[encoder_outputs_transposed, attention_weights_3d],
s(scope, 'attention_weighted_encoder_context'),
)
# [batch_size, encoder_output_dim]
attention_weighted_encoder_context, _ = model.net.Reshape(
attention_weighted_encoder_context,
[
attention_weighted_encoder_context,
s(scope, 'attention_weighted_encoder_context_old_shape'),
],
shape=[1, -1, encoder_output_dim],
)
return attention_weighted_encoder_context
# Calculate a softmax over the passed in attention energy logits
def _calc_attention_weights(
model,
attention_logits_transposed,
scope,
encoder_lengths=None,
):
if encoder_lengths is not None:
attention_logits_transposed = model.net.SequenceMask(
[attention_logits_transposed, encoder_lengths],
['masked_attention_logits'],
mode='sequence',
)
# [batch_size, encoder_length, 1]
attention_weights_3d = brew.softmax(
model,
attention_logits_transposed,
s(scope, 'attention_weights_3d'),
engine='CUDNN',
axis=1,
)
return attention_weights_3d
# e_{ij} = \textbf{v}^T tanh \alpha(\textbf{h}_{i-1}, \textbf{s}_j)
def _calc_attention_logits_from_sum_match(
model,
decoder_hidden_encoder_outputs_sum,
encoder_output_dim,
scope,
):
# [encoder_length, batch_size, encoder_output_dim]
decoder_hidden_encoder_outputs_sum = model.net.Tanh(
decoder_hidden_encoder_outputs_sum,
decoder_hidden_encoder_outputs_sum,
)
# [encoder_length, batch_size, 1]
attention_logits = brew.fc(
model,
decoder_hidden_encoder_outputs_sum,
s(scope, 'attention_logits'),
dim_in=encoder_output_dim,
dim_out=1,
axis=2,
freeze_bias=True,
)
# [batch_size, encoder_length, 1]
attention_logits_transposed = brew.transpose(
model,
attention_logits,
s(scope, 'attention_logits_transposed'),
axes=[1, 0, 2],
)
return attention_logits_transposed
# \textbf{W}^\alpha used in the context of \alpha_{sum}(a,b)
def _apply_fc_weight_for_sum_match(
model,
input,
dim_in,
dim_out,
scope,
name,
):
output = brew.fc(
model,
input,
s(scope, name),
dim_in=dim_in,
dim_out=dim_out,
axis=2,
)
output = model.net.Squeeze(
output,
output,
dims=[0],
)
return output
# Implement RecAtt due to section 4.1 in http://arxiv.org/abs/1601.03317
def apply_recurrent_attention(
model,
encoder_output_dim,
encoder_outputs_transposed,
weighted_encoder_outputs,
decoder_hidden_state_t,
decoder_hidden_state_dim,
attention_weighted_encoder_context_t_prev,
scope,
encoder_lengths=None,
):
weighted_prev_attention_context = _apply_fc_weight_for_sum_match(
model=model,
input=attention_weighted_encoder_context_t_prev,
dim_in=encoder_output_dim,
dim_out=encoder_output_dim,
scope=scope,
name='weighted_prev_attention_context',
)
weighted_decoder_hidden_state = _apply_fc_weight_for_sum_match(
model=model,
input=decoder_hidden_state_t,
dim_in=decoder_hidden_state_dim,
dim_out=encoder_output_dim,
scope=scope,
name='weighted_decoder_hidden_state',
)
# [1, batch_size, encoder_output_dim]
decoder_hidden_encoder_outputs_sum_tmp = model.net.Add(
[
weighted_prev_attention_context,
weighted_decoder_hidden_state,
],
s(scope, 'decoder_hidden_encoder_outputs_sum_tmp'),
)
# [encoder_length, batch_size, encoder_output_dim]
decoder_hidden_encoder_outputs_sum = model.net.Add(
[
weighted_encoder_outputs,
decoder_hidden_encoder_outputs_sum_tmp,
],
s(scope, 'decoder_hidden_encoder_outputs_sum'),
broadcast=1,
)
attention_logits_transposed = _calc_attention_logits_from_sum_match(
model=model,
decoder_hidden_encoder_outputs_sum=decoder_hidden_encoder_outputs_sum,
encoder_output_dim=encoder_output_dim,
scope=scope,
)
# [batch_size, encoder_length, 1]
attention_weights_3d = _calc_attention_weights(
model=model,
attention_logits_transposed=attention_logits_transposed,
scope=scope,
encoder_lengths=encoder_lengths,
)
# [batch_size, encoder_output_dim, 1]
attention_weighted_encoder_context = _calc_weighted_context(
model=model,
encoder_outputs_transposed=encoder_outputs_transposed,
encoder_output_dim=encoder_output_dim,
attention_weights_3d=attention_weights_3d,
scope=scope,
)
return attention_weighted_encoder_context, attention_weights_3d, [
decoder_hidden_encoder_outputs_sum,
]
def apply_regular_attention(
model,
encoder_output_dim,
encoder_outputs_transposed,
weighted_encoder_outputs,
decoder_hidden_state_t,
decoder_hidden_state_dim,
scope,
encoder_lengths=None,
):
weighted_decoder_hidden_state = _apply_fc_weight_for_sum_match(
model=model,
input=decoder_hidden_state_t,
dim_in=decoder_hidden_state_dim,
dim_out=encoder_output_dim,
scope=scope,
name='weighted_decoder_hidden_state',
)
# [encoder_length, batch_size, encoder_output_dim]
decoder_hidden_encoder_outputs_sum = model.net.Add(
[weighted_encoder_outputs, weighted_decoder_hidden_state],
s(scope, 'decoder_hidden_encoder_outputs_sum'),
broadcast=1,
use_grad_hack=1,
)
attention_logits_transposed = _calc_attention_logits_from_sum_match(
model=model,
decoder_hidden_encoder_outputs_sum=decoder_hidden_encoder_outputs_sum,
encoder_output_dim=encoder_output_dim,
scope=scope,
)
# [batch_size, encoder_length, 1]
attention_weights_3d = _calc_attention_weights(
model=model,
attention_logits_transposed=attention_logits_transposed,
scope=scope,
encoder_lengths=encoder_lengths,
)
# [batch_size, encoder_output_dim, 1]
attention_weighted_encoder_context = _calc_weighted_context(
model=model,
encoder_outputs_transposed=encoder_outputs_transposed,
encoder_output_dim=encoder_output_dim,
attention_weights_3d=attention_weights_3d,
scope=scope,
)
return attention_weighted_encoder_context, attention_weights_3d, [
decoder_hidden_encoder_outputs_sum,
]
def apply_dot_attention(
model,
encoder_output_dim,
# [batch_size, encoder_output_dim, encoder_length]
encoder_outputs_transposed,
# [1, batch_size, decoder_state_dim]
decoder_hidden_state_t,
decoder_hidden_state_dim,
scope,
encoder_lengths=None,
):
if decoder_hidden_state_dim != encoder_output_dim:
weighted_decoder_hidden_state = brew.fc(
model,
decoder_hidden_state_t,
s(scope, 'weighted_decoder_hidden_state'),
dim_in=decoder_hidden_state_dim,
dim_out=encoder_output_dim,
axis=2,
)
else:
weighted_decoder_hidden_state = decoder_hidden_state_t
# [batch_size, decoder_state_dim]
squeezed_weighted_decoder_hidden_state = model.net.Squeeze(
weighted_decoder_hidden_state,
s(scope, 'squeezed_weighted_decoder_hidden_state'),
dims=[0],
)
# [batch_size, decoder_state_dim, 1]
expanddims_squeezed_weighted_decoder_hidden_state = model.net.ExpandDims(
squeezed_weighted_decoder_hidden_state,
squeezed_weighted_decoder_hidden_state,
dims=[2],
)
# [batch_size, encoder_output_dim, 1]
attention_logits_transposed = model.net.BatchMatMul(
[
encoder_outputs_transposed,
expanddims_squeezed_weighted_decoder_hidden_state,
],
s(scope, 'attention_logits'),
trans_a=1,
)
# [batch_size, encoder_length, 1]
attention_weights_3d = _calc_attention_weights(
model=model,
attention_logits_transposed=attention_logits_transposed,
scope=scope,
encoder_lengths=encoder_lengths,
)
# [batch_size, encoder_output_dim, 1]
attention_weighted_encoder_context = _calc_weighted_context(
model=model,
encoder_outputs_transposed=encoder_outputs_transposed,
encoder_output_dim=encoder_output_dim,
attention_weights_3d=attention_weights_3d,
scope=scope,
)
return attention_weighted_encoder_context, attention_weights_3d, []
def apply_soft_coverage_attention(
model,
encoder_output_dim,
encoder_outputs_transposed,
weighted_encoder_outputs,
decoder_hidden_state_t,
decoder_hidden_state_dim,
scope,
encoder_lengths,
coverage_t_prev,
coverage_weights,
):
weighted_decoder_hidden_state = _apply_fc_weight_for_sum_match(
model=model,
input=decoder_hidden_state_t,
dim_in=decoder_hidden_state_dim,
dim_out=encoder_output_dim,
scope=scope,
name='weighted_decoder_hidden_state',
)
# [encoder_length, batch_size, encoder_output_dim]
decoder_hidden_encoder_outputs_sum = model.net.Add(
[weighted_encoder_outputs, weighted_decoder_hidden_state],
s(scope, 'decoder_hidden_encoder_outputs_sum'),
broadcast=1,
)
# [batch_size, encoder_length]
coverage_t_prev_2d = model.net.Squeeze(
coverage_t_prev,
s(scope, 'coverage_t_prev_2d'),
dims=[0],
)
# [encoder_length, batch_size]
coverage_t_prev_transposed = brew.transpose(
model,
coverage_t_prev_2d,
s(scope, 'coverage_t_prev_transposed'),
)
# [encoder_length, batch_size, encoder_output_dim]
scaled_coverage_weights = model.net.Mul(
[coverage_weights, coverage_t_prev_transposed],
s(scope, 'scaled_coverage_weights'),
broadcast=1,
axis=0,
)
# [encoder_length, batch_size, encoder_output_dim]
decoder_hidden_encoder_outputs_sum = model.net.Add(
[decoder_hidden_encoder_outputs_sum, scaled_coverage_weights],
decoder_hidden_encoder_outputs_sum,
)
# [batch_size, encoder_length, 1]
attention_logits_transposed = _calc_attention_logits_from_sum_match(
model=model,
decoder_hidden_encoder_outputs_sum=decoder_hidden_encoder_outputs_sum,
encoder_output_dim=encoder_output_dim,
scope=scope,
)
# [batch_size, encoder_length, 1]
attention_weights_3d = _calc_attention_weights(
model=model,
attention_logits_transposed=attention_logits_transposed,
scope=scope,
encoder_lengths=encoder_lengths,
)
# [batch_size, encoder_output_dim, 1]
attention_weighted_encoder_context = _calc_weighted_context(
model=model,
encoder_outputs_transposed=encoder_outputs_transposed,
encoder_output_dim=encoder_output_dim,
attention_weights_3d=attention_weights_3d,
scope=scope,
)
# [batch_size, encoder_length]
attention_weights_2d = model.net.Squeeze(
attention_weights_3d,
s(scope, 'attention_weights_2d'),
dims=[2],
)
coverage_t = model.net.Add(
[coverage_t_prev, attention_weights_2d],
s(scope, 'coverage_t'),
broadcast=1,
)
return (
attention_weighted_encoder_context,
attention_weights_3d,
[decoder_hidden_encoder_outputs_sum],
coverage_t,
)
|
## @package task
# Module caffe2.python.task
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, context
from caffe2.python.schema import Field, from_blob_list
from collections import defaultdict
from copy import copy
from future.utils import viewitems
def _merge_node_kwargs(a, b):
# TODO(azzolini): consistency checks
if a is None:
return b
if b is None:
return a
c = copy(a)
c.update(b)
return c
@context.define_context(allow_default=True)
class Cluster(object):
"""
Context that keeps track of all the node names used.
Users shouldn't have to use them directly, since a Cluster is automatically
generated at the first usage of 'Node'.
"""
def __init__(self):
# list instead of set to keep order
self._nodes = []
self._node_kwargs = {}
def add_node(self, node):
if str(node) not in self._nodes:
self._nodes.append(str(node))
self._node_kwargs[str(node)] = _merge_node_kwargs(
node.kwargs(),
self._node_kwargs.get(str(node)))
def nodes(self):
"""
Returns the list of unique node names used within this context.
"""
return self._nodes
def node_kwargs(self):
return self._node_kwargs
@context.define_context(allow_default=True)
class Node(object):
"""
A Node context is used to indicate that all Tasks instantiated within will
run on the given node name. (Only the name of the node actually counts.)
Example:
with TaskGroup() as tg:
with Node('node1'):
s1 = execution_step(...)
Task(step=s1)
with Node('node2'):
s2 = execution_step(...)
with Node('node1'):
s3 = execution_step(...)
In this example, all three execution steps will run in parallel.
Moreover, s1 and s3 will run on the same node, and can see each
others blobs.
Additionally, a Node can be passed implementation-specific kwargs,
in order to specify properties of the node.
"""
def __init__(self, node='local', **kwargs):
self._name = str(node)
self._kwargs = kwargs
Cluster.current().add_node(self)
def __str__(self):
return self._name
def kwargs(self):
return self._kwargs
class WorkspaceType(object):
"""
Determines whether tasks of a TaskGroup will run directly at the global
workspace, which is kept alive across runs, or whether a new child
workspace will be created for the run and destroyed afterwards.
"""
PRIVATE = 'private'
GLOBAL = 'global'
def get_setup_nets(key, steps_or_nets, target):
init_net = core.Net(key + '/init')
exit_net = core.Net(key + '/exit')
init_nets = []
exit_nets = []
objs = []
for step_or_net in steps_or_nets:
if hasattr(step_or_net, 'get_all_attributes'):
objs += step_or_net.get_all_attributes(key)
elif hasattr(step_or_net, 'get_attributes'):
objs += step_or_net.get_attributes(key)
for obj in objs:
# these are needed in order to allow nesting of TaskGroup, which
# is a feature not yet implemented.
if hasattr(obj, '_setup_used') and obj._setup_used:
continue
if hasattr(obj, '_setup_target') and obj._setup_target != target:
continue
if hasattr(obj, 'setup'):
nets = obj.setup(init_net)
if isinstance(nets, (list, tuple)):
init_nets += nets
elif isinstance(nets, (core.Net, core.ExecutionStep)):
init_nets.append(nets)
elif nets is not None:
raise TypeError('Unsupported type for setup: %s' % type(nets))
obj._setup_used = True
if hasattr(obj, 'exit'):
nets = obj.exit(exit_net)
if isinstance(nets, (list, tuple)):
exit_nets += nets
elif isinstance(nets, (core.Net, core.ExecutionStep)):
exit_nets.append(nets)
elif nets is not None:
raise TypeError('Unsupported type for setup: %s' % type(nets))
obj._setup_used = True
if len(init_net.Proto().op) > 0:
init_nets.insert(0, init_net)
if len(exit_net.Proto().op) > 0:
exit_nets.insert(0, exit_net)
return init_nets, exit_nets
def add_setup_steps(step, init_nets, exit_nets, name):
if not init_nets and not exit_nets:
return step
steps = []
if init_nets:
steps.append(core.execution_step('%s:init' % name, init_nets))
steps.append(step)
if len(exit_nets) > 0:
steps.append(core.execution_step('%s:exit' % name, exit_nets))
return core.execution_step(name, steps)
@context.define_context(allow_default=False)
class TaskGroup(object):
"""
Context that gathers tasks which will run concurrently, potentially on
multiple nodes. All tasks in the same node will share the same workspace
and thus can share blobs, while tasks running in different nodes won't
be able to directly share data.
All tasks of the task group will start concurrently, and the task group
will finish execution when the last task of the group finishes.
Example:
# supose that s1 ... s5 are execution steps or nets.
with TaskGroup() as tg:
# these tasks go to default node 'local'
Task(step=s1)
Task(step=s2)
with Node('n2'):
Task(step=s3)
with Node('n1'):
Task(step=s4)
with Node('n2'):
Task(step=s5)
# this will run all steps in parallel.
# s1 and s2 will run at default node 'local'
# s3 and s5 will run at node 'n2'
# s4 will run at node 'n1'
session.run(tg)
"""
LOCAL_SETUP = 'local_setup'
def __init__(self, workspace_type=None):
self._plan_cache = None
self._tasks = []
self._already_used = False
self._prev_active = None
self._tasks_to_add = []
self._report_nets = {}
self._report_steps = []
self._workspace_type = workspace_type
self._tasks_by_node = None
def add(self, task):
assert not self._already_used, (
'Cannot add Task to an already used TaskGroup.')
assert (
self._workspace_type is None or
task._workspace_type is None or
self._workspace_type == task._workspace_type)
if task._workspace_type is None:
task._workspace_type = (
self._workspace_type or WorkspaceType.PRIVATE)
if self._workspace_type is None:
self._workspace_type = task._workspace_type
task._notify_used()
self._tasks.append(task)
def tasks(self):
for task in self._tasks_to_add:
self.add(task)
self._tasks_to_add = []
self._already_used = True
return self._tasks
def num_registered_tasks(self):
return len(self._tasks_to_add) + len(self._tasks)
def used_nodes(self):
# use list to keep order
used = []
for task in self._tasks + self._tasks_to_add:
if task.node not in used:
used.append(task.node)
return used
def report_step(self, step=None, node=None, interval_ms=1000):
"""
Add a "report step" to this TaskGroup. This step will run repeatedly
every `interval_ms` milliseconds for the duration of the TaskGroup
execution on each of the nodes. It is guaranteed that this step
will be run at least once after every Task in the node has finished.
"""
step = core.to_execution_step(step)
step.RunEveryMillis(interval_ms)
self._report_steps.append((str(node or Node.current(node)), step))
def report_net(self, net=None, node=None, report_interval=5):
"""
DEPRECATED. Use report_step instead.
"""
node = str(node or Node.current(node))
assert net is None or node not in self._report_nets
if node not in self._report_nets:
self._report_nets[node] = (
net if net else core.Net('%s/reporter' % node),
report_interval)
return self._report_nets[node][0]
def tasks_by_node(self, node_remap=None):
# tasks_by_node can't be called twice because the setup won't
# work properly a second time.
node_map = {}
for task in self.tasks():
node_map[task.node] =\
node_remap(task.node) if node_remap else task.node
if self._tasks_by_node is not None:
tasks_by_node, prev_node_map = self._tasks_by_node
assert prev_node_map == node_map, (
'Cannot call tasks_by_node multiple times.')
return tasks_by_node
# now we have report_steps. report_net is deprecated
for node, (net, interval) in viewitems(self._report_nets):
self.report_step(net, node=node, interval_ms=interval * 1000)
self._report_nets = {}
tasks_by_node = defaultdict(list)
for task in self.tasks():
mapped_node = node_map[task.node]
tasks_by_node[mapped_node].append(task)
report_steps_by_node = defaultdict(list)
for original_node, step in self._report_steps:
report_steps_by_node[node_map[original_node]].append(step)
grouped_by_node = TaskGroup()
for node, tasks in viewitems(tasks_by_node):
report_steps = report_steps_by_node[node]
node_inits, node_exits = get_setup_nets(
TaskGroup.LOCAL_SETUP,
[t.get_step() for t in tasks] + report_steps,
self)
# shortcut for single task with no queue
steps = report_steps
outputs = []
grouped_workspace_type = WorkspaceType.PRIVATE
for task in tasks:
step = task.get_step()
step.SetCreateWorkspace(
task.workspace_type() == WorkspaceType.PRIVATE)
if step is not None:
steps.append(step)
outputs += task.outputs()
# If any of the tasks in the node uses the global workspace,
# then set the grouped task to use the global workspace as well
if task.workspace_type() == WorkspaceType.GLOBAL:
grouped_workspace_type = WorkspaceType.GLOBAL
if len(steps) == 0:
steps.append(core.execution_step('empty', []))
if len(steps) == 1:
step = steps[0]
else:
step = core.execution_step(
'%s:body' % node, steps, concurrent_substeps=True)
if len(node_inits) > 0 or len(node_exits) > 0:
steps = []
if len(node_inits) > 0:
steps.append(
core.execution_step('%s:init' % node, node_inits))
steps.append(step)
if len(node_exits) > 0:
steps.append(
core.execution_step('%s:exit' % node, node_exits))
step = core.execution_step(node, steps)
Task(
node=node, step=step, outputs=outputs,
name='grouped_by_node',
group=grouped_by_node, workspace_type=grouped_workspace_type)
self._tasks_by_node = (grouped_by_node, node_map)
return grouped_by_node
def to_task(self, node=None):
node = str(Node.current(node))
tasks = self.tasks_by_node(lambda x: node).tasks()
if len(tasks) == 0:
return Task()
return tasks[0]
def workspace_type(self):
return self._workspace_type
class TaskOutput(object):
"""
Represents the output of a task. An output can be a blob,
a list of blob, or a record.
"""
def __init__(self, names):
self._schema = None
self._is_scalar = False
if isinstance(names, Field):
self._schema = names
names = self._schema.field_blobs()
self._is_scalar = type(names) not in (tuple, list)
if self._is_scalar:
names = [names]
self.names = names
self._values = None
def set(self, values, _fetch_func=None):
assert len(values) == len(self.names)
self._values = values
self._fetch_func = _fetch_func
def get(self):
assert self._values is not None, 'Output value not set yet.'
if self._is_scalar:
return self._values[0]
elif self._schema:
return from_blob_list(self._schema, self._values)
else:
return self._values
def fetch(self):
assert self._fetch_func is not None, (
'Cannot fetch value for this output.')
fetched_vals = [self._fetch_func(v) for v in self._values]
if self._is_scalar:
return fetched_vals[0]
elif self._schema:
return from_blob_list(self._schema, fetched_vals)
else:
return fetched_vals
def final_output(blob_or_record):
"""
Adds an output to the current Task, or if no task is active,
create a dummy task that returns the given blob or record
to the client. This will return the value of the blob or record when
the last task of the TaskGroup for a given node finishes.
"""
cur_task = Task.current(required=False) or Task()
return cur_task.add_output(blob_or_record)
class TaskOutputList(object):
""" Keeps a list of outputs for a task """
def __init__(self, outputs=None):
self.outputs = outputs or []
def names(self):
"""
Retrive the output names.
TODO(azzolini): make this schema-based.
"""
names = []
for o in self.outputs:
names += o.names
return names
def set_values(self, values, _fetch_func=None):
offset = 0
for o in self.outputs:
num = len(o.names)
o.set(values[offset:offset + num], _fetch_func)
offset += num
assert offset == len(values), 'Wrong number of output values.'
@context.define_context()
class Task(object):
"""
A Task is composed of an execution step and zero or more outputs.
Tasks are executed in the context of a TaskGroup, which, in turn, can
be run by a Session.
Task outputs are fetched by the session at the end of the run.
The recommended way of creating a task is by using `net_builder.ops`.
Example:
from net_builder import ops
with Node('trainer'), Task(name='my_task', num_instances=2):
with ops.task_init():
globl = ops.Const(0)
with ops.task_instance_init():
local = ops.Const(0)
with ops.loop(100):
ops.Copy(globl, local)
with ops.task_instance_exit():
ops.Add([globl, local], [globl])
with ops.task_exit():
ops.Mul([globl, globl], [blobl])
The task above will create 2 instances that will run in parallel.
Each instance will copy `local` to `globl` 100 times, Then Add `local`
to `globl` once. The `Mul` will only execute once, after all the instances
of the task have finished.
"""
# TASK_SETUP runs once per task, before/after all
# concurrent task instances start/finish.
TASK_SETUP = 'task_setup'
# Setup will run once for each instance of the task.
TASK_INSTANCE_SETUP = 'task_instance_setup'
REPORT_STEP = 'report_step'
_global_names_used = set()
@staticmethod
def _get_next_name(node, group, name):
basename = str(node) + '/' + str(name)
names_used = (
Task._global_names_used
if group is None else
set(t.name for t in group._tasks_to_add))
cur_name = basename
i = 0
while cur_name in names_used:
i += 1
cur_name = '%s:%d' % (basename, i)
return cur_name
def __init__(
self, step=None, outputs=None,
workspace_type=None, group=None, node=None, name=None,
num_instances=None):
"""
Instantiate a Task and add it to the current TaskGroup and Node.
Args:
step: If provided, this task will run this ExecutionStep.
outputs: If provided, the task will return the provided outputs
to the client at completion time.
node: If provided, force task execution on the given node.
name: Name of the Task.
num_instances: If provided, this task will be cloned num_instances
times at runtime, and all instances will run
concurrently.
"""
if not name and isinstance(step, core.ExecutionStep):
name = step.Proto().name
if not name:
name = 'task'
# register this node name with active context
self.node = str(Node.current(None if node is None else Node(node)))
self.group = TaskGroup.current(group, required=False)
self.name = Task._get_next_name(self.node, self.group, name)
# may need to be temporarily removed later if Task used as a context
if self.group is not None:
self.group._tasks_to_add.append(self)
self._already_used = False
self._step = None
self._step_with_setup = None
self._outputs = []
if step is not None:
self.set_step(step)
if outputs is not None:
self.add_outputs(outputs)
self._pipeline = None
self._is_pipeline_context = False
self._workspace_type = workspace_type
self._report_net = None
self._num_instances = num_instances
def __enter__(self):
# temporarily remove from _tasks_to_add to ensure correct order
if self.group is not None:
self.group._tasks_to_add.remove(self)
self._assert_not_used()
assert self._step is None, 'This Task already has an execution step.'
from caffe2.python import net_builder
self._net_builder = net_builder.NetBuilder(_fullname=self.name)
self._net_builder.__enter__()
return self
def __exit__(self, type, value, traceback):
self._net_builder.__exit__(type, value, traceback)
if type is None:
self.set_step(self._net_builder)
if self.group is not None:
self.group._tasks_to_add.append(self)
self._net_builder = None
def workspace_type(self):
return self._workspace_type
def _assert_not_used(self):
assert not self._already_used, (
'Cannot modify task since it is already been used.')
def add_output(self, output):
self._assert_not_used()
output = (
output if isinstance(output, TaskOutput) else TaskOutput(output))
self._outputs.append(output)
return output
def add_outputs(self, outputs):
self._assert_not_used()
if type(outputs) not in (list, tuple):
return self.add_output(outputs)
else:
return [self.add_output(output) for output in outputs]
def set_step(self, step):
self._assert_not_used()
self._step = core.to_execution_step(step)
def get_step(self):
if self._step_with_setup is not None:
return self._step_with_setup
if self._step is None:
self._step_with_setup = core.execution_step(self.name, [])
return self._step_with_setup
report_steps = [
s
for s in self._step.get_all_attributes(Task.REPORT_STEP)
if not hasattr(s, '_report_step_used')
]
for step in report_steps:
step._report_step_used = True
if not step.Proto().run_every_ms:
step.RunEveryMillis(1000)
task_init_nets, task_exit_nets = get_setup_nets(
Task.TASK_SETUP, [self._step] + report_steps, self)
instance_init_nets, instance_exit_nets = get_setup_nets(
Task.TASK_INSTANCE_SETUP, [self._step] + report_steps, self)
if len(self._outputs) == 0:
output_net = core.Net('%s:output' % self.name)
self.add_output(output_net.ConstantFill(
[], 1, dtype=core.DataType.INT32, value=0))
task_exit_nets.append(output_net)
# Add instance-level report steps
body = self._step if not report_steps else core.execution_step(
'%s:body' % self.name, report_steps + [self._step])
# Enclose with instance-level (thread-local) setup nets
step_with_instance_setup = add_setup_steps(
body, instance_init_nets, instance_exit_nets,
self.name + ':instance')
# Set up runtime concurrent instances
if self._num_instances and self._num_instances > 1:
step_with_instance_setup.SetCreateWorkspace(True)
step_with_instance_setup = core.execution_step(
'%s:parallel',
[step_with_instance_setup],
num_concurrent_instances=self._num_instances)
# Enclose with task-level setup nets
self._step_with_setup = add_setup_steps(
step_with_instance_setup, task_init_nets, task_exit_nets, self.name)
return self._step_with_setup
def output_list(self):
return TaskOutputList(self._outputs)
def outputs(self):
return self._outputs
def _notify_used(self):
self.get_step()
self._already_used = True
class SetupNets(object):
"""
Allow to register a list of nets to be run at initialization
and finalization of Tasks or TaskGroups.
For example, let's say you have the following:
init_net = core.Net('init')
my_val = init_net.ConstantFill([], 'my_val', value=0)
net = core.Net('counter')
net.Add([my_val, net.Const(1),], [my_val])
with TaskGroup() as task_group:
with Node('trainer'):
my_task = Task(step=[net])
In order to have `init_net` run once before `net` runs for the
first time, you can do one of the following:
net.add_attribute(Task.TASK_SETUP, SetupNets([init_net]))
or
net.add_attribute(TaskGroup.LOCAL_SETUP, SetupNets([init_net]))
- With Task.TASK_SETUP, init_net will run once at my_task startup.
- With TaskGroup.LOCAL_SETUP, init_net will run once on node 'trainer',
before any task of the task group is run on that node.
The same SetupNets object can be added to multiple nets. It will only
run once per Task/TaskGroup run.
"""
def __init__(self, init_nets=None, exit_nets=None):
self.init_nets = init_nets
self.exit_nets = exit_nets
def setup(self, init_net):
return self.init_nets
def exit(self, exit_net):
return self.exit_nets
|
import unittest
from caffe2.python import convnet_benchmarks as cb
from caffe2.python import test_util, workspace
@unittest.skipIf(not workspace.has_gpu_support, "no gpu")
class TestConvnetBenchmarks(test_util.TestCase):
def testConvnetBenchmarks(self):
all_args = [
'--batch_size 16 --order NCHW --iterations 1 '
'--warmup_iterations 1',
'--batch_size 16 --order NCHW --iterations 1 '
'--warmup_iterations 1 --forward_only',
]
for model in [cb.AlexNet, cb.OverFeat, cb.VGGA, cb.Inception]:
for arg_str in all_args:
args = cb.GetArgumentParser().parse_args(arg_str.split(' '))
cb.Benchmark(model, args)
if __name__ == '__main__':
unittest.main()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from caffe2.proto import caffe2_pb2
import caffe2.python.optimizer as optimizer
from caffe2.python.optimizer import (
build_sgd, build_multi_precision_sgd, build_ftrl, build_adagrad,
build_adam, build_yellowfin, build_rms_prop, add_weight_decay, SgdOptimizer)
from caffe2.python.optimizer_context import UseOptimizer
from caffe2.python.optimizer_test_util import (
OptimizerTestBase, LRModificationTestBase
)
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import numpy as np
from numpy.testing import assert_allclose, assert_equal
import math
import unittest
class TestLars(OptimizerTestBase, TestCase):
def testSparse(self):
raise unittest.SkipTest("no sparse support")
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_sgd(model, base_learning_rate=0.1, lars=0.5, **kwargs)
def check_optimizer(self, optimizer):
self.assertTrue(optimizer.get_auxiliary_parameters().shared)
self.assertFalse(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().shared:
tensor = workspace.FetchBlob(param)
np.testing.assert_allclose(np.array([1.0]), tensor, atol=1e-5)
class TestMomentumSgd(OptimizerTestBase, TestCase):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_sgd(model, base_learning_rate=0.1, momentum=0.1, **kwargs)
def check_optimizer(self, optimizer):
self.assertTrue(optimizer.get_auxiliary_parameters().shared)
self.assertTrue(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().shared:
tensor = workspace.FetchBlob(param)
np.testing.assert_allclose(np.array([1.0]), tensor, atol=1e-5)
class TestSgd(OptimizerTestBase, LRModificationTestBase, TestCase):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_sgd(model, base_learning_rate=0.1, **kwargs)
def check_optimizer(self, optimizer):
self.assertTrue(optimizer.get_auxiliary_parameters().shared)
self.assertFalse(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().shared:
tensor = workspace.FetchBlob(param)
np.testing.assert_allclose(np.array([1.0]), tensor, atol=1e-5)
class TestMultiPrecisionSgd(
OptimizerTestBase, LRModificationTestBase, TestCase
):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_multi_precision_sgd(
model, base_learning_rate=0.1, **kwargs
)
def check_optimizer(self, optimizer):
self.assertTrue(optimizer.get_auxiliary_parameters().shared)
self.assertFalse(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().shared:
tensor = workspace.FetchBlob(param)
np.testing.assert_allclose(np.array([1.0]), tensor, atol=1e-5)
@unittest.skipIf(not workspace.has_gpu_support, "No GPU support")
def testGPUDense(self):
super(TestMultiPrecisionSgd, self).testGPUDense(core.DataType.FLOAT16)
class TestFtrl(OptimizerTestBase, TestCase):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = True
return build_ftrl(
model,
engine=None,
alpha=1.0,
beta=0.1,
lambda1=0.0,
lambda2=0.0,
**kwargs
)
def check_optimizer(self, optimizer):
self.assertFalse(optimizer.get_auxiliary_parameters().shared)
self.assertTrue(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().local:
workspace.FetchBlob(param)
class TestAdagrad(OptimizerTestBase, LRModificationTestBase, TestCase):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_adagrad(model, base_learning_rate=1.0, lars=0.5, **kwargs)
def check_optimizer(self, optimizer):
self.assertFalse(optimizer.get_auxiliary_parameters().shared)
self.assertTrue(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().local:
workspace.FetchBlob(param)
class TestAdam(OptimizerTestBase, LRModificationTestBase, TestCase):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_adam(model, base_learning_rate=0.1, **kwargs)
def check_optimizer(self, optimizer):
self.assertTrue(optimizer.get_auxiliary_parameters().shared)
self.assertTrue(optimizer.get_auxiliary_parameters().local)
self.assertTrue(workspace.HasBlob("optimizer_iteration"))
iteration_tensor = workspace.FetchBlob("optimizer_iteration")
np.testing.assert_allclose(np.array([2000]),
iteration_tensor,
atol=1e-5)
for param in optimizer.get_auxiliary_parameters().shared:
workspace.FetchBlob(param)
for param in optimizer.get_auxiliary_parameters().local:
workspace.FetchBlob(param)
class TestYellowFin(OptimizerTestBase, TestCase):
# YellowFin: An automatic tuner for momentum SGD
# (https://arxiv.org/abs/1706.03471)
def build_optimizer(self, model):
self._skip_gpu = False
return build_yellowfin(model, base_learning_rate=0.1)
def check_optimizer(self, optimizer):
self.assertTrue(optimizer.get_auxiliary_parameters().shared)
self.assertTrue(optimizer.get_auxiliary_parameters().local)
self.assertTrue(workspace.HasBlob("optimizer_iteration"))
iteration_tensor = workspace.FetchBlob("optimizer_iteration")
np.testing.assert_allclose(np.array([2000]),
iteration_tensor,
atol=1e-5)
for param in optimizer.get_auxiliary_parameters().shared:
workspace.FetchBlob(param)
for param in optimizer.get_auxiliary_parameters().local:
workspace.FetchBlob(param)
def testSparse(self):
raise unittest.SkipTest("no sparse support")
def deb(self, val, beta, i, zero_debias):
if zero_debias:
return val / (1.0 - beta ** i)
else:
return val
def get_lr_mu(self, distance, grad_var, h_min, h_max):
# First tune based on dynamic range
if grad_var == 0:
dr = h_max / h_min
mu = ((np.sqrt(dr) - 1) / (np.sqrt(dr) + 1)) ** 2
lr_min = (1 + np.sqrt(mu)) ** 2 / h_max
return lr_min, mu
p = distance ** 2 * h_min ** 2 / 2 / grad_var
w3 = (-math.sqrt(p * p + 4.0 / 27.0 * p * p * p) - p) / 2.0
w = (1.0 if w3 > 0.0 else -1.0) * math.pow(math.fabs(w3), 1.0 / 3.0)
y = w - p / 3.0 / w
root = y + 1
root = min(root, 1.0 - 1e-6)
dr = h_max / h_min
mu = max(((np.sqrt(dr) - 1) / (np.sqrt(dr) + 1)) ** 2, root**2)
lr_min = (1 - np.sqrt(mu)) ** 2 / h_min
return lr_min, mu
def caffe2_yellowfin(self, zero_debias, grad_coef, n_dim, n_iter, gpu):
caffe2_res = {}
alpha = 1.0
mu = 0.0
beta = 0.999
curv_win_width = 20
epsilon = 1e-6
net = core.Net("net")
param_init_net = core.Net("param_init_net")
workspace.ResetWorkspace()
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
iteration = param_init_net.ConstantFill(
[],
"iteration",
shape=[1],
value=0,
dtype=core.DataType.INT64)
iter_mutex = param_init_net.CreateMutex([], ["iteration_mutex"])
net.AtomicIter([iter_mutex, iteration], [iteration])
pre_grad = param_init_net.ConstantFill(
[],
"pre_grad",
shape=[n_dim],
value=grad_coef
)
if gpu:
iteration = net.CopyCPUToGPU(
[iteration],
"iteration_cpu"
)
iteration_float = net.Cast([iteration], "iteration_float")
grad = net.Mul([pre_grad, iteration_float], "grad", broadcast=True)
w = param_init_net.ConstantFill([], "w", shape=[n_dim], value=0.0)
# a hack to create an object with __dict__
param_info = lambda: None
param_info.blob = w
param_info.grad = grad
optimizer.YellowFinOptimizer(
alpha=alpha,
mu=mu,
beta=beta,
curv_win_width=curv_win_width,
epsilon=epsilon,
zero_debias=zero_debias
)._run(
net,
param_init_net,
param_info
)
workspace.RunNetOnce(param_init_net)
workspace.CreateNet(net, overwrite=True)
for i in range(n_iter):
workspace.RunNet(net)
scalars_memory_blob = workspace.FetchBlob("w_scalars_memory")
g_norm2_avg = scalars_memory_blob[1]
g_norm2_min_avg = scalars_memory_blob[2]
g_norm2_max_avg = scalars_memory_blob[3]
distance_avg = scalars_memory_blob[4]
g_avg_blob = workspace.FetchBlob("w_g_avg")
res_lr = workspace.FetchBlob("w_lr_avg")[0]
res_mu = workspace.FetchBlob("w_mu_avg")[0]
g_deb = self.deb(g_avg_blob, beta, i + 1, zero_debias)
variance = max(
self.deb(g_norm2_avg, beta, i + 1, zero_debias) -
g_deb.dot(g_deb),
epsilon
)
if i > 0:
caffe2_res[i] = {
'h_max': np.exp(self.deb(g_norm2_max_avg,
beta,
i + 1,
zero_debias)),
'h_min': np.exp(self.deb(g_norm2_min_avg,
beta,
i + 1,
zero_debias)),
'var': variance,
'dist': self.deb(distance_avg, beta, i + 1, zero_debias),
'lr': res_lr,
'mu': res_mu
}
return caffe2_res
def numpy_yellowfin(self, zero_debias, grad_coef, n_dim, n_iter, gpu):
numpy_res = {}
target_h_max = 0.0
target_h_min = 0.0
target_g_norm_squared_avg = 0.0
target_g_norm_avg = 0.0
target_g_avg = 0.0
target_dist_avg = 0.0
target_lr = 1.0
target_mu = 0.0
for i in range(n_iter):
grad_val = (i + 1) * grad_coef
target_g_norm_squared_avg = 0.999 * target_g_norm_squared_avg + \
0.001 * np.sum((grad_val * np.ones([n_dim, ])) ** 2)
target_g_norm_avg = 0.999 * target_g_norm_avg + \
0.001 * np.linalg.norm(grad_val * np.ones([n_dim, ]))
target_g_avg = 0.999 * target_g_avg + 0.001 * grad_val
target_h_max = 0.999 * target_h_max + \
0.001 * np.log(grad_val ** 2 * n_dim)
target_h_min = 0.999 * target_h_min + \
0.001 * np.log((max(1, i + 2 - 20) * grad_coef) ** 2 * n_dim)
if zero_debias:
target_var = target_g_norm_squared_avg / \
(1 - 0.999 ** (i + 1)) - \
target_g_avg ** 2 * n_dim / (1 - 0.999 ** (i + 1)) ** 2
else:
target_var = target_g_norm_squared_avg - \
target_g_avg ** 2 * n_dim
target_dist_avg = 0.999 * target_dist_avg + \
0.001 * target_g_norm_avg / target_g_norm_squared_avg
if i > 0:
if zero_debias:
lr, mu = self.get_lr_mu(
target_dist_avg / (1.0 - 0.999 ** (i + 1)),
target_var,
np.exp(target_h_min / (1.0 - 0.999 ** (i + 1))),
np.exp(target_h_max / (1.0 - 0.999 ** (i + 1))))
target_lr = 0.999 * target_lr + 0.001 * lr
target_mu = 0.999 * target_mu + 0.001 * mu
numpy_res[i] = {
'h_max': np.exp(target_h_max / (1 - 0.999 ** (i + 1))),
'h_min': np.exp(target_h_min / (1 - 0.999 ** (i + 1))),
'var': target_var,
'dist': target_dist_avg / (1 - 0.999 ** (i + 1)),
'lr': target_lr,
'mu': target_mu
}
else:
lr, mu = self.get_lr_mu(
target_dist_avg,
target_var,
np.exp(target_h_min),
np.exp(target_h_max))
target_lr = 0.999 * target_lr + 0.001 * lr
target_mu = 0.999 * target_mu + 0.001 * mu
numpy_res[i] = {
'h_max': np.exp(target_h_max),
'h_min': np.exp(target_h_min),
'var': target_var,
'dist': target_dist_avg,
'lr': target_lr,
'mu': target_mu
}
return numpy_res
def compare_yellowfin_models(self,
model0,
model1,
zero_debias,
grad_coef,
n_dim,
n_iter,
gpu):
model0_res = model0(zero_debias, grad_coef, n_dim, n_iter, gpu)
model1_res = model1(zero_debias, grad_coef, n_dim, n_iter, gpu)
assert_equal(len(model0_res), len(model1_res))
for i in range(1, len(model0_res)):
assert_equal(model0_res[i].keys(), model1_res[i].keys())
for feat in model0_res[i].keys():
err_msg = \
'i=' + str(i) + ',\n' + \
'feat=' + feat + ',\n' + \
'grad_coef=' + str(grad_coef) + ',\n' + \
'zero_debias=' + str(zero_debias)
assert_allclose(model0_res[i][feat],
model1_res[i][feat],
rtol=1e-2,
err_msg=err_msg)
@unittest.skip("Results might vary too much. Only for individual use.")
def test_caffe2_cpu_vs_numpy(self):
n_dim = 1000000
n_iter = 50
cpu_device_opt = core.DeviceOption(caffe2_pb2.CPU)
with core.DeviceScope(cpu_device_opt):
for zero_debias, grad_coef in [
(False, 1.0),
(False, 0.1),
(False, 0.01),
(True, 1.0)
]:
self.compare_yellowfin_models(
self.caffe2_yellowfin,
self.numpy_yellowfin,
zero_debias,
grad_coef,
n_dim,
n_iter,
gpu=False
)
@unittest.skip("Results might vary too much. Only for individual use.")
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
def test_caffe2_gpu_vs_numpy(self):
n_dim = 1000000
n_iter = 50
gpu_device_opt = core.DeviceOption(caffe2_pb2.CUDA, 0)
with core.DeviceScope(gpu_device_opt):
for zero_debias in [False, True]:
for grad_coef in [1.0, 0.1, 0.01]:
self.compare_yellowfin_models(
self.caffe2_yellowfin,
self.numpy_yellowfin,
zero_debias,
grad_coef,
n_dim,
n_iter,
gpu=True
)
class TestRmsProp(OptimizerTestBase, LRModificationTestBase, TestCase):
def build_optimizer(self, model, **kwargs):
self._skip_gpu = False
return build_rms_prop(
model, base_learning_rate=0.1, epsilon=0.1, **kwargs
)
def check_optimizer(self, optimizer):
self.assertFalse(optimizer.get_auxiliary_parameters().shared)
self.assertTrue(optimizer.get_auxiliary_parameters().local)
for param in optimizer.get_auxiliary_parameters().local:
workspace.FetchBlob(param)
def testSparse(self):
raise unittest.SkipTest("no sparse support")
class TestMultiOptimizers(TestCase):
def test_multiple_optimizers(self):
from caffe2.python import brew, core, optimizer
from caffe2.python.model_helper import ModelHelper
model = ModelHelper(name="test")
fc1 = brew.fc(model, 'data', 'fc1', 100, 50)
fc2 = brew.fc(model, fc1, 'fc2', 50, 25)
pred = brew.fc(model, fc2, 'fc3', 25, 10)
(softmax, loss) = model.SoftmaxWithLoss(
[pred, 'label'],
['softmax', 'loss'],
)
model.AddGradientOperators([loss])
param_to_device = optimizer._get_param_to_device(model)
def infer_blob_device(blob_name):
return optimizer.get_param_device(
blob_name, "{}_grad".format(blob_name), param_to_device
)
sgd_1 = optimizer.SgdOptimizer(base_learning_rate=0.1)
sgd_2 = optimizer.SgdOptimizer(base_learning_rate=0.2)
adagrad = optimizer.AdagradOptimizer()
# Check same optimizer share the same learning rate.
with core.DeviceScope(infer_blob_device("fc1_w")):
sgd_1(model.net, model.param_init_net, "fc1_w", "fc1_w_grad")
with core.DeviceScope(infer_blob_device("fc1_b")):
sgd_1(model.net, model.param_init_net, "fc1_b", "fc1_b_grad")
fc1_lr_blobs = []
for op in model.net.Proto().op:
if op.type == 'WeightedSum' and op.input[0] == 'fc1_w' or \
op.input[0] == 'fc1_b':
fc1_lr_blobs.append(op.input[3])
self.assertEqual(fc1_lr_blobs[0], fc1_lr_blobs[1])
# Check different instance of the same optimizer has a different lr.
with core.DeviceScope(infer_blob_device("fc2_w")):
sgd_2(model.net, model.param_init_net, "fc2_w", "fc2_w_grad")
with core.DeviceScope(infer_blob_device("fc2_b")):
sgd_2(model.net, model.param_init_net, "fc2_b", "fc2_b_grad")
fc2_lr_blobs = []
for op in model.net.Proto().op:
if op.type == 'WeightedSum' and op.input[0] == 'fc2_w' or \
op.input[0] == 'fc2_b':
self.assertTrue(op.input[3] not in fc1_lr_blobs)
fc2_lr_blobs.append(op.input[3])
self.assertEqual(fc2_lr_blobs[0], fc2_lr_blobs[1])
# Check different optimizer type case
with core.DeviceScope(infer_blob_device("fc3_w")):
adagrad(model.net, model.param_init_net, "fc3_w", "fc3_w_grad")
with core.DeviceScope(infer_blob_device("fc3_b")):
adagrad(model.net, model.param_init_net, "fc3_b", "fc3_b_grad")
fc3_lr_blobs = []
for op in model.net.Proto().op:
if op.type == 'Adagrad' and op.input[0] == 'fc3_w' or \
op.input[0] == 'fc3_b':
self.assertTrue(op.input[3] not in fc2_lr_blobs)
self.assertTrue(op.input[3] not in fc1_lr_blobs)
fc3_lr_blobs.append(op.input[3])
self.assertEqual(fc3_lr_blobs[0], fc3_lr_blobs[1])
class TestWeightDecay(TestCase):
def test_weight_decay(self):
from caffe2.python import brew
from caffe2.python.model_helper import ModelHelper
model = ModelHelper(name="test", arg_scope={'order': 'NCHW'})
cnv = brew.conv(model, 'data', 'cnv', 32, 32, 4)
a = brew.fc(model, cnv, 'a', 100, 200)
pred = brew.fc(model, a, 'b', 200, 5)
(softmax, loss) = model.SoftmaxWithLoss(
[pred, 'label'],
['softmax', 'loss'],
)
model.AddGradientOperators([loss])
add_weight_decay(model, weight_decay=1e-4)
build_sgd(model, 0.11)
expected_weight_grad = {'b_w_grad', 'a_w_grad', 'cnv_w_grad'}
# Check the proto that all weights are decayed and not non-weights
# are decayed.
for op in model.net.Proto().op:
if op.type == 'WeightedSum' and 'wd_0_0' in op.input:
if op.output[0] not in expected_weight_grad:
print(
"Unexpected param for weight_decay: {}".
format(op.output[0])
)
self.assertTrue(op.output[0] in expected_weight_grad)
expected_weight_grad.remove(op.output[0])
self.assertEqual(
expected_weight_grad,
set(),
"Not all weights were decayed: {}".format(expected_weight_grad)
)
class TestOptimizerContext(TestCase):
def test_optimizer_context(self):
from caffe2.python import brew, optimizer
from caffe2.python.model_helper import ModelHelper
model = ModelHelper(name="test", arg_scope={'order': 'NCHW'})
count = optimizer._optimizer_instance_count['SgdOptimizer']
cnv_optim = SgdOptimizer(0.15)
weight_optim = SgdOptimizer(0.2)
bias_optim = SgdOptimizer(0.1)
with UseOptimizer(cnv_optim):
cnv = brew.conv(model, 'data', 'cnv', 32, 32, 4)
with UseOptimizer({'WEIGHT': weight_optim, 'BIAS': bias_optim}):
a = brew.fc(model, cnv, 'a', 100, 200)
pred = brew.fc(model, a, 'b', 200, 5)
(softmax, loss) = model.SoftmaxWithLoss(
[pred, 'label'],
['softmax', 'loss'],
)
model.AddGradientOperators([loss])
add_weight_decay(model, weight_decay=1e-4)
# use the following optimizer if none specified in param_info
build_sgd(model, 0.11)
expected_weight_grad = {'b_w_grad', 'a_w_grad', 'cnv_w_grad'}
expected_learning_rate = {
"SgdOptimizer_{}_lr_cpu".format(count): -0.15,
"SgdOptimizer_{}_lr_cpu".format(count + 1): -0.2,
"SgdOptimizer_{}_lr_cpu".format(count + 2): -0.1,
"SgdOptimizer_{}_lr_cpu".format(count + 3): -0.11
}
for op in model.net.Proto().op:
# Check the proto that all weights are decayed and not non-weights
# are decayed.
if op.type == 'WeightedSum' and 'wd_0_0' in op.input:
if op.output[0] not in expected_weight_grad:
print(
"Unexpected param for weight_decay: {}".
format(op.output[0])
)
self.assertTrue(op.output[0] in expected_weight_grad)
expected_weight_grad.remove(op.output[0])
# Check the learning rate for each parameter
if op.type == 'LearningRate':
val = 0
for arg in op.arg:
if arg.name == 'base_lr':
val = arg.f
self.assertAlmostEqual(
val,
expected_learning_rate[op.output[0]]
)
self.assertEqual(
expected_weight_grad,
set(),
"Not all weights were decayed: {}".format(expected_weight_grad)
)
|
## @package optimizer_context
# Module caffe2.python.optimizer_context
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import context
from caffe2.python.modifier_context import (
ModifierContext, UseModifierBase)
DEFAULT_OPTIM = 'DEFAULT'
@context.define_context(allow_default=True)
class OptimizerContext(ModifierContext):
"""
provide context to allow param_info to have different optimizers
"""
def has_optimizer(self, name):
return self._has_modifier(name)
def get_optimizer(self, name):
assert self.has_optimizer(name), (
"{} optimizer is not provided!".format(name))
return self._get_modifier(name)
class UseOptimizer(UseModifierBase):
'''
context class to allow setting the current context.
Example usage with brew:
- with UseOptimizer(optim):
brew.func
- with UseOptimizer({'WEIGHT': weight_optim}):
brew.func
- with UseOptimizer({'DEFAULT': optim, 'BIAS': bias_optim,
'WEIGHT': weight_optim}):
brew.func
- with UseOptimizer(optim1):
brew.func
with UseOptimizer(optim2):
brew.func
Example useage with layer:
optimizers = {'optim1': optim1, 'optim2': optim2}
with Optimizers(optimizers):
optim = OptimizerContext.current().get_optimizer('optim1')
layer(optim=optim)
'''
def _context_class(self):
return OptimizerContext
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import scope, core
from caffe2.proto import caffe2_pb2
import unittest
import threading
import time
SUCCESS_COUNT = 0
def thread_runner(idx, testobj):
global SUCCESS_COUNT
testobj.assertEquals(scope.CurrentNameScope(), "")
testobj.assertEquals(scope.CurrentDeviceScope(), None)
namescope = "namescope_{}".format(idx)
dsc = core.DeviceOption(caffe2_pb2.CUDA, idx)
with scope.DeviceScope(dsc):
with scope.NameScope(namescope):
testobj.assertEquals(scope.CurrentNameScope(), namescope + "/")
testobj.assertEquals(scope.CurrentDeviceScope(), dsc)
time.sleep(0.01 + idx * 0.01)
testobj.assertEquals(scope.CurrentNameScope(), namescope + "/")
testobj.assertEquals(scope.CurrentDeviceScope(), dsc)
testobj.assertEquals(scope.CurrentNameScope(), "")
testobj.assertEquals(scope.CurrentDeviceScope(), None)
SUCCESS_COUNT += 1
class TestScope(unittest.TestCase):
def testNamescopeBasic(self):
self.assertEquals(scope.CurrentNameScope(), "")
with scope.NameScope("test_scope"):
self.assertEquals(scope.CurrentNameScope(), "test_scope/")
self.assertEquals(scope.CurrentNameScope(), "")
def testNamescopeAssertion(self):
self.assertEquals(scope.CurrentNameScope(), "")
try:
with scope.NameScope("test_scope"):
self.assertEquals(scope.CurrentNameScope(), "test_scope/")
raise Exception()
except Exception:
pass
self.assertEquals(scope.CurrentNameScope(), "")
def testDevicescopeBasic(self):
self.assertEquals(scope.CurrentDeviceScope(), None)
dsc = core.DeviceOption(caffe2_pb2.CUDA, 9)
with scope.DeviceScope(dsc):
self.assertEquals(scope.CurrentDeviceScope(), dsc)
self.assertEquals(scope.CurrentDeviceScope(), None)
def testEmptyDevicescopeBasic(self):
self.assertEquals(scope.CurrentDeviceScope(), None)
dsc = core.DeviceOption(caffe2_pb2.CUDA, 9)
with scope.DeviceScope(dsc):
self.assertEquals(scope.CurrentDeviceScope(), dsc)
with scope.EmptyDeviceScope():
self.assertEquals(scope.CurrentDeviceScope(), None)
self.assertEquals(scope.CurrentDeviceScope(), dsc)
self.assertEquals(scope.CurrentDeviceScope(), None)
def testDevicescopeAssertion(self):
self.assertEquals(scope.CurrentDeviceScope(), None)
dsc = core.DeviceOption(caffe2_pb2.CUDA, 9)
try:
with scope.DeviceScope(dsc):
self.assertEquals(scope.CurrentDeviceScope(), dsc)
raise Exception()
except Exception:
pass
self.assertEquals(scope.CurrentDeviceScope(), None)
def testMultiThreaded(self):
"""
Test that name/device scope are properly local to the thread
and don't interfere
"""
global SUCCESS_COUNT
self.assertEquals(scope.CurrentNameScope(), "")
self.assertEquals(scope.CurrentDeviceScope(), None)
threads = []
for i in range(4):
threads.append(threading.Thread(
target=thread_runner,
args=(i, self),
))
for t in threads:
t.start()
with scope.NameScope("master"):
self.assertEquals(scope.CurrentDeviceScope(), None)
self.assertEquals(scope.CurrentNameScope(), "master/")
for t in threads:
t.join()
self.assertEquals(scope.CurrentNameScope(), "master/")
self.assertEquals(scope.CurrentDeviceScope(), None)
# Ensure all threads succeeded
self.assertEquals(SUCCESS_COUNT, 4)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from caffe2.python.core import CreatePythonOperator
import caffe2.python.hypothesis_test_util as hu
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
def SubFunctionThatThrowsRuntimeError():
raise RuntimeError("This is an intentional exception.")
def MainOpFunctionThatThrowsRuntimeError(inputs, _):
return SubFunctionThatThrowsRuntimeError()
def op_builder(name, index, extra):
iterations = [0]
assert name == 'name'
assert index == 5
assert extra - 4.2 < 0.0001
def my_op(inputs, outputs):
assert inputs[0].data[0] == iterations[0]
assert name == 'name'
assert index == 5
assert extra - 4.2 < 0.0001
iterations[0] += 1
return my_op
class PythonOpTest(hu.HypothesisTestCase):
@given(x=hu.tensor())
def test_feed(self, x):
def f(inputs, _):
self.assertEqual(x.shape, inputs[0].shape)
self.assertEqual(type(inputs[0].shape), tuple)
self.assertEqual(type(inputs[0].data), np.ndarray)
np.testing.assert_almost_equal(x, inputs[0].data)
op = CreatePythonOperator(f, ["x"], [])
workspace.FeedBlob("x", x)
workspace.RunOperatorOnce(op)
def test_exception(self):
op = CreatePythonOperator(MainOpFunctionThatThrowsRuntimeError, [], [])
with self.assertRaisesRegexp(
RuntimeError, "This is an intentional exception."
):
workspace.RunOperatorOnce(op)
@given(x=hu.tensor())
def test_feed_with_helper_function(self, x):
def f(inputs, _):
self.assertEqual(x.shape, inputs[0].shape)
self.assertEqual(type(inputs[0].shape), tuple)
self.assertEqual(type(inputs[0].data), np.ndarray)
np.testing.assert_almost_equal(x, inputs[0].data)
net = core.Net("test")
net.Python(f)(["x"], [])
workspace.FeedBlob("x", x)
workspace.RunNetOnce(net)
def test_builder_tuple(self):
net = core.Net("builder_template")
iter_blob = 'iter'
net.Python((op_builder, ['name', 5], {'extra': 4.2}))([iter_blob], [])
net.Python((op_builder, ['name', 5], {'extra': 4.2}))([iter_blob], [])
for repeat in range(2):
# check that the builder will be called exactly once for each
# PythonOp constructor. Cloning the net will also trigger a call
# to the builder when the net is created.
cloned_net = net.Clone('builder_%d' % repeat)
workspace.FeedBlob(iter_blob, np.array([0]))
# Builder gets called once per python op in the line below
workspace.CreateNet(cloned_net)
for i in range(10):
workspace.FeedBlob(iter_blob, np.array([i]))
workspace.RunNet(cloned_net)
@given(x=hu.tensor())
def test_feed_with_gc(self, x):
def f(inputs, _):
self.assertEqual(x.shape, inputs[0].shape)
np.testing.assert_almost_equal(x, inputs[0].data)
op = CreatePythonOperator(f, ["x"], [])
workspace.FeedBlob("x", x)
workspace.RunOperatorOnce(op)
del f
workspace.FeedBlob("x", x)
workspace.RunOperatorOnce(op)
@given(x=hu.tensor())
def test_reshape(self, x):
def f(inputs, outputs):
outputs[0].reshape(inputs[0].shape)
self.assertEqual(x.shape, inputs[0].shape)
self.assertEqual(x.shape, outputs[0].shape)
outputs[0].data[...] = inputs[0].data
op = CreatePythonOperator(f, ["x"], ["y"])
workspace.FeedBlob("x", x)
workspace.RunOperatorOnce(op)
y = workspace.FetchBlob("y")
np.testing.assert_almost_equal(x, y)
@given(x=hu.tensor())
def test_workspace_manipulation(self, x):
"""
Verify that python op can manipulate workspace directly
"""
def f(inputs, outputs, ws):
fetched = ws.blobs['internal'].fetch()
np.testing.assert_almost_equal(fetched, x)
ws = workspace.C.Workspace()
net = core.Net("test")
net.GivenTensorFill([], ['internal'], values=x, shape=x.shape)
net.Python(f, pass_workspace=True)([], [])
ws.run(net)
@given(x=hu.tensor())
def test_caught_exception_doesnt_terminate(self, x):
def f(inputs, outputs):
try:
raise Exception("Exception in handler")
except Exception:
pass
op = CreatePythonOperator(f, ["x"], ["y"])
workspace.FeedBlob("x", x)
workspace.RunOperatorOnce(op)
@given(x=hu.tensor(),
n=st.integers(min_value=1, max_value=20),
w=st.integers(min_value=1, max_value=20))
def test_multithreaded_evaluation(self, x, n, w):
def f(inputs, outputs):
outputs[0].reshape(inputs[0].shape)
outputs[0].data[...] = inputs[0].data
ops = [CreatePythonOperator(f, ["x"], [str(i)]) for i in range(n)]
net = core.Net("net")
net.Proto().op.extend(ops)
net.Proto().type = "dag"
net.Proto().num_workers = w
iters = 100
plan = core.Plan("plan")
plan.AddStep(core.ExecutionStep("test-step", net, iters))
workspace.FeedBlob("x", x)
workspace.RunPlan(plan.Proto().SerializeToString())
for i in range(n):
y = workspace.FetchBlob(str(i))
np.testing.assert_almost_equal(x, y)
@given(x=hu.tensor(), in_place=st.booleans(), **hu.gcs)
def test_gradient(self, x, in_place, gc, dc):
def f(inputs, outputs):
outputs[0].reshape(inputs[0].shape)
outputs[0].data[...] = inputs[0].data * 2
def grad_f(inputs, outputs):
# Ordering is [inputs, outputs, grad_outputs]
grad_output = inputs[2]
grad_input = outputs[0]
grad_input.reshape(grad_output.shape)
grad_input.data[...] = grad_output.data * 2
op = CreatePythonOperator(
f, ["x"], ["x" if in_place else "y"], grad_f=grad_f)
self.assertGradientChecks(gc, op, [x], 0, [0])
self.assertDeviceChecks(dc, op, [x], [0])
@given(inputs=hu.tensors(n=2), **hu.gcs)
def test_gradient_multiple(self, inputs, gc, dc):
(x1, x2) = inputs
def f(inputs, outputs):
for idx in [0, 1]:
self.assertEqual(type(inputs[idx].shape), tuple)
outputs[idx].reshape(inputs[idx].shape)
outputs[idx].data[...] = inputs[idx].data * 2
def grad_f(inputs, outputs):
# Ordering is [inputs, outputs, grad_outputs]
self.assertEqual(len(inputs), 6)
self.assertEqual(len(outputs), 2)
for (grad_output_idx, grad_input_idx) in [(4, 0), (5, 1)]:
grad_output = inputs[grad_output_idx]
grad_input = outputs[grad_input_idx]
grad_input.reshape(grad_output.shape)
grad_input.data[...] = grad_output.data * 2
op = CreatePythonOperator(f, ["x1", "x2"], ["y1", "y2"], grad_f=grad_f)
for idx in [0, 1]:
self.assertGradientChecks(gc, op, [x1, x2], idx, [0, 1])
self.assertDeviceChecks(dc, op, [x1, x2], [0, 1])
@given(inputs=hu.tensors(n=3), **hu.gcs)
def test_gradient_multiple_with_indices(self, inputs, gc, dc):
(x1, x2, x3) = inputs
def f(inputs, outputs):
for idx in [0, 1, 2]:
self.assertEqual(type(inputs[idx].shape), tuple)
outputs[idx].reshape(inputs[idx].shape)
outputs[idx].data[...] = inputs[idx].data * 2
def grad_f(inputs, outputs):
# Ordering is [inputs, outputs, grad_outputs]
self.assertEqual(len(inputs), 8)
self.assertEqual(len(outputs), 1)
for (grad_output_idx, grad_input_idx) in [(6, 0)]:
grad_output = inputs[grad_output_idx]
grad_input = outputs[grad_input_idx]
grad_input.reshape(grad_output.shape)
grad_input.data[...] = grad_output.data * 2
op = CreatePythonOperator(
f, ["x1", "x2", "x3"], ["y1", "y2", "y3"],
grad_f=grad_f,
grad_output_indices=[0, 2], # Receive grad outputs for y1 and y3
grad_input_indices=[0] # Produce grad inputs for x1
)
self.assertGradientChecks(gc, op, [x1, x2, x3], 0, [0, 2])
self.assertDeviceChecks(dc, op, [x1, x2, x3], [0, 1, 2])
|
## @package hsm_util
# Module caffe2.python.hsm_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import hsm_pb2
'''
Hierarchical softmax utility methods that can be used to:
1) create TreeProto structure given list of word_ids or NodeProtos
2) create HierarchyProto structure using the user-inputted TreeProto
'''
def create_node_with_words(words, name='node'):
node = hsm_pb2.NodeProto()
node.name = name
for word in words:
node.word_ids.append(word)
return node
def create_node_with_nodes(nodes, name='node'):
node = hsm_pb2.NodeProto()
node.name = name
for child_node in nodes:
new_child_node = node.children.add()
new_child_node.MergeFrom(child_node)
return node
def create_hierarchy(tree_proto):
max_index = 0
def create_path(path, word):
path_proto = hsm_pb2.PathProto()
path_proto.word_id = word
for entry in path:
new_path_node = path_proto.path_nodes.add()
new_path_node.index = entry[0]
new_path_node.length = entry[1]
new_path_node.target = entry[2]
return path_proto
def recursive_path_builder(node_proto, path, hierarchy_proto, max_index):
node_proto.offset = max_index
path.append([max_index,
len(node_proto.word_ids) + len(node_proto.children), 0])
max_index += len(node_proto.word_ids) + len(node_proto.children)
if hierarchy_proto.size < max_index:
hierarchy_proto.size = max_index
for target, node in enumerate(node_proto.children):
path[-1][2] = target
max_index = recursive_path_builder(node, path, hierarchy_proto,
max_index)
for target, word in enumerate(node_proto.word_ids):
path[-1][2] = target + len(node_proto.children)
path_entry = create_path(path, word)
new_path_entry = hierarchy_proto.paths.add()
new_path_entry.MergeFrom(path_entry)
del path[-1]
return max_index
node = tree_proto.root_node
hierarchy_proto = hsm_pb2.HierarchyProto()
path = []
max_index = recursive_path_builder(node, path, hierarchy_proto, max_index)
return hierarchy_proto
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python.schema import (
Struct, FetchRecord, NewRecord, FeedRecord, InitEmptyRecord)
from caffe2.python import core, workspace
from caffe2.python.session import LocalSession
from caffe2.python.dataset import Dataset
from caffe2.python.pipeline import pipe
from caffe2.python.queue_util import Queue
from caffe2.python.task import TaskGroup
from caffe2.python.test_util import TestCase
from caffe2.python.net_builder import ops
import numpy as np
import math
class TestPipeline(TestCase):
def test_dequeue_many(self):
init_net = core.Net('init')
N = 17
NUM_DEQUEUE_RECORDS = 3
src_values = Struct(
('uid', np.array(range(N))),
('value', 0.1 * np.array(range(N))))
expected_dst = Struct(
('uid', 2 * np.array(range(N))),
('value', np.array(N * [0.0])))
with core.NameScope('init'):
src_blobs = NewRecord(init_net, src_values)
dst_blobs = InitEmptyRecord(init_net, src_values.clone_schema())
counter = init_net.Const(0)
ONE = init_net.Const(1)
def proc1(rec):
with core.NameScope('proc1'):
out = NewRecord(ops, rec)
ops.Add([rec.uid(), rec.uid()], [out.uid()])
out.value.set(blob=rec.value(), unsafe=True)
return out
def proc2(rec):
with core.NameScope('proc2'):
out = NewRecord(ops, rec)
out.uid.set(blob=rec.uid(), unsafe=True)
ops.Sub([rec.value(), rec.value()], [out.value()])
ops.Add([counter, ONE], [counter])
return out
src_ds = Dataset(src_blobs)
dst_ds = Dataset(dst_blobs)
with TaskGroup() as tg:
out1 = pipe(
src_ds.reader(),
output=Queue(
capacity=11, num_dequeue_records=NUM_DEQUEUE_RECORDS),
processor=proc1)
out2 = pipe(out1, processor=proc2)
pipe(out2, dst_ds.writer())
ws = workspace.C.Workspace()
FeedRecord(src_blobs, src_values, ws)
session = LocalSession(ws)
session.run(init_net)
session.run(tg)
output = FetchRecord(dst_blobs, ws=ws)
num_dequeues = ws.blobs[str(counter)].fetch()
self.assertEquals(
num_dequeues, int(math.ceil(float(N) / NUM_DEQUEUE_RECORDS)))
for a, b in zip(output.field_blobs(), expected_dst.field_blobs()):
np.testing.assert_array_equal(a, b)
|
## @package memonger
# Module caffe2.python.memonger
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import networkx as nx
import collections
import time
import copy
from caffe2.python import workspace, core
from caffe2.proto import caffe2_pb2
import enum
import logging
from future.utils import viewitems, viewvalues
import caffe2.python._import_c_extension as C
log = logging.getLogger("memonger")
log.setLevel(logging.INFO)
LiveRange = collections.namedtuple('LiveRange', ["defined", "used", "size"])
def share_grad_blobs(
net,
losses,
param_grads,
namescope,
dont_share_blobs=None,
share_activations=False,
blob_shapes=None,
):
'''
Implements similar optimization as Torch's shareGradInput():
for the gradients that are passed between layers, share blobs between
operators when possible. This yields significant memory savings with
deep networks.
Returns an optimized protobuf (assign to net._net)
'''
def is_grad_blob(b):
name = str(b)
# Note: need to look at _{namescope} pattern as it matches
# to handle the auto-split gradients
return name.endswith("_grad") and (name.startswith(namescope) or
name.startswith("_" + namescope)) and name not in param_grads
def is_grad_op(op):
# TODO: something smarter
for b in list(op.input) + list(op.output):
if is_grad_blob(b):
return True
return False
log.warn("NOTE: Executing memonger to optimize gradient memory")
# Collect ops that have something to do with gradients
if namescope != "" and not namescope.endswith("/"):
namescope += "/"
netproto = copy.deepcopy(net.Proto())
activations = []
external_output = set(net.Proto().external_output)
# Hacky way to get activations, think of a better way
for op in net.Proto().op:
for b in op.output:
if b + "_w" in op.input and b not in external_output:
activations.append(b)
# Remove last activations, as they are usually accessed externally
activations = set(activations[:-2])
# Gradient ops
grad_op_indices = []
for idx, op in enumerate(netproto.op):
if (is_grad_op(op)):
grad_op_indices.append(idx)
shared_blobs = set()
for op in net.Proto().op:
for b in list(op.input) + list(op.output):
if is_grad_blob(b) or (share_activations and b in activations):
shared_blobs.add(b)
start_time = time.time()
optim_str = C.memonger_compute_blob_recycling_for_dag(
netproto.SerializeToString(),
[str(s).encode('utf-8') for s in losses],
grad_op_indices,
set(str(s).encode('utf-8') for s in shared_blobs),
namescope.encode('utf-8'),
set() if dont_share_blobs is None else dont_share_blobs,
{} if blob_shapes is None else blob_shapes
)
log.info("Memonger memory optimization took {} secs".format(
time.time() - start_time),
)
optim = caffe2_pb2.NetDef()
optim.ParseFromString(optim_str)
assert verify_graph_equality(net.Proto(), optim), \
"Memonger graph is not equal to original."
assert verify_inplace_blobs(net.Proto(), optim), \
"Inplace assignments differ in memonger net."
return optim
def optimize_inference_for_dag(net, input_blobs, namescope=""):
netproto = copy.deepcopy(net.Proto())
external_input = set(net.Proto().external_input)
external_output = set(net.Proto().external_output)
def is_activation_blob(b):
return b not in external_input and b not in external_output
activation_blobs = set()
seen_as_output = set()
ops = list(net.Proto().op)
op_indices = [index for index, op in enumerate(net.Proto().op)]
# Sanity check: check that all external inputs are properlyh accounted
# and that no gradient ops are included in 'net'
for op in ops:
for b in op.input:
if is_activation_blob(b):
activation_blobs.add(b)
if b not in seen_as_output:
assert False, "{} not in external input".format(b)
for b in op.output:
if is_activation_blob(b):
activation_blobs.add(b)
seen_as_output = seen_as_output.union(set(op.output))
assert not op.is_gradient_op, \
"You can only pass inference-only nets to optimize_inference_for_dag"
start_time = time.time()
optim_str = C.memonger_compute_blob_recycling_for_dag(
netproto.SerializeToString(),
[str(s).encode('utf-8') for s in input_blobs],
op_indices,
set(str(s).encode('utf-8') for s in activation_blobs),
namescope.encode('utf-8'),
set(),
{}
)
log.info("Memonger memory optimization took {} secs".format(
time.time() - start_time),
)
optim = caffe2_pb2.NetDef()
optim.ParseFromString(optim_str)
assert verify_graph_equality(net.Proto(), optim), \
"Memonger graph is not equal to original."
assert verify_inplace_blobs(net.Proto(), optim), \
"Inplace assignments differ in memonger net."
return optim
def estimate_memory_usage(protos, shapes, types, devicescope):
import numpy as np
'''
Estimate memory usage of a model. This is an estimate because
we assume a single threaded execution and miss some internal
memory usage of operators. Only estimates the memory for a given
device scope.
Also, currently it does not handle correctly if blob sizes vary
during execution, as it uses only the final blob size.
Returns (total, highwater, by op type) memory allocation in bytes.
'''
sizeofs = {
caffe2_pb2.TensorProto.DOUBLE: 8,
caffe2_pb2.TensorProto.FLOAT: 4,
caffe2_pb2.TensorProto.FLOAT16: 2,
caffe2_pb2.TensorProto.INT32: 4,
caffe2_pb2.TensorProto.INT8: 1,
caffe2_pb2.TensorProto.UINT8: 1,
caffe2_pb2.TensorProto.UINT16: 2,
caffe2_pb2.TensorProto.INT16: 2,
caffe2_pb2.TensorProto.BOOL: 1,
caffe2_pb2.TensorProto.INT64: 8,
}
def split_net(proto):
ops = [op for op in proto.op if
op.device_option == devicescope or op.type in {"Free", "Alias"}]
del proto.op[:]
proto.op.extend(ops)
return proto
def num_bytes(blob):
if blob not in shapes or blob not in types:
log.warning("Unknown blob encountered: {}".format(blob))
return 0
sizeof = sizeofs[types[blob]]
return sizeof * np.prod(shapes[blob])
protos = [split_net(proto) for proto in protos]
allocs_by_ops = collections.defaultdict(lambda: 0)
# Evaluate
current_allocated = 0
max_allocated = 0
total_allocated = 0
allocated = set()
for proto in protos:
for op in proto.op:
if op.type == "Free" or op.type == "Alias":
for o in op.output:
if o in allocated:
current_allocated -= num_bytes(o)
allocated.remove(o)
else:
for output in op.output:
if output not in allocated:
nbytes = num_bytes(output)
total_allocated += nbytes
current_allocated += nbytes
max_allocated = max(max_allocated, current_allocated)
allocated.add(output)
allocs_by_ops[op.type] += nbytes
return (total_allocated, max_allocated, allocs_by_ops)
def release_blobs_when_used(netproto, dont_free_blobs, selector_fun=None):
'''
Insert Free-ops after a blob has been used the last time, so that its
memory can be reclaimed. Use this only with efficient caching memory
managers (such as CUB, --caffe2_cuda_memory_pool=cub).
Blobs used with Alias op won't be freed.
@dont_free_blobs: is a set of blobs that should not be freed
@selector_fun: optional lambda that return True if blob name
can be released. Use for easy special filtering, like
excluding blobs with "loss" in the name.
Returns a new protobuffer. To use with a model, use:
model.net._net = memonger.release_blobs_when_used(..)
'''
input_blobs = set()
can_release = set()
alias_blobs = set()
netproto = copy.deepcopy(netproto)
for op in netproto.op:
if op.type == 'Alias':
alias_blobs.add(op.input[0])
continue
for inp in op.input:
input_blobs.add(inp)
for outp in op.output:
if outp not in input_blobs:
if selector_fun is None or selector_fun(outp):
can_release.add(outp)
# Remove such blobs that are not input at all and external outputs
can_release = can_release - set(netproto.external_output)
can_release = can_release.intersection(input_blobs)
can_release = can_release - dont_free_blobs
can_release = can_release - alias_blobs
ops = list(netproto.op)
# .. then find last use of each can-release blob, and insert a Free op
for j in reversed(range(0, len(netproto.op))):
op = netproto.op[j]
for inp in op.input:
if inp in can_release:
can_release.remove(inp)
ops.insert(j + 1, core.CreateOperator("Free", [inp], [inp]))
del netproto.op[:]
netproto.op.extend(ops)
return netproto
def _find_source_nodes(g):
''' Return nodes without predecessors '''
ret = []
for cn in g:
cur_pred = list(g.predecessors(cn))
if not cur_pred:
ret.append(cn)
return ret
def _find_target_nodes(g):
''' Return nodes without successors '''
ret = []
for cn in g:
cur_succ = list(g.successors(cn))
if not cur_succ:
ret.append(cn)
return ret
def _add_single_target_ifneeded(g):
targets = _find_target_nodes(g)
assert len(targets) >= 1
if len(targets) == 1:
return g
ret = copy.deepcopy(g)
def _next_available_idx(g):
ret = -1
for cn in g:
if cn > ret:
ret = cn
ret += 1
return ret
target_node_idx = _next_available_idx(g)
ret.add_node(target_node_idx)
for cn in targets:
ret.add_edge(cn, target_node_idx)
return ret
def _get_path(pred_list, dist_list):
''' Get the path from nx.bellman_ford()'s output '''
# distances are negative
assert all(dist_list[x] <= 0 for x in dist_list)
# node with longest distance to source is the target
target = min(dist_list, key=lambda x: dist_list[x])
ret = []
cur = target
while cur is not None:
ret.append(cur)
# Hack to get networkx 2.0 happy: it uses list in pred.
# TODO(tulloch): are there cases with multiple predecessors?
try:
cur = pred_list[cur][0]
except TypeError:
cur = pred_list[cur]
return list(reversed(ret))
def _get_longest_paths(g, source_nodes):
''' Get the longest path for nodes in 'source_nodes'
Find with bellman_ford() by setting weight = -1
'''
ng = copy.deepcopy(g)
for u, v in ng.edges():
ng[u][v]["weight"] = -1
ret = {}
for cn in source_nodes:
pred, dist = nx.bellman_ford(ng, cn, weight="weight")
path = _get_path(pred, dist)
assert path[0] == cn
assert len(path) - 1 == -dist[path[-1]]
ret[cn] = path
return ret
def _build_tree(paths):
''' Build a tree for given paths based on common elements.
Last elements of all paths are the same, which is the root of the tree.
'''
assert all(cp[-1] == paths[0][-1] for cp in paths)
g = nx.DiGraph()
node_set = {y for x in paths for y in x}
g.add_nodes_from(node_set)
for cp in paths:
for ce in zip(cp[0:-1], cp[1:]):
g.add_edge(ce[1], ce[0])
root = paths[0][-1]
_compute_tree_height(g, root)
return (g, root)
def _compute_tree_height(g, root):
''' Compute the heights of the tree for all nodes
Height of leaves are 0
'''
def _get_height(root):
children = list(g.successors(root))
height = 0
if children:
child_heights = [_get_height(x) for x in children]
height = max(child_heights) + 1
g.node[root]["height"] = height
return height
_get_height(root)
def _sort_tree_leaves(g, root):
''' For each node, sort its child nodes based on the height of the nodes.
Return the leaf nodes of the tree after sorting.
'''
def _get_height(root):
return g.node[root]["height"]
def _get_sorted_leaves(root):
children = list(g.successors(root))
if not children:
return [root]
child_heights = [_get_height(x) for x in children]
order = sorted(range(len(children)), key=lambda x: child_heights[x])
ret = []
for co in order:
cr = children[co]
ret += _get_sorted_leaves(cr)
return ret
return _get_sorted_leaves(root)
def topological_sort_traversal_longest_path(g):
''' The graph 'g' may contain several source nodes (nodes without incoming
edge), which could be in any order and still be a valid
topological sorting result. We would like to arrange these source nodes
so that the average live spans of the computed blobs are shorter.
The idea is to sort the source nodes based on the length of their path to
the target node so that the one with longer path is used first.
This is done by:
- Add a single target node if there are multiple target nodes in 'g'.
- Find the longest path between each source and the target node.
- Convert the longest paths to a tree with the target node being the root
and source nodes being the leaves.
- Sort the nodes of the tree based on the height of the tree.
'''
gt = _add_single_target_ifneeded(g)
source_nodes = _find_source_nodes(gt)
lpaths = _get_longest_paths(gt, source_nodes)
tree, root = _build_tree(list(viewvalues(lpaths)))
sorted_sources = _sort_tree_leaves(tree, root)
assert(sorted(sorted_sources) == sorted(source_nodes))
if nx.__version__ < '2.0':
ret = nx.topological_sort(g, sorted_sources)
else:
# Manually making a sorted descendent list
dependency_order = list(sorted_sources)
seen_nodes = set(sorted_sources)
for s in sorted_sources:
desc = nx.descendants(g, s)
for d in desc:
if d not in seen_nodes:
seen_nodes.add(d)
dependency_order.append(d)
sort_key = dict((v, len(dependency_order) - i) for i, v in enumerate(dependency_order))
ret = nx.algorithms.dag.lexicographical_topological_sort(
g, key=lambda x: sort_key[x])
ret = list(ret)
assert(len(ret) == len(g.node))
return ret
def topological_sort_traversal(g):
return list(nx.topological_sort(g))
def compute_ranges(linearized_ops, blob_sizes=None):
if not blob_sizes:
log.warning('Provide blob sizes to get more accurate assignments.')
blobs = collections.defaultdict(
lambda: LiveRange(defined=None, used=None, size=None))
for i, op in enumerate(linearized_ops):
for blob in op.input:
used = blobs[blob].used
if used is None:
used = i
else:
used = max(used, i)
blobs[blob] = blobs[blob]._replace(used=used)
blob_size = blob_sizes[blob] if blob_sizes else None
assert not blob_sizes or blob_size is not None
blobs[blob] = blobs[blob]._replace(size=blob_size)
for blob in op.output:
defined = blobs[blob].defined
if defined is None:
defined = i
else:
defined = min(defined, i)
blobs[blob] = blobs[blob]._replace(defined=defined)
blob_size = blob_sizes[blob] if blob_sizes else None
assert not blob_sizes or blob_size is not None
blobs[blob] = blobs[blob]._replace(size=blob_size)
return blobs
def is_compatible(candidate_range, assignment, static_blobs):
(name, range_) = assignment[-1]
if name in static_blobs:
return False
if candidate_range.defined is None or range_.defined is None \
or range_.used is None:
return False
return candidate_range.defined > range_.used
def compute_blob_assignments(assignments):
blob_assignments = {}
for assignment in assignments:
if len(assignment) == 1:
continue
last_blob, _ = assignment[-1]
for (blob, _) in assignment:
blob_assignments[blob] = last_blob
return blob_assignments
def _get_max_size(assignment):
if not assignment:
return 0
ret = max([x[1].size for x in assignment])
ret = 0 if ret is None else ret
return ret
def get_memory_usage(assignments):
ret = 0
for cur in assignments:
ret += _get_max_size(cur)
return ret
def compute_assignments_greedy(ranges_sorted, init_assignments=None):
assignments = init_assignments or []
visited = {y[0] for x in assignments for y in x}
for (name, range_) in ranges_sorted:
if name in visited:
continue
assigned = False
best_assignment = 0
min_dist = float("inf")
candidate_size = range_.size or 0
for idx, assignment in enumerate(assignments):
if is_compatible(range_, assignment, []):
assigned = True
dist = abs(_get_max_size(assignment) - candidate_size)
if dist < min_dist:
min_dist = dist
best_assignment = idx
if assigned:
assignment = assignments[best_assignment]
assignment.append((name, range_))
else:
assignments.append([(name, range_)])
return assignments
def _get_count(assignments):
''' Return number of blobs in assignments '''
if assignments:
return sum([len(x) for x in assignments])
return 0
def compute_assignments_dp(ranges_sorted, init_assignment, counter=None):
''' Compute assignment for blobs in 'ranges_sorted' on top of 'init_assignment'
using dynamic programming + recursion.
ranges_sorted: blobs sorted by 'used'
init_assignment: assignment to start with, blobs in 'ranges_sorted' should
not be used in 'init_assignment'
Using f(b, k, init) to represent the best assignment for blobs b[0:k]
given initial assignment 'init', we have
f(b, k, init) = f(b, j, init) +
find_best(b[j:k], f(b, j, init))
where j is the index of the last best assignment that is independent of
blob b[k - 1] (b[k - 1] is compatible with all assignments in
f(b, j, init)), and find_best(b1, init1) gives the best assignment
for blobs in 'b1' based on the initial assignment 'init1', and blobs
b1[0:-1] should be incompatible with b1[-1]. f(b, len(b), []) gives
the best assignment for blobs 'b'.
For find_best(b, init), since b[0:-1] are not compatible with b[-1], we
could reduce it to a smaller problem to find best assignment for b[0:-1]
as
find_best(b, init) = min {
f(b[0:-1], len(b) - 1, init - x) + [x, b[-1]] for x in init, or
f(b[0:-1], len(b) - 1, init) + [b[-1]]
}
where min{} gives the assignment with minimum memory usage.
'''
def _get_compatible_prev(candidate_range, best_assignments, cur_idx):
''' Find closest position k of best_assignments that is independent of
candidate_range that candiate_range is compatible with all assignments
in best_assignments[k].
Return -1 if not found.
'''
def is_compatible_all(candidate_range, assignments):
''' return true if compatiable for all assignments in assignments '''
return all([is_compatible(candidate_range[1], x, []) for x in assignments])
ii = cur_idx - 1
while ii >= 0:
cba = best_assignments[ii]
if is_compatible_all(candidate_range, cba):
return ii
ii -= 1
return -1
def _find_best(ranges, init_assignment, prev_best_assignment, counter):
''' Find the best assignment for blobs 'ranges' given an initialized
assignment 'init_assignment'.
Blobs in ranges[0:-1] should be incompatible with blob range[-1].
'prev_best_assignment': best assignment for blobs in ranges[:-1]
By assigning ranges[-1] to each assignment k in 'init_assignment' or
in a new assignment, the problem becomes a smaller problem to find
the best assignment for ranges[0:-1] given the initial assignment
init_assigment[0:k, (k+1):-1].
'''
# Blob to check
find_range = ranges[-1]
# Blobs in ranges[0:-1] are incompatible with ranges[-1] so that we can
# reduce it to a smaller problem.
assert all(not is_compatible(x[1], [find_range], []) for x in ranges[0:-1])
sz = len(init_assignment)
best_candidates = []
# Try to assign 'find_range' to each assignment in init_assignment
for ii in range(sz):
if not is_compatible(find_range[1], init_assignment[ii], []):
continue
cur_best = copy.deepcopy(init_assignment)
cur_best[ii].append(find_range)
if len(ranges) > 1:
cur_best_tmp = [x for i, x in enumerate(cur_best) if i != ii]
# reduce to a smaller dp problem
cur_best_tmp = compute_assignments_dp(
ranges[:-1], cur_best_tmp, counter)
cur_best = cur_best_tmp + [cur_best[ii]]
best_candidates.append(cur_best)
# Try to put 'find_range' in a new assignment
best_candidates.append(prev_best_assignment + [[find_range]])
ret = min(best_candidates, key=lambda x: get_memory_usage(x))
return ret
if not counter:
counter = [0]
counter[0] += 1
if counter and counter[0] % 5000 == 0:
rs = [ranges_sorted[0][1].defined, ranges_sorted[-1][1].used]
log.info('Finding assignments {} ({} -> {})...'.format(
counter[0], rs[0], rs[1]))
init_assignment = init_assignment or []
# best_assignments[k]: best assignments for first k blobs ranges_sorted[0:(k+1)]
best_assignments = []
# Find best assignment for blobs ranges_sorted[0:ii]
for ii, cur_range in enumerate(ranges_sorted):
# closest best_assignment that is independent of ranges_sorted[ii]
prev_idx = _get_compatible_prev(cur_range, best_assignments, ii)
prev_best = copy.deepcopy(init_assignment) if prev_idx < 0 else \
copy.deepcopy(best_assignments[prev_idx])
# Need to find best assignment for blobs in 'ranges_part'
ranges_part = ranges_sorted[(prev_idx + 1):(ii + 1)]
cur_best = _find_best(
ranges_part, prev_best,
best_assignments[-1] if best_assignments else init_assignment,
counter)
assert _get_count(cur_best) == _get_count(prev_best) + len(ranges_part)
best_assignments.append(copy.deepcopy(cur_best))
assert len(best_assignments) == len(ranges_sorted)
best = best_assignments[-1]
return best
def get_updated_ranges(ranges, max_live=None):
''' Set LiveRange.defined = -1 if it is None
Set LiveRange.used = max_live if it is None
Set LiveRanee.size = 1 if it is None
'''
def _get_max_live(ranges):
max_live = max(x[1].used for x in ranges if x[1].used) + 1
return max_live
def _update_range(x, max_live, size):
cx = x
if x[1].defined is None:
cx = (cx[0], cx[1]._replace(defined=-1))
if x[1].used is None:
cx = (cx[0], cx[1]._replace(used=max_live))
if x[1].size is None:
cx = (cx[0], cx[1]._replace(size=size))
return cx
if max_live is None:
max_live = _get_max_live(ranges)
ranges = [_update_range(x, max_live, 1) for x in ranges]
return ranges
def compute_assignments(ranges, static_blobs, algo):
'''
algo: Method used to find assignments (AssignmentAlgorithm.GREEDY or
AssignmentAlgorithm.DYNAMIC_PROGRAMMING).
AssignmentAlgorithm.DYNAMIC_PROGRAMMING gives optimal solution at the
cost of more computation.
AssignmentAlgorithm.GREEDY may be better in the case 'blob_sizes' is
not provided.
'''
# Sort the ranges based on when they are last used.
# If LiveRange.used is None, then the blob is never used and could
# be consumed externally. Sort these to the end of the list as opposed
# to the beginning so that they can be shared as well.
ranges = sorted(
viewitems(ranges),
key=lambda p: (p[1].used is None, p[1].used),
)
# Update None values
ranges = get_updated_ranges(ranges)
# Sharable blobs
ranges_sharable = [x for x in ranges if x[0] not in static_blobs]
# Static blobs, not sharable
ranges_static = [x for x in ranges if x[0] in static_blobs]
log.info("Total sharable blobs {}".format(len(ranges_sharable)))
best_assignment = []
if algo == AssignmentAlgorithm.DYNAMIC_PROGRAMMING:
best_assignment = compute_assignments_dp(ranges_sharable, [])
elif algo == AssignmentAlgorithm.GREEDY:
best_assignment = compute_assignments_greedy(ranges_sharable, [])
else:
assert "Invalid algo name {}".format(algo)
best_assignment += [[x] for x in ranges_static]
# verify_assignments(best_assignment)
return best_assignment
def verify_assignments(assignments):
for cur in assignments:
for x, y in zip(cur[0:-1], cur[1:]):
assert x[1].used < y[1].defined
def compute_interference_graph(ops):
g = nx.DiGraph()
for i, op in enumerate(ops):
g.add_node(i, op=op)
for i, parent_op in enumerate(ops):
for j, child_op in enumerate(ops):
if i >= j:
continue
if any(output in child_op.input for output in parent_op.output):
deps = set(child_op.input).intersection(parent_op.output)
g.add_edge(i, j, deps=deps)
assert nx.is_directed_acyclic_graph(g), child_op
return g
Optimization = collections.namedtuple(
'Optimization', ['net', 'assignments', 'blob_assignments'])
def apply_assignments(net, blob_assignments):
def canonical_name(blob):
if blob not in blob_assignments:
return blob
return blob_assignments[blob]
for op in net.op:
# Descend into subnets of the recurrent network
if op.type.startswith('RecurrentNetwork'):
apply_recurrent_blob_assignments(op, blob_assignments, canonical_name)
for i, input_ in enumerate(op.input):
op.input[i] = canonical_name(input_)
for i, output in enumerate(op.output):
op.output[i] = canonical_name(output)
def apply_recurrent_blob_assignments(op, blob_assignments, canonical_name):
log.debug("Applying assignments to recurrent op: {}".format(op.type))
step_args = [a for a in op.arg if a.name.endswith("step_net")]
for step_arg in step_args:
apply_assignments(step_arg.n, blob_assignments)
for i, einp in enumerate(step_arg.n.external_input):
if einp in blob_assignments:
step_arg.n.external_input[i] = canonical_name(einp)
# Store renamings
for blob, renamed in viewitems(blob_assignments):
if blob in list(op.input) + list(op.output):
a = caffe2_pb2.Argument()
a.name = blob + ".rename"
a.s = str(renamed).encode("ascii")
op.arg.extend([a])
class AssignmentAlgorithm(enum.Enum):
GREEDY = 0
DYNAMIC_PROGRAMMING = 1
def optimize_inference_fast(net, static_blobs):
optim = caffe2_pb2.NetDef()
optim_str = C.memonger_optimize_inference_net(
net.SerializeToString(),
[str(s).encode('utf-8') for s in static_blobs]
)
optim.ParseFromString(optim_str)
return optim
def optimize_interference(net, static_blobs,
ordering_function=topological_sort_traversal,
blob_sizes=None,
algo=AssignmentAlgorithm.GREEDY):
"""
ordering_function: topological_sort_traversal or
topological_sort_traversal_longest_path.
topological_sort_traversal_longest_path gives better
results but needs a bit more computation.
algo: Method used to find assignments (AssignmentAlgorithm.GREEDY or
AssignmentAlgorithm.DYNAMIC_PROGRAMMING).
AssignmentAlgorithm.DYNAMIC_PROGRAMMING gives optimal solution at the
cost of more computation.
AssignmentAlgorithm.GREEDY may be better in the case 'blob_sizes' is
not provided.
"""
"""
1) Use a BFS traversal of the execution graph to generate an
ordering of the node executions.
2) Generate use-def ranges for each `blob` in the BFS traversal
order.
3) Assign blobs to `canonical blobs`
4) Rename blobs to canonical blobs
"""
net = copy.deepcopy(net)
g = compute_interference_graph(net.op)
ordering = ordering_function(g)
linearized_ops = [net.op[i] for i in ordering]
# Reorder ops in net based on the computed linearlized order.
# If the graph has multiple topological orderings and if the NetDef's
# ordering differs from the order used to compute ranges, then the
# runtime might end up overwriting blobs before they are used.
del net.op[:]
net.op.extend(linearized_ops)
ranges = compute_ranges(linearized_ops, blob_sizes)
assignments = compute_assignments(ranges, static_blobs, algo)
blob_assignments = compute_blob_assignments(assignments)
apply_assignments(net, blob_assignments)
return Optimization(
net=net,
blob_assignments=blob_assignments,
assignments=assignments)
def verify_inplace_blobs(net_a, net_b):
"""
Verifies that net_a and net_b have the same in-place blob assignments.
Particularly, that memonger did not add an in-place assignment when that
did not exist before.
"""
def get_inplaces(op):
out = list(op.output)
inplaces = []
for j, inp in enumerate(op.input):
if inp in out:
inplaces.append([j, out.index(inp)])
return inplaces
for op_a, op_b in zip(net_a.op, net_b.op):
if op_a.type != op_b.type:
return False
if get_inplaces(op_a) != get_inplaces(op_b):
return False
return True
def verify_graph_equality(net_a, net_b):
"""
Determines if the execution of two graphs are identical.
That is, all inputs blobs are mapped to the same output blobs
for each operator in their respective positions.
This is meant to check the output of memonger with the original graph.
It assumes that the nets have same external input and output.
O(E) runtime + O(1) amortized cost to hash for python dict
"""
def parent_list(ops):
parent_list = [[] for _ in ops]
edge_owner = {}
for i, op in enumerate(ops):
for blob in op.input:
parent_id = edge_owner.get(blob)
if parent_id is not None:
parent_list[i].append(parent_id)
for blob in op.output:
edge_owner[blob] = i
return parent_list
# Operator wise equality checks
if (len(net_a.op) != len(net_b.op)):
return False
for op_a, op_b in zip(net_a.op, net_b.op):
if (op_a.type != op_b.type or
op_a.device_option != op_b.device_option or
op_a.engine != op_b.engine):
return False
# Print debug info
parent_list_a = parent_list(net_a.op)
parent_list_b = parent_list(net_b.op)
if parent_list_a != parent_list_b:
j = 0
for a, b in zip(parent_list_a, parent_list_b):
if a != b:
print("Difference {} vs {} \n {}".format(
j, net_a.op[j], net_b.op[j]))
print("Parents: {} vs {}".format(a, b))
j += 1
# Net wise equality check
return parent_list_a == parent_list_b
Statistics = collections.namedtuple(
'Statistics', ['baseline_nbytes', 'optimized_nbytes'])
def blob_nbytes(blob):
sz = 0
try:
sz = workspace.FetchBlob(blob).nbytes
except Exception:
log.warning('Error when fetching blob {}'.format(blob))
return sz
def compute_statistics(assignments):
blob_bytes = {
blob: blob_nbytes(blob) for assignment in assignments
for (blob, _) in assignment}
baseline_nbytes = sum(viewvalues(blob_bytes))
optimized_nbytes = sum(
max(blob_bytes[blob] for (blob, _) in assignment)
for assignment in assignments)
return Statistics(
baseline_nbytes=baseline_nbytes,
optimized_nbytes=optimized_nbytes)
def collect_blob_sizes(net):
blobs = {}
for op in net.op:
for blob in op.input:
blobs[blob] = blob_nbytes(blob)
for blob in op.output:
blobs[blob] = blob_nbytes(blob)
return blobs
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from caffe2.python import schema
from caffe2.python.regularizer_context import UseRegularizer, RegularizerContext
from caffe2.python.regularizer import L1Norm
from caffe2.python.optimizer import SgdOptimizer
from caffe2.python.layer_test_util import LayersTestCase
from caffe2.python import layer_model_instantiator
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import numpy as np
class TestRegularizerContext(LayersTestCase):
@given(
X=hu.arrays(dims=[2, 5]),
)
def test_regularizer_context(self, X):
weight_reg_out = L1Norm(0.2)
bias_reg_out = L1Norm(0)
regularizers = {
'WEIGHT': weight_reg_out,
'BIAS': bias_reg_out
}
output_dims = 2
input_record = self.new_record(schema.Scalar((np.float32, (5,))))
schema.FeedRecord(input_record, [X])
with UseRegularizer(regularizers):
weight_reg = RegularizerContext.current().get_regularizer('WEIGHT')
bias_reg = RegularizerContext.current().get_regularizer('BIAS')
optim = SgdOptimizer(0.15)
assert weight_reg == weight_reg_out, \
'fail to get correct weight reg from context'
assert bias_reg == bias_reg_out, \
'fail to get correct bias reg from context'
fc_output = self.model.FC(
input_record,
output_dims,
weight_optim=optim,
bias_optim=optim,
weight_reg=weight_reg,
bias_reg=bias_reg
)
# model.output_schema has to a struct
self.model.output_schema = schema.Struct((
'fc_output', fc_output
))
self.assertEqual(
schema.Scalar((np.float32, (output_dims, ))),
fc_output
)
_, train_net = layer_model_instantiator.generate_training_nets(self.model)
ops = train_net.Proto().op
ops_type_list = [ops[i].type for i in range(len(ops))]
assert ops_type_list.count('LpNorm') == 2
assert ops_type_list.count('Scale') == 4
assert ops_type_list.count('LpNormGradient') == 2
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from caffe2.python import workspace, core
import caffe2.python.parallel_workers as parallel_workers
def create_queue():
queue = 'queue'
workspace.RunOperatorOnce(
core.CreateOperator(
"CreateBlobsQueue", [], [queue], num_blobs=1, capacity=1000
)
)
return queue
def create_worker(queue, get_blob_data):
def dummy_worker(worker_id):
blob = 'blob_' + str(worker_id)
workspace.FeedBlob(blob, get_blob_data(worker_id))
workspace.RunOperatorOnce(
core.CreateOperator(
'SafeEnqueueBlobs', [queue, blob], [blob, 'status_blob']
)
)
return dummy_worker
def dequeue_value(queue):
dequeue_blob = 'dequeue_blob'
workspace.RunOperatorOnce(
core.CreateOperator(
"SafeDequeueBlobs", [queue], [dequeue_blob, 'status_blob']
)
)
return workspace.FetchBlob(dequeue_blob)
class ParallelWorkersTest(unittest.TestCase):
def testParallelWorkers(self):
workspace.ResetWorkspace()
queue = create_queue()
dummy_worker = create_worker(queue, lambda worker_id: str(worker_id))
worker_coordinator = parallel_workers.init_workers(dummy_worker)
worker_coordinator.start()
for _ in range(10):
value = dequeue_value(queue)
self.assertTrue(
value in [b'0', b'1'], 'Got unexpected value ' + str(value)
)
self.assertTrue(worker_coordinator.stop())
def testParallelWorkersInitFun(self):
workspace.ResetWorkspace()
queue = create_queue()
dummy_worker = create_worker(
queue, lambda worker_id: workspace.FetchBlob('data')
)
workspace.FeedBlob('data', 'not initialized')
def init_fun(worker_coordinator, global_coordinator):
workspace.FeedBlob('data', 'initialized')
worker_coordinator = parallel_workers.init_workers(
dummy_worker, init_fun=init_fun
)
worker_coordinator.start()
for _ in range(10):
value = dequeue_value(queue)
self.assertEqual(
value, b'initialized', 'Got unexpected value ' + str(value)
)
self.assertTrue(worker_coordinator.stop())
def testParallelWorkersShutdownFun(self):
workspace.ResetWorkspace()
queue = create_queue()
dummy_worker = create_worker(queue, lambda worker_id: str(worker_id))
workspace.FeedBlob('data', 'not shutdown')
def shutdown_fun():
workspace.FeedBlob('data', 'shutdown')
worker_coordinator = parallel_workers.init_workers(
dummy_worker, shutdown_fun=shutdown_fun
)
worker_coordinator.start()
self.assertTrue(worker_coordinator.stop())
data = workspace.FetchBlob('data')
self.assertEqual(data, b'shutdown', 'Got unexpected value ' + str(data))
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import brew, core, scope, workspace
from caffe2.python.modeling.parameter_info import ParameterTags
from caffe2.python.model_helper import ModelHelper
from caffe2.python.cnn import CNNModelHelper
import unittest
import numpy as np
class BrewTest(unittest.TestCase):
def setUp(self):
def myhelper(model, val=-1):
return val
if not brew.has_helper(myhelper):
brew.Register(myhelper)
self.myhelper = myhelper
def myhelper2(model, val=-1):
return val
if not brew.has_helper(myhelper2):
brew.Register(myhelper2)
self.myhelper2 = myhelper2
self.model = ModelHelper(name="test_model")
def test_dropout(self):
p = 0.2
X = np.ones((100, 100)).astype(np.float32) - p
workspace.FeedBlob("x", X)
model = ModelHelper(name="test_model")
brew.dropout(model, "x", "out", is_test=False)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
out = workspace.FetchBlob("out")
self.assertLess(abs(out.mean() - (1 - p)), 0.05)
def test_fc(self):
m, n, k = (15, 15, 15)
X = np.random.rand(m, k).astype(np.float32) - 0.5
workspace.FeedBlob("x", X)
model = ModelHelper(name="test_model")
brew.fc(model, "x", "out_1", k, n)
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
def test_relu(self):
Xpos = np.ones((5, 5)).astype(np.float32) - 0.5
Xneg = np.ones((5, 5)).astype(np.float32) - 1.5
workspace.FeedBlob("xpos", Xpos)
workspace.FeedBlob("xneg", Xneg)
model = ModelHelper(name="test_model")
brew.relu(model, "xpos", "out_xpos")
brew.relu(model, "xneg", "out_xneg")
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
pos = workspace.FetchBlob("out_xpos")
self.assertAlmostEqual(pos.mean(), 0.5)
neg = workspace.FetchBlob("out_xneg")
self.assertAlmostEqual(neg.mean(), 0)
def test_tanh(self):
X = np.ones((5, 5)).astype(np.float32) - 0.5
workspace.FeedBlob("x", X)
model = ModelHelper(name="test_model")
brew.tanh(model, "x", "out_tanh")
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
out = workspace.FetchBlob("out_tanh")
self.assertAlmostEqual(out.mean(), 0.46211711)
def test_validate(self):
model = ModelHelper(name="test_model")
model.params.append("aaa")
model.params.append("bbb")
self.assertEqual(model._Validate(), [])
model.params.append("xxx")
model.params.append("bbb")
self.assertEqual(model._Validate(), ["bbb"])
def test_arg_scope(self):
myhelper = self.myhelper
myhelper2 = self.myhelper2
n = 15
with brew.arg_scope([myhelper], val=n):
res = brew.myhelper(self.model)
self.assertEqual(n, res)
with brew.arg_scope([myhelper, myhelper2], val=n):
res1 = brew.myhelper(self.model)
res2 = brew.myhelper2(self.model)
self.assertEqual([n, n], [res1, res2])
def test_arg_scope_single(self):
X = np.random.rand(64, 3, 32, 32).astype(np.float32) - 0.5
workspace.FeedBlob("x", X)
model = ModelHelper(name="test_model")
with brew.arg_scope(
brew.conv,
stride=2,
pad=2,
weight_init=('XavierFill', {}),
bias_init=('ConstantFill', {})
):
brew.conv(
model=model,
blob_in="x",
blob_out="out",
dim_in=3,
dim_out=64,
kernel=3,
)
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
out = workspace.FetchBlob("out")
self.assertEqual(out.shape, (64, 64, 17, 17))
def test_arg_scope_nested(self):
myhelper = self.myhelper
n = 16
with brew.arg_scope([myhelper], val=-3), \
brew.arg_scope([myhelper], val=-2):
with brew.arg_scope([myhelper], val=n):
res = brew.myhelper(self.model)
self.assertEqual(n, res)
res = brew.myhelper(self.model)
self.assertEqual(res, -2)
res = brew.myhelper(self.model, val=15)
self.model.Validate()
self.assertEqual(res, 15)
def test_double_register(self):
myhelper = self.myhelper
with self.assertRaises(AttributeError):
brew.Register(myhelper)
def test_has_helper(self):
self.assertTrue(brew.has_helper(brew.conv))
self.assertTrue(brew.has_helper("conv"))
def myhelper3():
pass
self.assertFalse(brew.has_helper(myhelper3))
def test_model_helper(self):
X = np.random.rand(64, 32, 32, 3).astype(np.float32) - 0.5
workspace.FeedBlob("x", X)
my_arg_scope = {'order': 'NHWC'}
model = ModelHelper(name="test_model", arg_scope=my_arg_scope)
with brew.arg_scope(
brew.conv,
stride=2,
pad=2,
weight_init=('XavierFill', {}),
bias_init=('ConstantFill', {})
):
brew.conv(
model=model,
blob_in="x",
blob_out="out",
dim_in=3,
dim_out=64,
kernel=[8, 3]
)
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
out = workspace.FetchBlob("out")
self.assertEqual(out.shape, (64, 15, 17, 64))
def test_cnn_model_helper_deprecated(self):
X = np.random.rand(64, 32, 32, 3).astype(np.float32) - 0.5
workspace.FeedBlob("x", X)
# CNNModelHelper is going to be deprecated soon. This test is only
# covering some CNNModelHelper logic
model = CNNModelHelper(name="test_model", order='NHWC')
self.assertEqual(model.arg_scope['order'], 'NHWC')
def test_get_params(self):
def param(x):
return core.ScopedBlobReference(x)
def to_str_list(x):
return sorted([str(p) for p in x])
model = ModelHelper(name="test_model")
model.AddParameter(param("a"))
model.AddParameter(param("b"), tags=ParameterTags.COMPUTED_PARAM)
with scope.NameScope("c"):
model.AddParameter(param("a"))
model.AddParameter(param("d"), tags=ParameterTags.COMPUTED_PARAM)
self.assertEqual(to_str_list(model.GetParams()), ['c/a'])
self.assertEqual(to_str_list(model.GetComputedParams()), ['c/d'])
self.assertEqual(to_str_list(model.GetAllParams()), ['c/a', 'c/d'])
# Get AllParams from the global Scope
self.assertEqual(to_str_list(model.GetAllParams('')), [
'a', 'b', 'c/a', 'c/d'])
self.assertEqual(to_str_list(model.GetParams()), ['a', 'c/a'])
self.assertEqual(to_str_list(model.GetComputedParams()), ['b', 'c/d'])
self.assertEqual(to_str_list(model.GetAllParams()),
['a', 'b', 'c/a', 'c/d'])
self.assertEqual(to_str_list(model.GetAllParams('')),
['a', 'b', 'c/a', 'c/d'])
# Get AllParams from the scope 'c'
self.assertEqual(to_str_list(model.GetAllParams('c')), ['c/a', 'c/d'])
self.assertEqual(to_str_list(model.GetAllParams('c/')), ['c/a', 'c/d'])
def test_param_consistence(self):
model = ModelHelper(name='test_mode')
cnv = brew.conv(model, 'data', 'cnv', 32, 32, 4)
step_model = ModelHelper(name='step_model', param_model=model)
a = brew.fc(step_model, cnv, 'a', 100, 200)
brew.fc(model, a, 'b', 200, 5)
# test the _parameters_info is shared between model and step_model
self.assertEqual(model._parameters_info, step_model._parameters_info)
def test_cond(self):
workspace.FeedBlob("cond", np.array(True))
workspace.FeedBlob("then_value", np.array(1))
workspace.FeedBlob("else_value", np.array(2))
then_model = ModelHelper(name="then_test_model")
then_model.net.Copy("then_value", "output_blob")
else_model = ModelHelper(name="else_test_model")
else_model.net.Copy("else_value", "output_blob")
model = ModelHelper(name="test_model")
brew.cond(
model=model,
cond_blob="cond",
external_blobs=["then_value", "else_value", "output_blob"],
then_model=then_model,
else_model=else_model)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
output_value = workspace.FetchBlob("output_blob")
self.assertEqual(output_value, 1)
workspace.FeedBlob("cond", np.array(False))
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
output_value = workspace.FetchBlob("output_blob")
self.assertEqual(output_value, 2)
def test_loop(self):
workspace.FeedBlob("cond", np.array(True))
workspace.FeedBlob("ONE", np.array(1))
workspace.FeedBlob("TWO", np.array(2))
workspace.FeedBlob("TEN", np.array(10))
workspace.FeedBlob("counter", np.array(0))
workspace.FeedBlob("output_blob", np.array(0))
loop_model = ModelHelper(name="loop_test_model")
loop_model.net.Add(["output_blob", "TWO"], "output_blob")
cond_model = ModelHelper(name="cond_test_model")
cond_model.net.Add(["counter", "ONE"], "counter")
comp_res = cond_model.net.LT(["counter", "TEN"])
cond_model.net.Copy(comp_res, "cond")
model = ModelHelper(name="test_model")
brew.loop(
model=model,
cond_blob="cond",
external_blobs=["cond", "ONE", "TWO", "TEN", "counter", "output_blob"],
loop_model=loop_model,
cond_model=cond_model)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
output_value = workspace.FetchBlob("output_blob")
self.assertEqual(output_value, 18)
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support.")
class BrewGPUTest(unittest.TestCase):
def test_relu(self):
Xpos = np.ones((5, 5)).astype(np.float32) - 0.5
Xneg = np.ones((5, 5)).astype(np.float32) - 1.5
workspace.FeedBlob("xpos", Xpos)
workspace.FeedBlob("xneg", Xneg)
model = ModelHelper(name="test_model")
brew.relu(model, "xpos", "out_xpos", use_cudnn=True)
brew.relu(model, "xneg", "out_xneg", use_cudnn=True)
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
pos = workspace.FetchBlob("out_xpos")
self.assertAlmostEqual(pos.mean(), 0.5)
neg = workspace.FetchBlob("out_xneg")
self.assertAlmostEqual(neg.mean(), 0)
def test_tanh(self):
X = np.ones((5, 5)).astype(np.float32) - 0.5
workspace.FeedBlob("x", X)
model = ModelHelper(name="test_model")
brew.tanh(model, "x", "out_tanh", use_cudnn=True)
model.Validate()
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
out = workspace.FetchBlob("out_tanh")
self.assertAlmostEqual(out.mean(), 0.46211711)
|
## @package layer_test_util
# Module caffe2.python.layer_test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
from caffe2.python import (
core,
layer_model_instantiator,
layer_model_helper,
schema,
test_util,
workspace,
utils,
)
from caffe2.proto import caffe2_pb2
import numpy as np
class OpSpec(namedtuple("OpSpec", "type input output arg")):
def __new__(cls, op_type, op_input, op_output, op_arg=None):
return super(OpSpec, cls).__new__(cls, op_type, op_input,
op_output, op_arg)
class LayersTestCase(test_util.TestCase):
def setUp(self):
super(LayersTestCase, self).setUp()
self.setup_example()
def setup_example(self):
"""
This is undocumented feature in hypothesis,
https://github.com/HypothesisWorks/hypothesis-python/issues/59
"""
workspace.ResetWorkspace()
self.reset_model()
def reset_model(self, input_feature_schema=None, trainer_extra_schema=None):
input_feature_schema = input_feature_schema or schema.Struct(
('float_features', schema.Scalar((np.float32, (32,)))),
)
trainer_extra_schema = trainer_extra_schema or schema.Struct()
self.model = layer_model_helper.LayerModelHelper(
'test_model',
input_feature_schema=input_feature_schema,
trainer_extra_schema=trainer_extra_schema)
def new_record(self, schema_obj):
return schema.NewRecord(self.model.net, schema_obj)
def get_training_nets(self, add_constants=False):
"""
We don't use
layer_model_instantiator.generate_training_nets_forward_only()
here because it includes initialization of global constants, which make
testing tricky
"""
train_net = core.Net('train_net')
if add_constants:
train_init_net = self.model.create_init_net('train_init_net')
else:
train_init_net = core.Net('train_init_net')
for layer in self.model.layers:
layer.add_operators(train_net, train_init_net)
return train_init_net, train_net
def get_eval_net(self):
return layer_model_instantiator.generate_eval_net(self.model)
def get_predict_net(self):
return layer_model_instantiator.generate_predict_net(self.model)
def run_train_net(self):
self.model.output_schema = schema.Struct()
train_init_net, train_net = \
layer_model_instantiator.generate_training_nets(self.model)
workspace.RunNetOnce(train_init_net)
workspace.RunNetOnce(train_net)
def run_train_net_forward_only(self, num_iter=1):
self.model.output_schema = schema.Struct()
train_init_net, train_net = \
layer_model_instantiator.generate_training_nets_forward_only(
self.model)
workspace.RunNetOnce(train_init_net)
assert num_iter > 0, 'num_iter must be larger than 0'
workspace.CreateNet(train_net)
workspace.RunNet(train_net.Proto().name, num_iter=num_iter)
def assertBlobsEqual(self, spec_blobs, op_blobs):
"""
spec_blobs can either be None or a list of blob names. If it's None,
then no assertion is performed. The elements of the list can be None,
in that case, it means that position will not be checked.
"""
if spec_blobs is None:
return
self.assertEqual(len(spec_blobs), len(op_blobs))
for spec_blob, op_blob in zip(spec_blobs, op_blobs):
if spec_blob is None:
continue
self.assertEqual(spec_blob, op_blob)
def assertArgsEqual(self, spec_args, op_args):
self.assertEqual(len(spec_args), len(op_args))
keys = [a.name for a in op_args]
def parse_args(args):
operator = caffe2_pb2.OperatorDef()
# Generate the expected value in the same order
for k in keys:
v = args[k]
arg = utils.MakeArgument(k, v)
operator.arg.add().CopyFrom(arg)
return operator.arg
self.assertEqual(parse_args(spec_args), op_args)
def assertNetContainOps(self, net, op_specs):
"""
Given a net and a list of OpSpec's, check that the net match the spec
"""
ops = net.Proto().op
self.assertEqual(len(op_specs), len(ops))
for op, op_spec in zip(ops, op_specs):
self.assertEqual(op_spec.type, op.type)
self.assertBlobsEqual(op_spec.input, op.input)
self.assertBlobsEqual(op_spec.output, op.output)
if op_spec.arg is not None:
self.assertArgsEqual(op_spec.arg, op.arg)
return ops
|
import numpy as np
import unittest
from caffe2.proto import caffe2_pb2
from caffe2.python import (
workspace,
device_checker,
test_util,
model_helper,
brew,
)
class TestMiniAlexNet(test_util.TestCase):
def _MiniAlexNetNoDropout(self, order):
# First, AlexNet using the cnn wrapper.
model = model_helper.ModelHelper(name="alexnet")
conv1 = brew.conv(
model,
"data",
"conv1",
3,
16,
11,
("XavierFill", {}),
("ConstantFill", {}),
stride=4,
pad=0
)
relu1 = brew.relu(model, conv1, "relu1")
norm1 = brew.lrn(model, relu1, "norm1", size=5, alpha=0.0001, beta=0.75)
pool1 = brew.max_pool(model, norm1, "pool1", kernel=3, stride=2)
conv2 = brew.group_conv(
model,
pool1,
"conv2",
16,
32,
5,
("XavierFill", {}),
("ConstantFill", {"value": 0.1}),
group=2,
stride=1,
pad=2
)
relu2 = brew.relu(model, conv2, "relu2")
norm2 = brew.lrn(model, relu2, "norm2", size=5, alpha=0.0001, beta=0.75)
pool2 = brew.max_pool(model, norm2, "pool2", kernel=3, stride=2)
conv3 = brew.conv(
model,
pool2,
"conv3",
32,
64,
3,
("XavierFill", {'std': 0.01}),
("ConstantFill", {}),
pad=1
)
relu3 = brew.relu(model, conv3, "relu3")
conv4 = brew.group_conv(
model,
relu3,
"conv4",
64,
64,
3,
("XavierFill", {}),
("ConstantFill", {"value": 0.1}),
group=2,
pad=1
)
relu4 = brew.relu(model, conv4, "relu4")
conv5 = brew.group_conv(
model,
relu4,
"conv5",
64,
32,
3,
("XavierFill", {}),
("ConstantFill", {"value": 0.1}),
group=2,
pad=1
)
relu5 = brew.relu(model, conv5, "relu5")
pool5 = brew.max_pool(model, relu5, "pool5", kernel=3, stride=2)
fc6 = brew.fc(
model, pool5, "fc6", 1152, 1024, ("XavierFill", {}),
("ConstantFill", {"value": 0.1})
)
relu6 = brew.relu(model, fc6, "relu6")
fc7 = brew.fc(
model, relu6, "fc7", 1024, 1024, ("XavierFill", {}),
("ConstantFill", {"value": 0.1})
)
relu7 = brew.relu(model, fc7, "relu7")
fc8 = brew.fc(
model, relu7, "fc8", 1024, 5, ("XavierFill", {}),
("ConstantFill", {"value": 0.0})
)
pred = brew.softmax(model, fc8, "pred")
xent = model.LabelCrossEntropy([pred, "label"], "xent")
loss = model.AveragedLoss([xent], ["loss"])
model.AddGradientOperators([loss])
return model
def _testMiniAlexNet(self, order):
# First, we get all the random initialization of parameters.
model = self._MiniAlexNetNoDropout(order)
workspace.ResetWorkspace()
workspace.RunNetOnce(model.param_init_net)
inputs = dict(
[(str(name), workspace.FetchBlob(str(name))) for name in
model.params]
)
if order == "NCHW":
inputs["data"] = np.random.rand(4, 3, 227, 227).astype(np.float32)
else:
inputs["data"] = np.random.rand(4, 227, 227, 3).astype(np.float32)
inputs["label"] = np.array([1, 2, 3, 4]).astype(np.int32)
cpu_device = caffe2_pb2.DeviceOption()
cpu_device.device_type = caffe2_pb2.CPU
gpu_device = caffe2_pb2.DeviceOption()
gpu_device.device_type = caffe2_pb2.CUDA
checker = device_checker.DeviceChecker(0.05, [cpu_device, gpu_device])
ret = checker.CheckNet(
model.net.Proto(),
inputs,
# The indices sometimes may be sensitive to small numerical
# differences in the input, so we ignore checking them.
ignore=['_pool1_idx', '_pool2_idx', '_pool5_idx']
)
self.assertEqual(ret, True)
@unittest.skipIf(not workspace.has_gpu_support,
"No GPU support. Skipping test.")
def testMiniAlexNetNCHW(self):
self._testMiniAlexNet("NCHW")
# No Group convolution support for NHWC right now
#@unittest.skipIf(not workspace.has_gpu_support,
# "No GPU support. Skipping test.")
#def testMiniAlexNetNHWC(self):
# self._testMiniAlexNet("NHWC")
if __name__ == '__main__':
unittest.main()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import net_printer
from caffe2.python.checkpoint import Job
from caffe2.python.net_builder import ops
from caffe2.python.task import Task, final_output, WorkspaceType
import unittest
def example_loop():
with Task():
total = ops.Const(0)
total_large = ops.Const(0)
total_small = ops.Const(0)
total_tiny = ops.Const(0)
with ops.loop(10) as loop:
outer = ops.Mul([loop.iter(), ops.Const(10)])
with ops.loop(loop.iter()) as inner:
val = ops.Add([outer, inner.iter()])
with ops.If(ops.GE([val, ops.Const(80)])) as c:
ops.Add([total_large, val], [total_large])
with c.Elif(ops.GE([val, ops.Const(50)])) as c:
ops.Add([total_small, val], [total_small])
with c.Else():
ops.Add([total_tiny, val], [total_tiny])
ops.Add([total, val], total)
def example_task():
with Task():
with ops.task_init():
one = ops.Const(1)
two = ops.Add([one, one])
with ops.task_init():
three = ops.Const(3)
accum = ops.Add([two, three])
# here, accum should be 5
with ops.task_exit():
# here, accum should be 6, since this executes after lines below
seven_1 = ops.Add([accum, one])
six = ops.Add([accum, one])
ops.Add([accum, one], [accum])
seven_2 = ops.Add([accum, one])
o6 = final_output(six)
o7_1 = final_output(seven_1)
o7_2 = final_output(seven_2)
with Task(num_instances=2):
with ops.task_init():
one = ops.Const(1)
with ops.task_instance_init():
local = ops.Const(2)
ops.Add([one, local], [one])
ops.LogInfo('ble')
return o6, o7_1, o7_2
def example_job():
with Job() as job:
with job.init_group:
example_loop()
example_task()
return job
class TestNetPrinter(unittest.TestCase):
def test_print(self):
self.assertTrue(len(net_printer.to_string(example_job())) > 0)
def test_valid_job(self):
job = example_job()
with job:
with Task():
# distributed_ctx_init_* ignored by analyzer
ops.Add(['distributed_ctx_init_a', 'distributed_ctx_init_b'])
# net_printer.analyze(example_job())
print(net_printer.to_string(example_job()))
def test_undefined_blob(self):
job = example_job()
with job:
with Task():
ops.Add(['a', 'b'])
with self.assertRaises(AssertionError) as e:
net_printer.analyze(job)
self.assertEqual("Blob undefined: a", str(e.exception))
def test_multiple_definition(self):
job = example_job()
with job:
with Task(workspace_type=WorkspaceType.GLOBAL):
ops.Add([ops.Const(0), ops.Const(1)], 'out1')
with Task(workspace_type=WorkspaceType.GLOBAL):
ops.Add([ops.Const(2), ops.Const(3)], 'out1')
with self.assertRaises(AssertionError):
net_printer.analyze(job)
|
## @package dataio
# Module caffe2.python.dataio
"""
Defines the base interface for reading and writing operations.
Readers/Writers are objects that produce operations that read/write sequences
of data. Each operation reads or writes a list of BlobReferences.
Readers and Writers must be implemented such that read and write operations
are atomic and thread safe.
Examples of possible Readers and Writers:
QueueReader, QueueWriter,
DatasetReader, DatasetWriter,
See `dataset.py` for an example of implementation.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from caffe2.python.schema import Field, Struct, from_blob_list
import numpy as np
class Reader(object):
"""
Reader is an abstract class to be implemented in order to provide
operations capable of iterating through a dataset or stream of data.
A Reader must implement at least one operation, `read`, which
adds operations to a net that read the next batch of data. Readers can
optionally support the `reset` operation, which is useful when multiple
passes over the data are required.
"""
def __init__(self, schema=None):
if schema is not None:
assert isinstance(schema, Field)
self._schema = schema
def schema(self):
assert self._schema is not None, 'Schema not provided for this reader.'
return self._schema
def _set_schema(self, schema):
self._schema = schema
def setup_ex(self, init_net, finish_net):
"""Setup nets to run at task initialization and cleanup time.
Args:
global_init_net: A net invoked at task init time.
global_finish_net: A net invoked at task cleanup time.
"""
pass
def read_ex(self, local_init_net, local_finish_net):
read_net = core.Net('reader_body')
return ([read_net], ) + self.read(read_net)
def read_record_ex(self, local_init_net, local_finish_net):
nets, should_stop, fields = self.read_ex(
local_init_net, local_finish_net)
if self._schema:
fields = from_blob_list(self._schema, fields)
return nets, should_stop, fields
def read(self, read_net):
"""Append operations to read_net that will read a batch from the
underlying data soruce.
Operations added to `read_net` must be thread safe and atomic, that is,
it should be possible to clone `read_net` and run multiple instances of
it in parallel.
Args:
read_net: the net that will be appended with read operations
Returns:
A tuple (should_stop, fields), with:
should_stop: BlobReference pointing to a boolean scalar
blob that indicates whether the read operation
was succesfull or whether the end of data has
been reached.
fields: A tuple of BlobReference containing the latest batch
of data that was read.
"""
raise NotImplementedError('Readers must implement `read`.')
def reset(self, net):
"""Append operations to `net` that will reset the reader.
This can be used to read the data multiple times.
Not all readers support this operation.
"""
raise NotImplementedError('This reader cannot be resetted.')
def read_record(self, read_net):
should_stop, fields = self.read(read_net)
if self._schema:
fields = from_blob_list(self._schema, fields)
return should_stop, fields
def execution_step(self, reader_net_name=None, external_should_stop=None):
"""Create an execution step with a net containing read operators.
The execution step will contain a `stop_blob` that knows how to stop
the execution loop when end of data was reached.
E.g.:
read_step, fields = reader.execution_step()
consume_net = core.Net('consume')
consume_net.Print(fields[0], [])
p = core.Plan('reader')
p.AddStep(read_step.AddNet(consume_net))
core.RunPlan(p)
Args:
reader_net_name: (optional) the name of the reader_net to be
created. The execution step will
be named accordingly.
Returns:
A tuple (read_step, fields), with:
read_step: A newly created execution step containing a net with
read operations. The step will have `stop_blob` set,
in order to stop the loop on end of data.
fields: A tuple of BlobReference containing the latest batch
of data that was read.
"""
reader_net = core.Net(reader_net_name or 'reader')
should_stop, fields = self.read_record(reader_net)
if external_should_stop is not None:
should_stop = reader_net.Or([external_should_stop, should_stop])
read_step = core.execution_step(
'{}_step'.format(reader_net_name),
reader_net,
should_stop_blob=should_stop)
return (read_step, fields)
class Writer(object):
"""
Writer is an abstract class to be implemented in order to provide
operations capable of feeding a data stream or a dataset.
A Writer must implement 2 operations:
`write`, which adds operations to a net that write the write batch of
data, and `commit`, which adds operations to a net in order to indicate
that no more data will be written.
"""
_schema = None
def schema(self):
return self._schema
def write(self, writer_net, fields):
"""Add operations to `writer_net` that write the next batch of data.
Operations added to the net must be thread-safe and unique, that is:
multiple writers must be able to write to the dataset in parallel.
Args:
fields: a tuple of BlobReference containing the batch of data to
write.
"""
raise NotImplementedError('Writers must implement write.')
def write_record(self, writer_net, fields):
if isinstance(fields, Field):
self._schema = fields
fields = fields.field_blobs()
self.write(writer_net, fields)
def setup_ex(self, init_net, finish_net):
"""Experimental, don't use yet"""
self.commit(finish_net)
def write_ex(self, fields, local_init_net, local_finish_net, stop_blob):
"""Experimental extension to the interface. Don't use yet"""
write_net = core.Net('write_net')
self.write(write_net, fields)
return [write_net]
def write_record_ex(
self, fields, local_init_net, local_finish_net, stop_blob=None):
"""Experimental extension to the interface. Don't use yet."""
if isinstance(fields, Field):
self._schema = fields
fields = fields.field_blobs()
if stop_blob is None:
stop_blob = local_init_net.NextName("dequeue_status")
write_nets = self.write_ex(
fields, local_init_net, local_finish_net, stop_blob)
return (write_nets, stop_blob)
def commit(self, finish_net):
"""Add operations to `finish_net` that signal end of data.
This must be implemented by all Writers, but may be no-op for some
of them.
"""
pass
class ReaderBuilder(object):
""" Allow usage of a reader in distributed fashion. """
def schema(self):
raise NotImplementedError()
def setup(self, **kwargs):
"""
Optionally, perform one-time setup before calling new_reader().
Subclass should make sure this function is only called once.
"""
raise NotImplementedError()
def new_reader(self, **kwargs):
raise NotImplementedError()
class PipedReaderBuilder(ReaderBuilder):
"""ReaderBuilder that modifies underlying builder by calling `piper`
function on each new reader produced, and return the result of
the function. This way, it is possible to append data processing
pipelines that will be replicated for each reader that gets created.
E.g.:
PipedReaderBuilder(
ReaderBuilder(...),
lambda reader: pipe(reader, processor=my_proc))
"""
def __init__(self, builder, piper):
self._builder = builder
self._piper = piper
def schema(self):
return self._builder.schema()
def setup(self, **kwargs):
self._builder.setup(**kwargs)
def new_reader(self, **kwargs):
# Passing everything down since you could wrap a PipedReaderBuilder in
# another PipedReaderBuilder
output = self._piper(
reader=self._builder.new_reader(**kwargs),
**kwargs
)
return output if isinstance(output, Reader) else output.reader()
class Pipe(object):
def __init__(self, schema=None, obj_key=None):
self._num_writers = 0
self._num_readers = 0
self._schema = schema
self._obj_key = obj_key
def schema(self):
return self._schema
def setup(self, global_init_net):
pass
def reader(self):
raise NotImplementedError()
def writer(self):
raise NotImplementedError()
def num_readers(self):
return self._num_readers
def num_writers(self):
return self._num_writers
def _new_writer(self, writer_schema, writer_init_net):
if writer_schema is not None and self._schema is None:
self._schema = writer_schema
self._num_writers += 1
if self._obj_key is not None:
writer_init_net.add_attribute(self._obj_key, self)
def _new_reader(self, reader_init_net):
self._num_readers += 1
if self._obj_key is not None:
reader_init_net.add_attribute(self._obj_key, self)
class CounterReader(Reader):
""" Reader that produces increasing integers. """
def __init__(self):
Reader.__init__(self, schema=Struct(('iter', np.int64)))
self.counter = None
self.should_stop = None
def setup_ex(self, global_init_net, global_finish_net):
if self.counter is None:
self.counter = global_init_net.CreateCounter([], init_count=0)
self.should_stop = global_init_net.ConstantFill(
[], shape=[], dtype=core.DataType.BOOL, value=False)
def read_ex(self, local_init_net, local_finish_net):
count_net = core.Net('limited_reader_counter')
value = count_net.CountUp([self.counter], 1)
return [count_net], self.should_stop, [value]
class ReaderWithLimitBase(Reader):
"""Abstract Reader constrained by certain conditions.
Base class for Reader classes which check for certain conditions to stop
further processing (e.g. max number of iterations or time limit).
Also produces a boolean blob (data_finished) that can be used to see if
the reader exausted all input data (true) or stopped for another reason
(false).
"""
def __init__(self, reader):
Reader.__init__(self, schema=reader._schema)
self.reader = reader
self.net = core.Net('reader_with_limit')
self._data_finished = self.net.AddExternalInput(
self.net.NextName('data_finished'))
self.should_stop = None
def setup_ex(self, global_init_net, global_finish_net):
global_init_net.ConstantFill(
[], [self._data_finished],
shape=[], value=False, dtype=core.DataType.BOOL)
self.reader.setup_ex(global_init_net, global_finish_net)
self.setup_limiter(global_init_net, global_finish_net)
def read_ex(self, local_init_net, local_finish_net):
"""Reads from an underlying Reader class, but may stop due to additional
constraints.
Build and return network(s) to read data from a Reader with
additional constraints, depending on which derived class is used.
Derived classes implement setup_limited and check_limiter_condition
which determine the nature of the constraint imposed on the reader,
e.g. iteration limits or time limit.
Args:
local_init_net: A net invoked at task instance init time (Once per
parallel thread).
local_finish_net: A net invoked at task instance cleanup time (Once
per parallel thread).
"""
# Check if limiting constraint is met.
stop_condition_net = core.Net('limited_reader_condition')
should_stop = self.check_limiter_condition(stop_condition_net)
# Call original reader.
nets, local_data_finished, fields = self.reader.read_ex(
local_init_net, local_finish_net)
self._set_schema(self.reader._schema)
# Check if original reader is done.
check_done_net = core.Net('limited_reader_post')
# Copy to the same blob as the counter output to trigger reader
# stopping - this is ok because execution will check should_stop_blob
# after every single operation, so it has already been checked on this
# iteration by this point.
check_done_net.Copy(local_data_finished, should_stop)
# Update externally-accessible flag indicating if reader is done
check_done_net.Or([self._data_finished, local_data_finished],
[self._data_finished])
return [stop_condition_net] + nets + [check_done_net], should_stop, fields
def setup_limiter(self, global_init_net, global_finish_net):
"""Configure task level init/cleanup nets required to implement limit
condition. Must be implemented by subclass.
Args:
global_init_net: A net invoked at task init time.
global_finish_net: A net invoked at task cleanup time.
"""
raise NotImplementedError("Subclass must implement `setup_limiter`")
def check_limiter_condition(self, stop_condition_net):
"""Configure a net that is invoked between reading batches to see if
limit condition is met. Must be implemented by subclass.
Args:
stop_condition_net: A net invoked to evaluate an early termination
condition.
"""
raise NotImplementedError("Subclass must implement `check_limiter_condition")
def data_finished(self):
"""
Return a blob that can be checked after the end of the reading task,
which will contain a scalar float indicating whether the underlying
reader has been exhausted (True) or whether we stopped because reached
the limit of iterations (False).
"""
return self._data_finished
class ReaderWithLimit(ReaderWithLimitBase):
"""Reader that stops after `num_iter` batches.
If `num_iter` <= 0 or is None, reverts to an unconstrained reader that
exports a boolean blob indicating that the reader has exhausted
the data steam.
"""
def __init__(self, reader, num_iter=1):
"""Class initializer.
Args:
reader: The underlying reader object doing the actual read.
num_iter: Number of batches to read. If `None`,
the class reverts to a normal reader except that it also
produces a data_finished blob as a side effect to indicate
whether the input stream is exhausted.
"""
super(ReaderWithLimit, self).__init__(reader)
self.counter = None
self.num_iter = num_iter
if self.num_iter is not None:
self.counter = self.net.AddExternalInput(
self.net.NextName('counter'))
def setup_limiter(self, global_init_net, global_finish_net):
if self.counter:
global_init_net.CreateCounter(
[], [self.counter], init_count=int(self.num_iter))
def check_limiter_condition(self, stop_condition_net):
if self.counter:
return stop_condition_net.CountDown([self.counter], 1)
else:
return stop_condition_net.ConstantFill(
[], 1,
shape=[], value=False, dtype=core.DataType.BOOL)
def CountUntil(num_iter):
return ReaderWithLimit(CounterReader(), num_iter)
class ReaderWithTimeLimit(ReaderWithLimitBase):
"""Reader that stops after `duration` seconds.
If `duration` <= 0 or is None, reverts to an unconstrained reader that
exports a boolean blob indicating that the reader has exhausted
the data steam.
"""
def __init__(self, reader, duration=0):
"""Class initializer.
Args:
reader: The underlying reader object doing the actual read.
duration: Number of seconds to read. If un-specified, None, or <= 0,
the class reverts to a normal reader except that it also
produces a data_finished blob as a side effect to indicate
whether the input stream is exhausted.
"""
super(ReaderWithTimeLimit, self).__init__(reader)
self.timer = None
self.duration = duration
self.duration_ns_blob = None
def setup_limiter(self, global_init_net, global_finish_net):
if self.duration is not None and self.duration > 0:
duration_ns = int(self.duration * (10**9))
self.timer = global_init_net.TimerBegin(
[], counter_name='epoch_timer')
start_time = global_init_net.TimerGet(self.timer)
self.duration_ns_blob = global_init_net.ConstantFill(
[start_time], value=duration_ns)
global_finish_net.TimerEnd([self.timer], [])
def check_limiter_condition(self, stop_condition_net):
if self.duration:
time_elapsed = stop_condition_net.TimerGet(self.timer)
return stop_condition_net.GE(
[time_elapsed, self.duration_ns_blob], str(self.should_stop))
else:
return stop_condition_net.ConstantFill(
[], 1, shape=[], value=False, dtype=core.DataType.BOOL
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
import numpy as np
import unittest
import pickle
import random
class TestDB(unittest.TestCase):
def testPicklable(self):
s = schema.Struct(
('field1', schema.Scalar(dtype=np.int32)),
('field2', schema.List(schema.Scalar(dtype=str)))
)
s2 = pickle.loads(pickle.dumps(s))
for r in (s, s2):
self.assertTrue(isinstance(r.field1, schema.Scalar))
self.assertTrue(isinstance(r.field2, schema.List))
self.assertTrue(getattr(r, 'non_existent', None) is None)
def testNormalizeField(self):
s = schema.Struct(('field1', np.int32), ('field2', str))
self.assertEquals(
s,
schema.Struct(
('field1', schema.Scalar(dtype=np.int32)),
('field2', schema.Scalar(dtype=str))
)
)
def testTuple(self):
s = schema.Tuple(np.int32, str, np.float32)
s2 = schema.Struct(
('field_0', schema.Scalar(dtype=np.int32)),
('field_1', schema.Scalar(dtype=np.str)),
('field_2', schema.Scalar(dtype=np.float32))
)
self.assertEquals(s, s2)
self.assertEquals(s[0], schema.Scalar(dtype=np.int32))
self.assertEquals(s[1], schema.Scalar(dtype=np.str))
self.assertEquals(s[2], schema.Scalar(dtype=np.float32))
self.assertEquals(
s[2, 0],
schema.Struct(
('field_2', schema.Scalar(dtype=np.float32)),
('field_0', schema.Scalar(dtype=np.int32)),
)
)
# test iterator behavior
for i, (v1, v2) in enumerate(zip(s, s2)):
self.assertEquals(v1, v2)
self.assertEquals(s[i], v1)
self.assertEquals(s2[i], v1)
def testRawTuple(self):
s = schema.RawTuple(2)
self.assertEquals(
s, schema.Struct(
('field_0', schema.Scalar()), ('field_1', schema.Scalar())
)
)
self.assertEquals(s[0], schema.Scalar())
self.assertEquals(s[1], schema.Scalar())
def testStructIndexing(self):
s = schema.Struct(
('field1', schema.Scalar(dtype=np.int32)),
('field2', schema.List(schema.Scalar(dtype=str))),
('field3', schema.Struct()),
)
self.assertEquals(s['field2'], s.field2)
self.assertEquals(s['field2'], schema.List(schema.Scalar(dtype=str)))
self.assertEquals(s['field3'], schema.Struct())
self.assertEquals(
s['field2', 'field1'],
schema.Struct(
('field2', schema.List(schema.Scalar(dtype=str))),
('field1', schema.Scalar(dtype=np.int32)),
)
)
def testListInStructIndexing(self):
a = schema.List(schema.Scalar(dtype=str))
s = schema.Struct(
('field1', schema.Scalar(dtype=np.int32)),
('field2', a)
)
self.assertEquals(s['field2:lengths'], a.lengths)
self.assertEquals(s['field2:values'], a.items)
with self.assertRaises(KeyError):
s['fields2:items:non_existent']
with self.assertRaises(KeyError):
s['fields2:non_existent']
def testMapInStructIndexing(self):
a = schema.Map(
schema.Scalar(dtype=np.int32),
schema.Scalar(dtype=np.float32),
)
s = schema.Struct(
('field1', schema.Scalar(dtype=np.int32)),
('field2', a)
)
self.assertEquals(s['field2:values:keys'], a.keys)
self.assertEquals(s['field2:values:values'], a.values)
with self.assertRaises(KeyError):
s['fields2:keys:non_existent']
def testPreservesMetadata(self):
s = schema.Struct(
('a', schema.Scalar(np.float32)), (
'b', schema.Scalar(
np.int32,
metadata=schema.Metadata(categorical_limit=5)
)
), (
'c', schema.List(
schema.Scalar(
np.int32,
metadata=schema.Metadata(categorical_limit=6)
)
)
)
)
# attach metadata to lengths field
s.c.lengths.set_metadata(schema.Metadata(categorical_limit=7))
self.assertEqual(None, s.a.metadata)
self.assertEqual(5, s.b.metadata.categorical_limit)
self.assertEqual(6, s.c.value.metadata.categorical_limit)
self.assertEqual(7, s.c.lengths.metadata.categorical_limit)
sc = s.clone()
self.assertEqual(None, sc.a.metadata)
self.assertEqual(5, sc.b.metadata.categorical_limit)
self.assertEqual(6, sc.c.value.metadata.categorical_limit)
self.assertEqual(7, sc.c.lengths.metadata.categorical_limit)
sv = schema.from_blob_list(
s, [
np.array([3.4]), np.array([2]), np.array([3]),
np.array([1, 2, 3])
]
)
self.assertEqual(None, sv.a.metadata)
self.assertEqual(5, sv.b.metadata.categorical_limit)
self.assertEqual(6, sv.c.value.metadata.categorical_limit)
self.assertEqual(7, sv.c.lengths.metadata.categorical_limit)
def testDupField(self):
with self.assertRaises(ValueError):
schema.Struct(
('a', schema.Scalar()),
('a', schema.Scalar()))
def testAssignToField(self):
with self.assertRaises(TypeError):
s = schema.Struct(('a', schema.Scalar()))
s.a = schema.Scalar()
def testPreservesEmptyFields(self):
s = schema.Struct(
('a', schema.Scalar(np.float32)),
('b', schema.Struct()),
)
sc = s.clone()
self.assertIn("a", sc.fields)
self.assertIn("b", sc.fields)
sv = schema.from_blob_list(s, [np.array([3.4])])
self.assertIn("a", sv.fields)
self.assertIn("b", sv.fields)
self.assertEqual(0, len(sv.b.fields))
def testStructSubstraction(self):
s1 = schema.Struct(
('a', schema.Scalar()),
('b', schema.Scalar()),
('c', schema.Scalar()),
)
s2 = schema.Struct(
('b', schema.Scalar())
)
s = s1 - s2
self.assertEqual(['a', 'c'], s.field_names())
s3 = schema.Struct(
('a', schema.Scalar())
)
s = s1 - s3
self.assertEqual(['b', 'c'], s.field_names())
with self.assertRaises(TypeError):
s1 - schema.Scalar()
def testStructNestedSubstraction(self):
s1 = schema.Struct(
('a', schema.Scalar()),
('b', schema.Struct(
('c', schema.Scalar()),
('d', schema.Scalar()),
('e', schema.Scalar()),
('f', schema.Scalar()),
)),
)
s2 = schema.Struct(
('b', schema.Struct(
('d', schema.Scalar()),
('e', schema.Scalar()),
)),
)
s = s1 - s2
self.assertEqual(['a', 'b:c', 'b:f'], s.field_names())
def testStructAddition(self):
s1 = schema.Struct(
('a', schema.Scalar())
)
s2 = schema.Struct(
('b', schema.Scalar())
)
s = s1 + s2
self.assertIn("a", s.fields)
self.assertIn("b", s.fields)
with self.assertRaises(TypeError):
s1 + s1
with self.assertRaises(TypeError):
s1 + schema.Scalar()
def testStructNestedAddition(self):
s1 = schema.Struct(
('a', schema.Scalar()),
('b', schema.Struct(
('c', schema.Scalar())
)),
)
s2 = schema.Struct(
('b', schema.Struct(
('d', schema.Scalar())
))
)
s = s1 + s2
self.assertEqual(['a', 'b:c', 'b:d'], s.field_names())
s3 = schema.Struct(
('b', schema.Scalar()),
)
with self.assertRaises(TypeError):
s = s1 + s3
def testGetFieldByNestedName(self):
st = schema.Struct(
('a', schema.Scalar()),
('b', schema.Struct(
('c', schema.Struct(
('d', schema.Scalar()),
)),
)),
)
self.assertRaises(KeyError, st.__getitem__, '')
self.assertRaises(KeyError, st.__getitem__, 'x')
self.assertRaises(KeyError, st.__getitem__, 'x:y')
self.assertRaises(KeyError, st.__getitem__, 'b:c:x')
a = st['a']
self.assertTrue(isinstance(a, schema.Scalar))
bc = st['b:c']
self.assertIn('d', bc.fields)
bcd = st['b:c:d']
self.assertTrue(isinstance(bcd, schema.Scalar))
def testAddFieldByNestedName(self):
f_a = schema.Scalar(blob=core.BlobReference('blob1'))
f_b = schema.Struct(
('c', schema.Struct(
('d', schema.Scalar(blob=core.BlobReference('blob2'))),
)),
)
f_x = schema.Struct(
('x', schema.Scalar(blob=core.BlobReference('blob3'))),
)
with self.assertRaises(TypeError):
st = schema.Struct(
('a', f_a),
('b', f_b),
('b:c:d', f_x),
)
with self.assertRaises(TypeError):
st = schema.Struct(
('a', f_a),
('b', f_b),
('b:c:d:e', f_x),
)
st = schema.Struct(
('a', f_a),
('b', f_b),
('e:f', f_x),
)
self.assertEqual(['a', 'b:c:d', 'e:f:x'], st.field_names())
self.assertEqual(['blob1', 'blob2', 'blob3'], st.field_blobs())
st = schema.Struct(
('a', f_a),
('b:c:e', f_x),
('b', f_b),
)
self.assertEqual(['a', 'b:c:e:x', 'b:c:d'], st.field_names())
self.assertEqual(['blob1', 'blob3', 'blob2'], st.field_blobs())
st = schema.Struct(
('a:a1', f_a),
('b:b1', f_b),
('a', f_x),
)
self.assertEqual(['a:a1', 'a:x', 'b:b1:c:d'], st.field_names())
self.assertEqual(['blob1', 'blob3', 'blob2'], st.field_blobs())
def testContains(self):
st = schema.Struct(
('a', schema.Scalar()),
('b', schema.Struct(
('c', schema.Struct(
('d', schema.Scalar()),
)),
)),
)
self.assertTrue('a' in st)
self.assertTrue('b:c' in st)
self.assertTrue('b:c:d' in st)
self.assertFalse('' in st)
self.assertFalse('x' in st)
self.assertFalse('b:c:x' in st)
self.assertFalse('b:c:d:x' in st)
def testFromEmptyColumnList(self):
st = schema.Struct()
columns = st.field_names()
rec = schema.from_column_list(col_names=columns)
self.assertEqual(rec, schema.Struct())
def testFromColumnList(self):
st = schema.Struct(
('a', schema.Scalar()),
('b', schema.List(schema.Scalar())),
('c', schema.Map(schema.Scalar(), schema.Scalar()))
)
columns = st.field_names()
# test that recovery works for arbitrary order
for _ in range(10):
some_blobs = [core.BlobReference('blob:' + x) for x in columns]
rec = schema.from_column_list(columns, col_blobs=some_blobs)
self.assertTrue(rec.has_blobs())
self.assertEqual(sorted(st.field_names()), sorted(rec.field_names()))
self.assertEqual([str(blob) for blob in rec.field_blobs()],
[str('blob:' + name) for name in rec.field_names()])
random.shuffle(columns)
def testStructGet(self):
net = core.Net('test_net')
s1 = schema.NewRecord(net, schema.Scalar(np.float32))
s2 = schema.NewRecord(net, schema.Scalar(np.float32))
t = schema.Tuple(s1, s2)
assert t.get('field_0', None) == s1
assert t.get('field_1', None) == s2
assert t.get('field_2', None) is None
|
## @package checkpoint
# Module caffe2.python.checkpoint
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
from caffe2.python import core, context
from caffe2.python.net_builder import ops
from caffe2.python.task import Node, Task, TaskGroup, TaskOutput, WorkspaceType
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@context.define_context()
class Job(object):
"""
A Job defines three TaskGroups: the `init_group`, the `epoch_group` and the
`exit_group` which will be run by a JobRunner.
The `init_group` will be run only once at startup. Its role is to
initialize globally persistent blobs such as model weights, accumulators
and data file lists.
The `epoch_group` will be run in a loop after init_group. The loop will
exit when any of the stop signals added with `add_stop_signal` is True
at the end of an epoch.
The download_group will be run only once, after all the executions of
epoch_group finish. Its role is to collect the distribute scattered
parameters back after training.
The `exit_group` will be run only once at the very end of the job, the
role of this group is to save the results of training in the end of the job.
Jobs are context-driven, so that Tasks can be added to the active Job
without having to explicitly pass the job object around.
Example of usage:
def build_reader(partitions):
with Job.current().init_group:
reader = HiveReader(init_reader, ..., partitions)
Task(step=init_reader)
with Job.current().epoch_group:
limited_reader = ReaderWithLimit(reader, num_iter=10000)
data_queue = pipe(limited_reader, num_threads=8)
Job.current().add_stop_signal(limited_reader.data_finished())
return data_queue
def build_hogwild_trainer(reader, model):
with Job.current().init_group:
Task(step=model.param_init_net)
with Job.current().epoch_group:
pipe(reader, processor=model, num_threads=8)
with Job.current().exit_group:
Task(step=model.save_model_net)
with Job() as job:
reader = build_reader(partitions)
model = build_model(params)
build_hogwild_trainer(reader, model)
"""
def __init__(self,
init_group=None, epoch_group=None,
download_group=None, exit_group=None,
stop_signals=None, nodes_to_checkpoint=None):
self.init_group = init_group or TaskGroup(
workspace_type=WorkspaceType.GLOBAL)
self.epoch_group = epoch_group or TaskGroup()
self.download_group = download_group or TaskGroup()
self.exit_group = exit_group or TaskGroup()
self.stop_signals = stop_signals or []
self._nodes_to_checkpoint = nodes_to_checkpoint
def nodes_to_checkpoint(self):
if self._nodes_to_checkpoint:
return self._nodes_to_checkpoint
else:
return self.init_group.used_nodes()
def compile(self, session_class):
return Job(
init_group=session_class.compile(self.init_group),
epoch_group=session_class.compile(self.epoch_group),
download_group=session_class.compile(self.download_group),
exit_group=session_class.compile(self.exit_group),
stop_signals=self.stop_signals,
nodes_to_checkpoint=self.nodes_to_checkpoint())
def __enter__(self):
self.epoch_group.__enter__()
return self
def __exit__(self, *args):
self.epoch_group.__exit__()
def add_stop_signal(self, output):
if isinstance(output, core.BlobReference):
t = Task(outputs=[output], group=self.epoch_group)
output = t.outputs()[0]
assert isinstance(output, TaskOutput)
self.stop_signals.append(output)
def get_ckpt_filename(node_name, epoch):
"""Returns the checkpoint filename.
Args:
node_name: A string. The name of the node.
epoch: An integer. The checkpoint epoch.
Returns:
ckpt_filename: A string. The filename of the checkpoint.
"""
return node_name + '.' + str(epoch)
def db_name(epoch, node_name, db_prefix, path_prefix=None):
"""Returns the full db name where checkpoint files are saved.
Args:
epoch: An integer. The checkpoint epoch.
node_name: A string. The name of the node.
db_prefix: A string. The prefix used to construct full db name.
path_prefix: A string. Optional param used to construct db name or path
where checkpoint files are are stored.
Returns:
db_name: A string. The absolute path of full_db_name where checkpoint
files are saved
"""
if path_prefix:
db_name = path_prefix + get_ckpt_filename(node_name, epoch)
else:
ckpt_filename = get_ckpt_filename(node_name, epoch)
db_name = os.path.join(db_prefix, ckpt_filename)
return db_name
class CheckpointManager(object):
"""
Controls saving and loading of workspaces on every epoch boundary of a job.
If a CheckpointManager instance is passed to JobRunner, then JobRunner will
call `init`, `read` and `save` at different moments in between epoch runs.
Args:
db_prefix: The prefix used to construct full db name. Since `absolute_path`
is set to True, this will be used as db_name in SaveOp.
node_name: Name of the node where this checkpoint_manager is used.
db_type: Type of database to use for storing checkpoint.
metadata_handler: An optional object capable of reading/writing
checkpoint info in storage of choice.
"""
def __init__(self, db_prefix, node_name, db_type, metadata_handler=None):
self._db_prefix = db_prefix
self._node_name = node_name
self._db_type = db_type
self._metadata_handler = metadata_handler
# make sure these blobs are the first in the checkpoint file.
self._net = core.Net('!!checkpoint_mngr')
self._blob_names = self._net.AddExternalInput('blob_names')
self._names_output = None
self._path_prefix = None
self._path_type = None
"""
Initialize the checkpoint manager. Determines all blobs that need to be saved
or loads from a checkpoint.
Args:
nodes: An array of nodes where this checkpoint manager is running. Should
only contain a single node.
retrieve_from_epoch: Set to a number to load blobs from this epoch.
path_prefix: Used to construct db name or path where checkpoint files are
stored.
path_type: Indicate the type of path where checkpoint files are stored.
"""
def init(
self,
nodes=None,
retrieve_from_epoch=None,
path_prefix=None,
path_type=None
):
"""
Build a Task that will be run once after the job's `init_group` is run.
This task will determine which blobs need to be checkpointed.
If retrieve_from_epoch is not None, then the checkpoint metadata is
retrieved from a previously saved checkpoint.
"""
assert nodes is None or len(nodes) == 1, (
'CheckpointManager only supports single node.')
with Task(outputs=[self._blob_names]) as task:
if retrieve_from_epoch is None:
ops.GetAllBlobNames(
[],
self._blob_names,
include_shared=False)
else:
full_db_name = db_name(retrieve_from_epoch,
self._node_name, self._db_prefix, path_prefix)
db_type = path_type or self._db_type
logger.info("Initializing checkpoints from = %s"
% full_db_name)
ops.Load(
[], self._blob_names,
db=full_db_name,
db_type=db_type,
absolute_path=True)
self._names_output = task.outputs()[0]
return task
def blob_list(self):
assert self._names_output
return self._names_output.fetch().tolist()
def load(self, epoch, path_prefix=None, path_type=None):
"""
Build a Task that will be run by JobRunner when the job is to be
resumed from a given epoch. This task will run a Load op that will
load and deserialize all relevant blobs from a persistent storage.
"""
full_db_name = db_name(epoch, self._node_name, self._db_prefix, path_prefix)
db_type = path_type or self._db_type
logger.info("Loading checkpoints from = %s" % full_db_name)
with Task() as task:
ops.Load(
[],
self.blob_list(),
db=full_db_name,
db_type=db_type,
absolute_path=True)
return task
def load_blobs_from_checkpoint(self, blob_names, epoch):
"""
Builds a Task that loads only the necessary blobs from a checkpoint of
the given epoch. The necessary blobs are given in the blob_names
argument.
Args:
blob_names: A list of strings. Each string is the name of a
blob.
epoch: The checkpoint epoch to load from.
Returns:
A Task which loads the specified blobs from the checkpoint of the
given epoch.
"""
logger.info('Load from %s' % db_name(epoch, self._node_name, self._db_prefix))
with Task() as task:
ops.Load(
[],
blob_names,
db=db_name(epoch, self._node_name, self._db_prefix),
db_type=self._db_type,
absolute_path=True,
allow_incomplete=True)
return task
def check_db_exists(self, epoch):
logger.info('Check existence of %s' %
db_name(epoch, self._node_name, self._db_prefix))
with Task() as task:
existence = ops.Const(False)
ops.DBExists(
[],
[existence],
db_name=db_name(epoch, self._node_name, self._db_prefix),
db_type=self._db_type,
absolute_path=True)
task.add_output(existence)
return task
def save(self, epoch):
"""
Build a Task that is run once after `init_group` and after each
epoch is run. This will execute a Save ops to serialize and persist
blobs present in the global workspace.
"""
logger.info('Saving to %s' % db_name(epoch, self._node_name, self._db_prefix))
with Task() as task:
ops.Save(
self.blob_list(), [],
db=db_name(epoch, self._node_name, self._db_prefix),
db_type=self._db_type, absolute_path=True)
return task
def write_checkpoint_metadata(self, epoch):
"""
Write metadata for checkpoint
Args:
epoch: An integer. The epoch-id for which checkpoint metadata is
written
"""
if self._metadata_handler is not None:
self._metadata_handler.write(epoch=epoch)
def get_resume_from_epoch_id(self, user_epoch=None):
"""
Identify the epoch-id from which Job must resume
Args:
user_epoch: An integer. Optional parameter for user to explicitly
identify the epoch-id to load checkpoint from
Retruns:
epoch: the epoch-id to load checkpoints from
or None if no checkpoints were written
"""
last_epoch = user_epoch
if self._metadata_handler is not None:
last_epoch = self._metadata_handler.last_epoch(user_epoch=user_epoch)
return last_epoch
def set_params(self, nodes, path_prefix=None, path_type=None):
"""Set parameters associated with CP manager
Args:
nodes: An array of nodes where this checkpoint manager is running.
path_prefix: Used to construct db name or path where checkpoint files are
stored.
path_type: Indicate the type of path where checkpoint files are stored.
"""
if path_prefix:
self._path_prefix = path_prefix
if path_type:
self._path_type = path_type
if self._metadata_handler:
self._metadata_handler.set_params(
db_prefix=self._db_prefix,
db_type=self._db_type,
node_names=[str(self._node_name)],
path_prefix=self._path_prefix,
path_type=self._path_type)
def cp_accessible(self, epoch=None):
"""Returns True if Checkpoint data is accessible
Args:
epoch: An integer. The epoch of the checkpoint. If None,
it implies we need to check if checkpoint directory is accessible
Returns:
is_cp_accessible: A boolean. Returns True if Checkpoint data is accessible
"""
if self._metadata_handler is not None:
return self._metadata_handler.cp_accessible(epoch)
else:
return True
class MultiNodeCheckpointManager(object):
"""
Coordinates checkpointing and checkpointing across multiple nodes.
Each of `init`, `load` and `save` will build TaskGroups which will
trigger checkpointing on each of the nodes involved in a distributed job.
Args:
db_prefix: The prefix used to construct full db name. Since `absolute_path`
is set to True, this will be used as db_name in SaveOp.
db_type: Type of database to use for storing checkpoint.
metadata_handler: An optional object capable of reading/writing
checkpoint info in storage of choice.
"""
def __init__(self, db_prefix, db_type, metadata_handler=None):
self._node_managers = None
self._db_prefix = db_prefix
self._db_type = db_type
self._metadata_handler = metadata_handler
self._path_prefix = None
self._path_type = None
def _task_group(self, func, *args, **kw):
assert self._node_managers is not None, 'init must be called first.'
with TaskGroup(WorkspaceType.GLOBAL) as task_group:
for node, manager in self._node_managers:
with Node(node):
func(manager, *args, **kw)
return task_group
"""
Args:
nodes: An array of nodes where this checkpoint manager is running.
retrieve_from_epoch: Set to a number to load blobs from this epoch.
path_prefix: Used to construct db name or path where checkpoint files are
stored.
path_type: Indicate the type of path where checkpoint files are stored.
"""
def init(
self, nodes, retrieve_from_epoch=None, path_prefix=None, path_type=None
):
if self._node_managers is not None:
assert [node for node, _ in self._node_managers] == nodes
return TaskGroup(WorkspaceType.GLOBAL)
self._node_managers = []
for node in nodes:
with Node(node):
manager = CheckpointManager(
db_prefix=self._db_prefix,
node_name=str(node),
db_type=self._db_type)
self._node_managers.append((node, manager))
return self._task_group(
CheckpointManager.init,
nodes=[node],
retrieve_from_epoch=retrieve_from_epoch,
path_prefix=path_prefix,
path_type=path_type)
def load(self, epoch, path_prefix=None, path_type=None):
return self._task_group(
CheckpointManager.load,
epoch,
path_prefix=path_prefix,
path_type=path_type)
def load_blobs_locally(self, nodes, blob_names, epoch, session):
"""Loads the necessary blobs from the checkpoints to the current node.
Args:
blob_names: A list of strings. Each string is the name of a
blob.
epoch: An integer. The checkpoint epoch to load from.
session: A Session object to execute the Load ops.
"""
if self._node_managers is not None:
assert [node for node, _ in self._node_managers] == nodes
else:
self._node_managers = []
for node in nodes:
with Node(node):
manager = CheckpointManager(
db_prefix=self._db_prefix,
node_name=str(node),
db_type=self._db_type)
self._node_managers.append((node, manager))
assert self._node_managers is not None, 'must initialize node managers'
for _, manager in self._node_managers:
existence_task = manager.check_db_exists(epoch)
session.run(existence_task)
existence = existence_task.outputs()[0].fetch()
if not existence:
logger.info('DB %s does not exist!' %
db_name(epoch, manager._node_name, manager._db_prefix))
return False
load_task = manager.load_blobs_from_checkpoint(blob_names, epoch)
session.run(load_task)
logger.info('Successfully loaded from checkpoints.')
return True
def get_ckpt_db_name(self, node_name, epoch):
"""Returns the DB name of the given node and the given epoch.
The DB name is effectively the checkpoint path of the given node and
the given epoch.
Args:
node_name: A string. The node name of interest.
epoch: An integer. The epoch of the checkpoint.
Returns:
checkpoint_db_name: A string. The checkpoint path of the given
node and the given epoch.
"""
for node, manager in self._node_managers:
if str(node) == node_name:
return db_name(epoch, manager._node_name, manager._db_prefix)
def save(self, epoch):
"""
Build a Task that will execute a Save ops to serialize and persist
blobs present in the global workspace.
"""
return self._task_group(CheckpointManager.save, epoch)
def write_checkpoint_metadata(self, epoch):
"""
Write metadata for checkpoint
Args:
epoch: An integer. The epoch-id for which checkpoint metadata is
written
"""
if self._metadata_handler is not None:
self._metadata_handler.write(epoch=epoch)
def get_resume_from_epoch_id(self, user_epoch=None):
"""
Identify the epoch-id from which Job must resume
Args:
user_epoch: An integer. Optional parameter for user to explicitly
identify the epoch-id to load checkpoint from
Retruns:
epoch: the epoch-id to load checkpoints from
or None if no checkpoints were written
"""
last_epoch = user_epoch
if self._metadata_handler is not None:
last_epoch = self._metadata_handler.last_epoch(user_epoch=user_epoch)
return last_epoch
def set_params(self, nodes, path_prefix=None, path_type=None):
"""Set parameters associated with CP manager
Args:
nodes: An array of nodes where this checkpoint manager is running.
path_prefix: Used to construct db name or path where checkpoint files are
stored.
path_type: Indicate the type of path where checkpoint files are stored.
"""
self._node_names = [str(node) for node in nodes]
if path_prefix:
self._path_prefix = path_prefix
if path_type:
self._path_type = path_type
if self._metadata_handler:
self._metadata_handler.set_params(
db_prefix=self._db_prefix,
db_type=self._db_type,
node_names=self._node_names,
path_prefix=self._path_prefix,
path_type=self._path_type)
def cp_accessible(self, epoch=None):
"""Returns True if Checkpoint data is accessible
Args:
epoch: An integer. The epoch of the checkpoint. If None,
it implies we need to check if checkpoint directory is accessible
Returns:
is_cp_accessible: A boolean. Returns True if Checkpoint data is accessible
"""
if self._metadata_handler is not None:
return self._metadata_handler.cp_accessible(epoch)
else:
return True
class UploadTaskGroupBuilder(object):
"""A simple class to upload checkpoints."""
def build(self, epoch, checkpoint_manager):
"""Builds the task group to upload checkpoints.
Args:
epoch: An integer. The checkpoint epoch to be uploaded.
checkpoint_manager: Can be a CheckpointManager for single machine
or a MultiNodeCheckpointManager for multi-machine. The manager
that initializes/saves/loads checkpoints.
Raises:
NotImplementedError: This base class only has the interface,
the implementation will be in the subclasses.
"""
raise NotImplementedError()
class JobRunner(object):
"""
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
runner is a callable to be called once from the master, passing a session
as an argument. This call will block until the Job execution is complete.
If a checkpoint_manager is passed, checkpoints will be taken after
initialization and after each epoch execution. If, in addition,
`resume_from_epoch` is an epoch number, the corresponding checkpoint will
be loaded and job execution will continue from the given epoch. In
this case, the job's init_group will not be run.
Refer to checkpoint_test.py for an example.
"""
def __init__(self, job, checkpoint_manager=None, resume_from_epoch=None,
upload_task_group_builder=None):
"""Initializes the JobRunner.
Args:
job: A Job object. The job to be executed.
checkpoint_manager: Can be a CheckpointManager for single machine
or a MultiNodeCheckpointManager for multi-machine. The manager
that initializes/saves/loads checkpoints.
resume_from_epoch: An integer. The epoch to resume from.
upload_task_group_builder: A subclass of the
UploadTaskGroupBuilder. Creates a task group to upload
checkpoints.
"""
self.resume_from_epoch = resume_from_epoch
self.checkpoint_manager = checkpoint_manager
self.job = job
self.upload_task_group_builder = upload_task_group_builder
def __call__(self, session):
"""Runs the training flow.
Args:
session: A Session object. Valid choises are: LocalSession,
LocalHostScheduler, and DistributedSession. It is used to
execute one TaskGroup a time.
"""
# identify the epoch we must resume from
if self.checkpoint_manager:
self.checkpoint_manager.set_params(nodes=self.job.nodes_to_checkpoint())
self.resume_from_epoch = self.checkpoint_manager.\
get_resume_from_epoch_id(self.resume_from_epoch)
if self.resume_from_epoch is not None:
logger.info('Resuming from epoch {}'.format(self.resume_from_epoch))
# Initialize all the nodes.
from_scratch = self.resume_from_epoch is None
if from_scratch:
session.run(self.job.init_group)
if self.checkpoint_manager:
logger.info('Preparing checkpoints ...')
session.run(self.checkpoint_manager.init(
self.job.nodes_to_checkpoint(),
retrieve_from_epoch=self.resume_from_epoch))
# Save the first checkpoint before training starts, or resume from
# a previously saved checkpoint.
if from_scratch:
self.save_checkpoints(0, session)
else:
logger.info('Loading checkpoints for epoch {} ...'.format(
self.resume_from_epoch))
session.run(
self.checkpoint_manager.load(self.resume_from_epoch))
logger.info('Checkpoint loaded')
logger.info("Finished initializing")
# Start training.
epoch = 1 if from_scratch else self.resume_from_epoch + 1
while True:
logger.info('Starting epoch %d' % epoch)
session.run(self.job.epoch_group)
logger.info('Finished epoch %d' % epoch)
stop_signals = [o.fetch() for o in self.job.stop_signals]
if self.checkpoint_manager:
self.save_checkpoints(epoch, session)
if any(stop_signals):
logger.info('Stopping')
break
epoch += 1
logger.info('Finished training')
# Upload the checkpoints.
if (self.upload_task_group_builder):
upload_task_group = self.upload_task_group_builder.build(
epoch, self.checkpoint_manager)
session.run(upload_task_group)
logger.info('Finished uploading the checkpoints')
# Download the parameters to save
session.run(self.job.download_group)
logger.info('Finished downloading the parameters')
# Finally run the exit step to save nets
session.run(self.job.exit_group)
logger.info('Finished running the exit group')
return epoch
def load_blobs_from_checkpoints(self, blob_names, epoch, session):
"""Loads the necessary blobs from the checkpoints.
Checkpoints store the snapshots of the workspace in each node.
Sometimes we only need to load a subset of the blobs from the
checkpoints. One common scenario is to load only the model blobs from
the checkpoints for evaluation purpose. Given the names of the
necessary blobs, this function goes over all the checkpoints of all the
nodes, but only loads the blobs specified in the blob_names to the
current workspace.
Args:
blob_names: A list of strings. Each string is the name of a
blob.
epoch: An integer. The checkpoint epoch to load from.
session: A Session object to execute the load ops.
Raises:
ValueError: When the checkpoint manager is invalid.
"""
if not self.checkpoint_manager:
raise ValueError('Checkpoint manager is None')
logger.info('Loading checkpoint for epoch {} ...'.format(epoch))
return self.checkpoint_manager.load_blobs_locally(
self.job.nodes_to_checkpoint(), blob_names, epoch, session)
def save_checkpoints(self, epoch, session):
"""Triggers operation to save checkpoints
This method will trigger the Save ops to serialize and persist the
blobs present in the global workspaace.
Args:
epoch: An integer. The checkpoint epoch-id that we are saving.
session: A Session object to execute the save ops.
Raises:
ValueError: When the checkpoint manager is invalid.
"""
if not self.checkpoint_manager:
raise ValueError('Checkpoint manager is None')
try:
is_accessible = self.checkpoint_manager.cp_accessible(epoch=None)
if is_accessible:
logger.info('Saving checkpoints for epoch {}'.format(epoch))
session.run(self.checkpoint_manager.save(epoch))
self.checkpoint_manager.write_checkpoint_metadata(epoch)
logger.info('Checkpoints saved')
else:
logger.warning("Checkpoint files cannot be accessed!")
except Exception as ex:
logger.warning("Unable to write checkpoint for epoch {}. Error={}".
format(epoch, ex))
def epoch_limiter(job, num_epochs):
"""
Creates a task that will output True when a given
number of epochs has finished.
"""
with job.init_group:
init_net = core.Net('epoch_counter_init')
counter = init_net.CreateCounter([], init_count=num_epochs - 1)
Task(step=init_net)
with job.epoch_group:
epoch_net = core.Net('epoch_countdown')
finished = epoch_net.CountDown(counter)
output = Task(step=epoch_net, outputs=finished).outputs()[0]
job.add_stop_signal(output)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import workspace, memonger, core, model_helper, brew
from caffe2.proto import caffe2_pb2
import caffe2.python.hypothesis_test_util as hu
from future.utils import viewvalues
import hypothesis.strategies as st
from hypothesis import given, settings
import unittest
def has_blob(proto, needle):
for op in proto.op:
for inp in op.input:
if inp == needle:
return True
for outp in op.output:
if outp == needle:
return True
return False
def count_blobs(proto):
blobs = set()
for op in proto.op:
blobs = blobs.union(set(op.input)).union(set(op.output))
return len(blobs)
class MemongerTest(hu.HypothesisTestCase):
@given(input_dim=st.integers(min_value=1, max_value=10),
output_dim=st.integers(min_value=1, max_value=10),
batch_size=st.integers(min_value=1, max_value=10),
do=st.sampled_from(hu.device_options),
algo=st.sampled_from(memonger.AssignmentAlgorithm))
@settings(max_examples=5, timeout=120)
def test_simple_memonger(self, input_dim, output_dim, batch_size, do, algo):
m = model_helper.ModelHelper()
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc2, "fc3", dim_in=output_dim, dim_out=output_dim)
fc3.Relu([], fc3)\
.Softmax([], "pred") \
.LabelCrossEntropy(["label"], ["xent"]) \
.AveragedLoss([], "loss")
input_to_grad = m.AddGradientOperators(["loss"])
m.net.Proto().device_option.CopyFrom(do)
m.param_init_net.Proto().device_option.CopyFrom(do)
static_blobs = \
[o for op in m.param_init_net.Proto().op for o in op.output] + \
["data", "label", "loss", input_to_grad["fc1_w"]]
optimization = memonger.optimize_interference(
m.Proto(), static_blobs, algo=algo)
data = np.random.randn(batch_size, input_dim).astype(np.float32)
label = np.random.randint(
low=0, high=output_dim, size=(batch_size,)).astype(np.int32)
workspace.RunNetOnce(m.param_init_net)
workspace.FeedBlob("data", data, device_option=do)
workspace.FeedBlob("label", label, device_option=do)
workspace.RunNetOnce(m.net)
loss = workspace.FetchBlob("loss")
grad = workspace.FetchBlob(str(input_to_grad["fc1_w"]))
workspace.RunNetOnce(optimization.net)
optimized_loss = workspace.FetchBlob("loss")
optimized_grad = workspace.FetchBlob(str(input_to_grad["fc1_w"]))
np.testing.assert_almost_equal(loss, optimized_loss)
np.testing.assert_almost_equal(grad, optimized_grad)
stats = memonger.compute_statistics(optimization.assignments)
self.assertLess(stats.optimized_nbytes, stats.baseline_nbytes)
# run with blob sizes
blob_sizes = memonger.collect_blob_sizes(m.Proto())
optimization1 = memonger.optimize_interference(
m.Proto(), static_blobs, blob_sizes=blob_sizes, algo=algo)
workspace.RunNetOnce(optimization1.net)
optimized_loss = workspace.FetchBlob("loss")
optimized_grad = workspace.FetchBlob(str(input_to_grad["fc1_w"]))
np.testing.assert_almost_equal(loss, optimized_loss)
np.testing.assert_almost_equal(grad, optimized_grad)
stats = memonger.compute_statistics(optimization1.assignments)
self.assertLessEqual(stats.optimized_nbytes, stats.baseline_nbytes)
@given(input_dim=st.integers(min_value=1, max_value=10),
output_dim=st.integers(min_value=1, max_value=10),
batch_size=st.integers(min_value=1, max_value=10),
do=st.sampled_from(hu.device_options))
@settings(max_examples=5, timeout=120)
def test_fast_memonger(self, input_dim, output_dim, batch_size, do):
m = model_helper.ModelHelper()
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc2, "fc3", dim_in=output_dim, dim_out=output_dim)
fc3.Relu([], fc3)\
.Softmax([], "pred") \
.LabelCrossEntropy(["label"], ["xent"]) \
.AveragedLoss([], "loss")
input_to_grad = m.AddGradientOperators(["loss"])
m.net.Proto().device_option.CopyFrom(do)
m.param_init_net.Proto().device_option.CopyFrom(do)
static_blobs = \
[o for op in m.param_init_net.Proto().op for o in op.output] + \
["data", "label", "loss", input_to_grad["fc1_w"]]
optimized_net = memonger.optimize_inference_fast(
m.Proto(), static_blobs)
data = np.random.randn(batch_size, input_dim).astype(np.float32)
label = np.random.randint(
low=0, high=output_dim, size=(batch_size,)).astype(np.int32)
workspace.RunNetOnce(m.param_init_net)
workspace.FeedBlob("data", data, device_option=do)
workspace.FeedBlob("label", label, device_option=do)
workspace.RunNetOnce(m.net)
loss = workspace.FetchBlob("loss")
grad = workspace.FetchBlob(str(input_to_grad["fc1_w"]))
workspace.RunNetOnce(optimized_net)
optimized_loss = workspace.FetchBlob("loss")
optimized_grad = workspace.FetchBlob(str(input_to_grad["fc1_w"]))
np.testing.assert_almost_equal(loss, optimized_loss)
np.testing.assert_almost_equal(grad, optimized_grad)
self.assertLess(count_blobs(optimized_net), count_blobs(m.Proto()))
def test_fast_memonger_unique_outputs(self):
m = model_helper.ModelHelper()
fc = []
for i in range(2):
z = brew.fc(
m, "data{}".format(i), "fc".format(i), dim_in=2, dim_out=2)
fc.append(z)
r = []
# Trick is here to have same input appear twice in a same Sum
for x in fc:
for y in fc:
r.append(brew.sum(m, [x, y], 1))
concated = brew.concat(m, r, "concated")
brew.relu(m, concated, "merged")
static_blobs = \
[o for op in m.param_init_net.Proto().op for o in op.output] + \
["merged"] + ["data{}".format(i) for i in range(len(fc))]
optimized_net = memonger.optimize_inference_fast(
m.Proto(), static_blobs)
for op in optimized_net.op:
self.assertEqual(len(op.output), len(set(op.output)), str(op))
@given(input_dim=st.integers(min_value=1, max_value=4),
output_dim=st.integers(min_value=1, max_value=4),
batch_size=st.integers(min_value=1, max_value=4))
def test_gradient_optim(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc2, "fc3", dim_in=output_dim, dim_out=output_dim)
fc4 = brew.fc(m, fc3, "fc4", dim_in=output_dim, dim_out=output_dim)
fc5 = brew.fc(m, fc4, "fc5", dim_in=output_dim, dim_out=output_dim)
fc5.Relu([], fc5)\
.Softmax([], "pred") \
.LabelCrossEntropy(["label"], ["xent"]) \
.AveragedLoss([], "loss")
input_to_grad = m.AddGradientOperators(["name_x/loss"])
blobs_before = count_blobs(m.net.Proto())
optim_proto = memonger.share_grad_blobs(
m.net,
["name_x/loss"],
set(viewvalues(m.param_to_grad)),
"name_x/",
share_activations=False,
)
blobs_after = count_blobs(optim_proto)
self.assertLess(blobs_after, blobs_before)
optim_proto_wacts = memonger.share_grad_blobs(
m.net,
["name_x/loss"],
set(viewvalues(m.param_to_grad)),
"name_x/",
share_activations=True,
dont_share_blobs=set([str(input_to_grad["name_x/fc1_w"])]),
)
blobs_wact_optim = count_blobs(optim_proto_wacts)
self.assertLessEqual(blobs_wact_optim, blobs_after)
# Check that the last activations are not shared
self.assertTrue(has_blob(optim_proto, "name_x/fc5"))
self.assertTrue(
has_blob(optim_proto_wacts, "name_x/fc5"),
"Dont remap final activation",
)
# Test networks produce exactly same gradients
data = np.random.randn(batch_size, input_dim).astype(np.float32)
label = np.random.randint(
low=0, high=output_dim, size=(batch_size,)).astype(np.int32)
workspace.RunNetOnce(m.param_init_net)
workspace.FeedBlob("name_x/data", data)
workspace.FeedBlob("name_x/label", label)
workspace.RunNetOnce(m.net)
loss = workspace.FetchBlob("name_x/loss")
grad = workspace.FetchBlob(str(input_to_grad["name_x/fc1_w"]))
workspace.RunNetOnce(optim_proto)
optimized_loss = workspace.FetchBlob("name_x/loss")
optimized_grad = workspace.FetchBlob(str(input_to_grad["name_x/fc1_w"]))
np.testing.assert_almost_equal(loss, optimized_loss)
np.testing.assert_almost_equal(grad, optimized_grad)
workspace.FeedBlob(str(input_to_grad["name_x/fc1_w"]), np.array([0.0]))
# Run with the forward optimization
workspace.RunNetOnce(optim_proto_wacts)
optimized_loss = workspace.FetchBlob("name_x/loss")
optimized_grad = workspace.FetchBlob(str(input_to_grad["name_x/fc1_w"]))
np.testing.assert_almost_equal(loss, optimized_loss)
np.testing.assert_almost_equal(grad, optimized_grad)
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support.")
def test_memonger_mix_cpu_gpu(self):
'''
Check that memonger does not make blobs cross CPU/GPU boundary
'''
m = model_helper.ModelHelper()
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
fc1 = brew.fc(m, "data", "fc1", dim_in=2, dim_out=2)
fc2 = brew.fc(m, fc1, "fc2", dim_in=2, dim_out=2)
fc3 = brew.fc(m, fc2, "fc3", dim_in=2, dim_out=2)
fc4 = brew.fc(m, fc3, "fc4", dim_in=2, dim_out=2)
fc4_cpu = m.net.CopyGPUToCPU(fc4, "fc4_cpu")
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)):
fc5_cpu = brew.fc(m, fc4_cpu, "fc5_cpu", dim_in=2, dim_out=2)
fc6_cpu = brew.fc(m, fc5_cpu, "fc6_cpu", dim_in=2, dim_out=2)
fc7_cpu = brew.fc(m, fc6_cpu, "fc7_cpu", dim_in=2, dim_out=2)
fc7_cpu.Relu([], fc7_cpu) \
.Softmax([], "pred") \
.LabelCrossEntropy(["label"], ["xent"]) \
.AveragedLoss([], "loss")
m.AddGradientOperators(["loss"])
blobs_before = count_blobs(m.net.Proto())
optim_proto = memonger.share_grad_blobs(
m.net,
["loss"],
set(viewvalues(m.param_to_grad)),
"",
share_activations=True,
dont_share_blobs=set(),
)
blobs_after = count_blobs(optim_proto)
self.assertLess(blobs_after, blobs_before)
# Create set of blobs on CPU side and GPU side and check they don't
# overlap
device_blobs = {caffe2_pb2.CPU: set(), caffe2_pb2.CUDA: set()}
for op in optim_proto.op:
if op.type not in ['CopyCPUToGPU', "CopyGPUToCPU"]:
dev = op.device_option.device_type
for b in list(op.input) + list(op.output):
device_blobs[dev].add(b)
device_crossers = device_blobs[caffe2_pb2.CPU].intersection(
device_blobs[caffe2_pb2.CUDA]
)
self.assertEquals(device_crossers, set())
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_gradient_optim_tree(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc2, "fc3", dim_in=output_dim, dim_out=output_dim)
fc4 = brew.fc(m, fc3, "fc4", dim_in=output_dim, dim_out=output_dim)
fc5 = brew.fc(m, fc4, "fc5", dim_in=output_dim, dim_out=output_dim)
fc5.Relu([], fc5) \
.Softmax([], "pred1") \
.LabelCrossEntropy(["label"], ["xent1"]) \
.AveragedLoss([], "loss1")
fc6 = brew.fc(m, fc5, "fc6", dim_in=output_dim, dim_out=output_dim)
fc6.Relu([], fc6) \
.Softmax([], "pred2") \
.LabelCrossEntropy(["label"], ["xent2"]) \
.AveragedLoss([], "loss2")
input_to_grad = m.AddGradientOperators(["name_x/loss1", "name_x/loss2"])
blobs_before = count_blobs(m.net.Proto())
optim_proto = memonger.share_grad_blobs(
m.net,
["name_x/loss1", "name_x/loss2"],
set(viewvalues(m.param_to_grad)),
"name_x", # "name_x//shared_gradinp_0_shared" if using "name_x/"
share_activations=True,
dont_share_blobs=set(['name_x/fc6', 'name_x/fc5',
str(input_to_grad["name_x/fc1_w"])]),
)
blobs_after = count_blobs(optim_proto)
self.assertLess(blobs_after, blobs_before)
self.assertTrue(has_blob(optim_proto, "name_x/fc6"))
# Test networks produce exactly same gradients
data = np.random.randn(batch_size, input_dim).astype(np.float32)
label = np.random.randint(
low=0, high=output_dim, size=(batch_size,)).astype(np.int32)
workspace.RunNetOnce(m.param_init_net)
workspace.FeedBlob("name_x/data", data)
workspace.FeedBlob("name_x/label", label)
workspace.RunNetOnce(m.net)
loss1 = workspace.FetchBlob("name_x/loss1")
loss2 = workspace.FetchBlob("name_x/loss2")
grad = workspace.FetchBlob(str(input_to_grad["name_x/fc1_w"]))
workspace.FeedBlob(str(input_to_grad["name_x/fc1_w"]), np.array([0.0]))
workspace.RunNetOnce(optim_proto)
optimized_loss1 = workspace.FetchBlob("name_x/loss1")
optimized_loss2 = workspace.FetchBlob("name_x/loss2")
optimized_grad = workspace.FetchBlob(str(input_to_grad["name_x/fc1_w"]))
np.testing.assert_almost_equal(loss1, optimized_loss1)
np.testing.assert_almost_equal(loss2, optimized_loss2)
np.testing.assert_almost_equal(grad, optimized_grad)
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_forward_optim_tree_daggy(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
m.Proto().type = "dag"
m.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc2, "fc3", dim_in=output_dim, dim_out=output_dim)
fc4 = brew.fc(m, fc3, "fc4", dim_in=output_dim, dim_out=output_dim)
fc5 = brew.fc(m, fc4, "fc5", dim_in=output_dim, dim_out=output_dim)
# Branch
fc3b = brew.fc(m, fc2, "fc3b", dim_in=output_dim, dim_out=output_dim)
fc4b = brew.fc(m, fc3b, "fc4b", dim_in=output_dim, dim_out=output_dim)
fc5b = brew.fc(m, fc4b, "fc5b", dim_in=output_dim, dim_out=output_dim)
fc5sum = brew.sum(m, [fc5, fc5b], "fc5sum")
fc5.Relu([], fc5sum) \
.Softmax([], "pred1") \
.LabelCrossEntropy(["label"], ["xent1"]) \
.AveragedLoss([], "loss1")
fc6 = brew.fc(m, fc5, "fc6", dim_in=output_dim, dim_out=output_dim)
fc6.Relu([], fc6) \
.Softmax([], "pred2") \
.LabelCrossEntropy(["label"], ["xent2"]) \
.AveragedLoss([], "loss2")
blobs_before = count_blobs(m.net.Proto())
optim_proto = memonger.optimize_inference_for_dag(
m.net, ["name_x/data"], "name_x"
)
blobs_after = count_blobs(optim_proto)
self.assertLess(blobs_after, blobs_before)
# Test networks produce exactly same results
data = np.random.randn(batch_size, input_dim).astype(np.float32)
label = np.random.randint(
low=0, high=output_dim, size=(batch_size,)).astype(np.int32)
workspace.RunNetOnce(m.param_init_net)
workspace.FeedBlob("name_x/data", data)
workspace.FeedBlob("name_x/label", label)
workspace.RunNetOnce(m.net)
loss1 = workspace.FetchBlob("name_x/loss1")
loss2 = workspace.FetchBlob("name_x/loss2")
workspace.RunNetOnce(optim_proto)
optimized_loss1 = workspace.FetchBlob("name_x/loss1")
optimized_loss2 = workspace.FetchBlob("name_x/loss2")
np.testing.assert_almost_equal(loss1, optimized_loss1)
np.testing.assert_almost_equal(loss2, optimized_loss2)
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_forward_optim_tree_harder(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
m.net.Proto().type = "dag"
m.net.Proto().num_workers = 4
m.net.AddExternalInput("label")
m.net.AddExternalInput("data")
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc2, "fc3", dim_in=output_dim, dim_out=output_dim)
fc4 = brew.fc(m, fc3, "fc4", dim_in=output_dim, dim_out=output_dim)
fc5 = brew.fc(m, fc4, "fc5", dim_in=output_dim, dim_out=output_dim)
# Branch
fc3b = brew.fc(m, fc2, "fc3b", dim_in=output_dim, dim_out=output_dim)
fc4b = brew.fc(m, fc3b, "fc4b", dim_in=output_dim, dim_out=output_dim)
fc5b = brew.fc(m, fc4b, "fc5b", dim_in=output_dim, dim_out=output_dim)
fc5sum = brew.sum(m, [fc5, fc5b], "fc5sum")
fc5sum.Relu([], "relu1") \
.Softmax([], "pred1") \
.LabelCrossEntropy(["label"], ["xent1"]) \
.AveragedLoss([], "loss1")
fc6 = brew.fc(m, fc5, "fc6", dim_in=output_dim, dim_out=output_dim)
fc6.Relu([], fc6) \
.Softmax([], "pred2") \
.LabelCrossEntropy(["label"], ["xent2"]) \
.AveragedLoss([], "loss2")
blobs_before = count_blobs(m.net.Proto())
optim_proto = memonger.optimize_inference_for_dag(
m.net, ["name_x/data"], "name_x/"
)
blobs_after = count_blobs(optim_proto)
# Extra test with when one of the parameters is also an input.
# This caused a bug before.
optim_proto_extra_input = memonger.optimize_inference_for_dag(
m.net, ["name_x/data", "name_x/fc1_w"], "name_x/"
)
blobs_after_extra_input = count_blobs(optim_proto_extra_input)
self.assertEqual(blobs_after, blobs_after_extra_input)
###
print(str(optim_proto))
self.assertLess(blobs_after, blobs_before)
# Test networks produce exactly same results
data = np.random.randn(batch_size, input_dim).astype(np.float32)
label = np.random.randint(
low=0, high=output_dim, size=(batch_size,)).astype(np.int32)
workspace.RunNetOnce(m.param_init_net)
workspace.FeedBlob("name_x/data", data)
workspace.FeedBlob("name_x/label", label)
workspace.RunNetOnce(m.net)
loss1 = workspace.FetchBlob("name_x/loss1")
loss2 = workspace.FetchBlob("name_x/loss2")
workspace.RunNetOnce(optim_proto)
optimized_loss1 = workspace.FetchBlob("name_x/loss1")
optimized_loss2 = workspace.FetchBlob("name_x/loss2")
np.testing.assert_almost_equal(loss1, optimized_loss1)
np.testing.assert_almost_equal(loss2, optimized_loss2)
def test_rnn(self):
from caffe2.python import rnn_cell
T = 5
model = model_helper.ModelHelper()
seq_lengths, labels = \
model.net.AddExternalInputs(
'seq_lengths', 'labels',
)
init_blobs = []
for i in range(2):
hidden_init, cell_init = model.net.AddExternalInputs(
"hidden_init_{}".format(i),
"cell_init_{}".format(i)
)
init_blobs.extend([hidden_init, cell_init])
model.param_init_net.ConstantFill([], ["input"], shape=[T, 4, 10])
output, last_hidden, _, last_state = rnn_cell.LSTM(
model=model,
input_blob="input",
seq_lengths=seq_lengths,
initial_states=init_blobs,
dim_in=10,
dim_out=[10, 10],
scope="lstm1",
forward_only=False,
drop_states=True,
return_last_layer_only=True,
)
softmax, loss = model.net.SoftmaxWithLoss(
[model.Flatten(output), "labels"],
['softmax', 'loss'],
)
model.AddGradientOperators([loss])
blobs_before = count_blobs(model.net.Proto())
optim_proto = memonger.share_grad_blobs(
model.net,
["loss"],
set(viewvalues(model.param_to_grad)),
"",
share_activations=True,
dont_share_blobs=set(),
)
blobs_after = count_blobs(optim_proto)
self.assertLess(blobs_after, blobs_before)
# Run once to see all blobs are set up correctly
for init_blob in init_blobs:
workspace.FeedBlob(init_blob, np.zeros(
[1, 4, 10], dtype=np.float32
))
workspace.FeedBlob("seq_lengths", np.array([T] * 4, dtype=np.int32))
workspace.FeedBlob("labels", np.random.rand(T).astype(np.int32))
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
def test_compute_interference_graph_inplace_ops(self):
m = model_helper.ModelHelper()
m.Copy("b1", "b1")
m.Copy("b1", "b1")
m.Copy("b1", "b1")
g = memonger.compute_interference_graph(m.net.Proto().op)
self.assertEqual(list(g.edges()), [(0, 1), (0, 2), (1, 2)])
def test_topological_sort_longest_path(self):
m = model_helper.ModelHelper()
# 0
m.Copy("conv0_w_comp", "conv0_w")
# 1
conv0 = brew.conv(m, "data", "conv0", 32, 32, 4)
# 2
m.Copy("conv2_w", "conv2_w")
# 3
brew.conv(m, conv0, "conv2", 16, 32, 4)
g = memonger.compute_interference_graph(m.net.Proto().op)
orders_org = memonger.topological_sort_traversal(g)
orders_gt_org = [2, 0, 1, 3]
self.assertEqual(orders_gt_org, list(orders_org))
orders = memonger.topological_sort_traversal_longest_path(g)
# longer path is in front of the shorter one
orders_gt = [0, 1, 2, 3]
self.assertEqual(orders_gt, list(orders))
def test_topological_sort_longest_path_multi_target(self):
# two outputs: conv2 and data4
m = model_helper.ModelHelper()
# 0
m.Copy("conv0_w_comp", "conv0_w")
# 1
conv0 = brew.conv(m, "data", "conv0", 32, 32, 4)
# 2
m.Copy("conv2_w", "conv2_w")
# 3
brew.conv(m, conv0, "conv2", 16, 32, 4)
# 4
m.Copy("data1", "data2")
# 5
m.Copy("data2", "data3")
g = memonger.compute_interference_graph(m.net.Proto().op)
orders_org = memonger.topological_sort_traversal(g)
orders_gt_org = [4, 5, 2, 0, 1, 3]
self.assertEqual(orders_gt_org, list(orders_org))
orders = memonger.topological_sort_traversal_longest_path(g)
# longer path is in front of the shorter one
orders_gt = [0, 1, 2, 3, 4, 5]
self.assertEqual(orders_gt, list(orders))
def test_topological_sort_longest_path_single_node(self):
# single node
m = model_helper.ModelHelper()
# 0
m.Copy("conv0_w_comp", "conv0_w")
g = memonger.compute_interference_graph(m.net.Proto().op)
orders_org = memonger.topological_sort_traversal(g)
orders_gt_org = [0]
self.assertEqual(orders_gt_org, list(orders_org))
orders = memonger.topological_sort_traversal_longest_path(g)
# longer path is in front of the shorter one
orders_gt = [0]
self.assertEqual(orders_gt, list(orders))
def test_compute_assignments_greedy(self):
LiveRange = memonger.LiveRange
ranges_sorted = [
('b1', LiveRange(1, 3, 10)),
('b2', LiveRange(3, 4, 1)),
('b3', LiveRange(5, 6, 1)),
('b4', LiveRange(5, 7, 10)),
]
assignment_gt = [
[ranges_sorted[0], ranges_sorted[3]],
[ranges_sorted[1], ranges_sorted[2]],
]
best = memonger.compute_assignments_greedy(ranges_sorted, None)
self.assertEqual(memonger.get_memory_usage(best), 11)
self.assertEqual(best, assignment_gt)
def test_compute_assignments_dp(self):
LiveRange = memonger.LiveRange
ranges_sorted = [
('b1', LiveRange(1, 3, 10)),
('b2', LiveRange(3, 4, 1)),
('b3', LiveRange(5, 6, 1)),
('b4', LiveRange(5, 7, 10)),
]
best = memonger.compute_assignments_dp(ranges_sorted, None)
self.assertEqual(memonger.get_memory_usage(best), 11)
def test_compute_assignments_dp1(self):
LiveRange = memonger.LiveRange
ranges_sorted = [
('b1', LiveRange(1, 2, 10)),
('b2', LiveRange(4, 6, 1)),
('b3', LiveRange(5, 6, 10)),
]
best = memonger.compute_assignments_dp(ranges_sorted, [])
self.assertEqual(memonger.get_memory_usage(best), 11)
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_verify_graph_equality(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
m.Proto().type = "dag"
m.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc1, "z", dim_in=output_dim, dim_out=output_dim)
brew.sum(m, [fc2, fc3], "out")
m2 = model_helper.ModelHelper()
m2.Proto().type = "dag"
m2.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m2, "data", "other_x", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m2, fc1, "other_y", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m2, fc1, "other_z", dim_in=output_dim, dim_out=output_dim)
brew.sum(m2, [fc2, fc3], "out")
self.assertTrue(memonger.verify_graph_equality(m.net.Proto(), m2.net.Proto()))
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_verify_graph_equality_harder(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
m.Proto().type = "dag"
m.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2a = brew.fc(m, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc2b = brew.fc(m, fc1, "z", dim_in=output_dim, dim_out=output_dim)
fc3a = brew.fc(m, fc2a, "u", dim_in=output_dim, dim_out=output_dim)
fc3b = brew.fc(m, fc2b, "v", dim_in=output_dim, dim_out=output_dim)
brew.sum(m, [fc3a, fc3b], "out")
m2 = model_helper.ModelHelper()
m2.Proto().type = "dag"
m2.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m2, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2a = brew.fc(m2, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc2b = brew.fc(m2, fc1, "z", dim_in=output_dim, dim_out=output_dim)
fc3a = brew.fc(m2, fc2a, "y", dim_in=output_dim, dim_out=output_dim)
fc3b = brew.fc(m2, fc2b, "z", dim_in=output_dim, dim_out=output_dim)
brew.sum(m2, [fc3a, fc3b], "out")
self.assertTrue(memonger.verify_graph_equality(m.net.Proto(), m2.net.Proto()))
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_verify_graph_inequality(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
m.Proto().type = "dag"
m.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m, fc1, "z", dim_in=output_dim, dim_out=output_dim)
brew.sum(m, [fc2, fc3], "out")
m2 = model_helper.ModelHelper()
m2.Proto().type = "dag"
m2.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m2, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m2, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc3 = brew.fc(m2, fc1, "y", dim_in=output_dim, dim_out=output_dim)
brew.sum(m2, [fc2, fc3], "out")
self.assertFalse(memonger.verify_graph_equality(m.net.Proto(), m2.net.Proto()))
@given(input_dim=st.integers(min_value=4, max_value=4),
output_dim=st.integers(min_value=4, max_value=4),
batch_size=st.integers(min_value=4, max_value=4))
def test_verify_graph_inequality_harder(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
m.Proto().type = "dag"
m.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2a = brew.fc(m, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc2b = brew.fc(m, fc1, "z", dim_in=output_dim, dim_out=output_dim)
fc3a = brew.fc(m, fc2a, "u", dim_in=output_dim, dim_out=output_dim)
fc3b = brew.fc(m, fc2b, "v", dim_in=output_dim, dim_out=output_dim)
brew.sum(m, [fc3a, fc3b], "out")
m2 = model_helper.ModelHelper()
m2.Proto().type = "dag"
m2.Proto().num_workers = 4
with core.NameScope("name_x"):
fc1 = brew.fc(m2, "data", "x", dim_in=input_dim, dim_out=output_dim)
fc2a = brew.fc(m2, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc2b = brew.fc(m2, fc1, "y", dim_in=output_dim, dim_out=output_dim)
fc3a = brew.fc(m2, fc2a, "u", dim_in=output_dim, dim_out=output_dim)
fc3b = brew.fc(m2, fc2b, "v", dim_in=output_dim, dim_out=output_dim)
brew.sum(m2, [fc3a, fc3b], "out")
self.assertFalse(memonger.verify_graph_equality(m.net.Proto(), m2.net.Proto()))
def test_release_blobs_when_used(self):
m = model_helper.ModelHelper()
fc1 = brew.fc(m, "data", "x", dim_in=2, dim_out=2)
fc2 = brew.fc(m, fc1, "y", dim_in=2, dim_out=2)
fc3 = brew.fc(m, fc1, "z", dim_in=2, dim_out=2)
fc4 = brew.fc(m, fc2, "u", dim_in=2, dim_out=2)
m.net.Alias(["u"], ["u_alias"])
brew.sum(m, [fc3, fc4], "out")
with_frees = memonger.release_blobs_when_used(m.net.Proto(), set("data"))
expect_frees = {"x", "y", "z"} # out is external output
# and u is aliased so cannot be freed
found_frees = set()
for op in with_frees.op:
if op.type == "Free":
self.assertFalse(op.input[0] in found_frees) # no double frees
found_frees.add(op.input[0])
else:
# Check a freed blob is not used anymore
for inp in op.input:
self.assertFalse(inp in found_frees)
for outp in op.output:
self.assertFalse(outp in found_frees)
self.assertEqual(expect_frees, found_frees)
if __name__ == '__main__':
unittest.main()
|
# @package parallel_workers
# Module caffe2.python.parallel_workers
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'''
This module provides a python-land multithreaded mechanism for executing work.
Basic usage is as follows:
coordinator = parallel_workers.init_workers(
my_worker_fun,
worker_name="train"
)
...
coordinator.start()
First argument is the function to run in a loop on potentially multiple threads.
It has the call signature
worker_fun(worker_id)
Argument 'worker_name' is used to distinguish different workers,
such as workers processing train data or workers processing test data.
Optionally, one can define an "init function" that is called once before
threads start, and has call signature:
my_init_fun(worker_coordinator, global_coordinator)
Note that for data_parallel_models, init_workers will be called
for each GPU. Note that the 'coordinator' returned by the function is same
each time.
'''
import logging
import threading
import atexit
import time
import collections
import six
import traceback
from abc import ABCMeta, abstractmethod
log = logging.getLogger("parallel_workers")
log.setLevel(logging.INFO)
LOG_INT_SECS = 60
def init_workers(
worker_fun,
num_worker_threads=2,
worker_name="train",
init_fun=None,
external_loggers=None,
shutdown_fun=None,
):
global global_coordinator
metrics = Metrics(external_loggers)
# Create coordinator object
coordinator = WorkerCoordinator(
worker_name, init_fun, shutdown_fun=shutdown_fun)
# Launch fetch worker threads
worker_ids = [
global_coordinator.get_new_worker_id()
for i in range(num_worker_threads)
]
workers = [
threading.Thread(
target=run_worker,
name="parallel_workers worker id {}".format(worker_id),
args=[coordinator,
Worker(coordinator, worker_id, worker_fun, metrics)],
) for worker_id in worker_ids
]
coordinator._workers = workers
global_coordinator.add(coordinator)
return global_coordinator
class Metrics(object):
def __init__(self, external_loggers):
self._metrics = collections.defaultdict(lambda: 0)
self._external_loggers = external_loggers
def reset_metrics(self):
self._metrics = collections.defaultdict(lambda: 0)
def log_metrics(self):
if not self._external_loggers:
return
for logger in self._external_loggers:
try:
logger.log(self._metrics)
except Exception as e:
print("Failed to call ExternalLogger: {}".format(e))
def put_metric(self, key, value, count=True):
self._metrics[key] += value
if count:
count_key = '{}_count'.format(key)
self._metrics[count_key] += 1
class State():
six.add_metaclass(ABCMeta)
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
@abstractmethod
def cleanup(self):
pass
class WorkerCoordinator(object):
def __init__(self, worker_name, init_fun, state=None, shutdown_fun=None):
self._active = True
self._started = False
self._workers = []
self._worker_name = worker_name
self._init_fun = init_fun
self._state = state
self._shutdown_fun = shutdown_fun
def is_active(self):
return self._active
def init(self, global_coordinator):
if self._init_fun and not self._started:
data_coordinator = self
self._init_fun(data_coordinator, global_coordinator)
def _start(self):
if self._started:
return
self._active = True
self._started = True
if self._state:
self._state.start()
for w in self._workers:
w.daemon = True
w.start()
def _stop(self, reason=None):
self._active = False
if reason is not None:
log.error("Data input failed due to an error: {}".format(reason))
if self._shutdown_fun and self._started:
self._shutdown_fun()
if self._state:
self._state.stop()
self._started = False
def _wait_finish(self, cleanup=None):
print("Wait for workers to die: {}".format(self._worker_name))
for w in self._workers:
if w != threading.current_thread():
w.join(5.0) # don't wait forever, thread may be blocked in i/o
success = True
for w in self._workers:
if w.isAlive():
print("Worker {} failed to close while waiting".format(w))
success = False
# Release memory for the scratch blobs
if success and self._state:
self._state.cleanup()
print("All workers terminated: {}".format(success))
return success
class GlobalWorkerCoordinator(object):
def __init__(self):
self._coordinators = []
self._fetcher_id_seq = 0
self._worker_ids = []
self.register_shutdown_handler()
def add(self, coordinator):
self._coordinators.append(coordinator)
def get_new_worker_id(self):
worker_id = self._fetcher_id_seq
self._worker_ids.append(worker_id)
self._fetcher_id_seq += 1
return worker_id
def get_worker_ids(self):
return self._worker_ids
def start(self):
# run init and start in separate for loop to
# ensure init happens serially before threads are spawn.
for c in self._coordinators:
c.init(self)
for c in self._coordinators:
c._start()
def stop(self):
all_success = True
for c in self._coordinators:
c._stop()
for c in self._coordinators:
success = c._wait_finish()
all_success = all_success and success
self._coordinators = []
return all_success
def stop_coordinator(self, worker_name):
'''
Stop a specific coordinator
'''
for c in self._coordinators:
if c._worker_name == worker_name:
c._stop()
c._wait_finish()
self._coordinators = [
c for c in self._coordinators
if c._worker_name != worker_name
]
def register_shutdown_handler(self):
def cleanup():
self.stop()
atexit.register(cleanup)
class Worker(object):
def __init__(
self,
coordinator,
worker_id,
worker_fun=None,
metrics=None
):
self._coordinator = coordinator
self._worker_id = worker_id
self._worker_fun = worker_fun
self._metrics = metrics
def start(self):
self._start_time = time.time()
def run(self):
self._worker_fun(self._worker_id)
def handle_exception(self, e):
traceback.print_exc()
logging.exception("Exception in worker", e)
self._coordinator._stop("Exception in worker {}: {}".format(
self._worker_id, e
))
def finish(self):
self._metrics.put_metric(
'worker_time', time.time() - self._start_time)
self._metrics.log_metrics()
global_coordinator = GlobalWorkerCoordinator()
def run_worker(coordinator, worker):
while coordinator.is_active():
worker.start()
try:
worker.run()
except Exception as e:
worker.handle_exception(e)
finally:
worker.finish()
|
## @package hypothesis_test_util
# Module caffe2.python.hypothesis_test_util
"""
The Hypothesis library uses *property-based testing* to check
invariants about the code under test under a variety of random inputs.
The key idea here is to express properties of the code under test
(e.g. that it passes a gradient check, that it implements a reference
function, etc), and then generate random instances and verify they
satisfy these properties.
The main functions of interest are exposed on `HypothesisTestCase`.
You can usually just add a short function in this to generate an
arbitrary number of test cases for your operator.
The key functions are:
- `assertDeviceChecks(devices, op, inputs, outputs)`. This asserts that the
operator computes the same outputs, regardless of which device it is executed
on.
- `assertGradientChecks(device, op, inputs, output_,
outputs_with_grads)`. This implements a standard numerical gradient checker
for the operator in question.
- `assertReferenceChecks(device, op, inputs, reference)`. This runs the
reference function (effectively calling `reference(*inputs)`, and comparing
that to the output of output.
`hypothesis_test_util.py` exposes some useful pre-built samplers.
- `hu.gcs` - a gradient checker device (`gc`) and device checker devices (`dc`)
- `hu.gcs_cpu_only` - a CPU-only gradient checker device (`gc`) and
device checker devices (`dc`). Used for when your operator is only
implemented on the CPU.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from caffe2.python import (
workspace, device_checker, gradient_checker, test_util, core)
import contextlib
import copy
import functools
import hypothesis
import hypothesis.extra.numpy
import hypothesis.strategies as st
import logging
import numpy as np
import os
def is_sandcastle():
if os.getenv('SANDCASTLE') == '1':
return True
elif os.getenv('TW_JOB_USER') == 'sandcastle':
return True
return False
def is_travis():
return 'TRAVIS' in os.environ
hypothesis.settings.register_profile(
"sandcastle",
hypothesis.settings(
derandomize=True,
suppress_health_check=[hypothesis.HealthCheck.too_slow],
database=None,
min_satisfying_examples=1,
max_examples=100,
verbosity=hypothesis.Verbosity.verbose))
hypothesis.settings.register_profile(
"dev",
hypothesis.settings(
suppress_health_check=[hypothesis.HealthCheck.too_slow],
database=None,
max_examples=10,
min_satisfying_examples=1,
verbosity=hypothesis.Verbosity.verbose))
hypothesis.settings.register_profile(
"debug",
hypothesis.settings(
suppress_health_check=[hypothesis.HealthCheck.too_slow],
database=None,
max_examples=1000,
min_satisfying_examples=1,
verbosity=hypothesis.Verbosity.verbose))
hypothesis.settings.load_profile(
'sandcastle' if is_sandcastle() else os.getenv('CAFFE2_HYPOTHESIS_PROFILE',
'dev')
)
def dims(min_value=1, max_value=5):
return st.integers(min_value=min_value, max_value=max_value)
def elements_of_type(dtype=np.float32, filter_=None):
elems = None
if dtype in (np.float16, np.float32, np.float64):
elems = st.floats(min_value=-1.0, max_value=1.0)
elif dtype is np.int32:
elems = st.integers(min_value=0, max_value=2 ** 31 - 1)
elif dtype is np.int64:
elems = st.integers(min_value=0, max_value=2 ** 63 - 1)
elif dtype is np.bool:
elems = st.booleans()
else:
raise ValueError("Unexpected dtype without elements provided")
return elems if filter_ is None else elems.filter(filter_)
def arrays(dims, dtype=np.float32, elements=None):
if elements is None:
elements = elements_of_type(dtype)
return hypothesis.extra.numpy.arrays(
dtype,
dims,
elements=elements,
)
def tensor(min_dim=1,
max_dim=4,
dtype=np.float32,
elements=None,
**kwargs):
dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim)
return dims_.flatmap(
lambda dims: arrays(dims, dtype, elements))
def tensor1d(min_len=1, max_len=64, dtype=np.float32, elements=None):
return tensor(1, 1, dtype, elements, min_value=min_len, max_value=max_len)
def segment_ids(size, is_sorted):
if size == 0:
return st.just(np.empty(shape=[0], dtype=np.int32))
if is_sorted:
return arrays(
[size],
dtype=np.int32,
elements=st.booleans()).map(
lambda x: np.cumsum(x, dtype=np.int32) - x[0])
else:
return arrays(
[size],
dtype=np.int32,
elements=st.integers(min_value=0, max_value=2 * size))
def lengths(size, min_segments=None, max_segments=None, **kwargs):
# First generate number of boarders between segments
# Then create boarder values and add 0 and size
# By sorting and computing diff we convert them to lengths of
# possible 0 value
if min_segments is None:
min_segments = 0
if max_segments is None:
max_segments = size
assert min_segments >= 0
assert min_segments <= max_segments
if size == 0 and max_segments == 0:
return st.just(np.empty(shape=[0], dtype=np.int32))
assert max_segments > 0, "size is not 0, need at least one segment"
return st.integers(
min_value=max(min_segments - 1, 0), max_value=max_segments - 1
).flatmap(
lambda num_borders:
hypothesis.extra.numpy.arrays(
np.int32, num_borders, elements=st.integers(
min_value=0, max_value=size
)
)
).map(
lambda x: np.append(x, np.array([0, size], dtype=np.int32))
).map(sorted).map(np.diff)
def segmented_tensor(
min_dim=1,
max_dim=4,
dtype=np.float32,
is_sorted=True,
elements=None,
segment_generator=segment_ids,
allow_empty=False,
**kwargs
):
gen_empty = st.booleans() if allow_empty else st.just(False)
data_dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim)
data_dims_ = st.tuples(
gen_empty, data_dims_
).map(lambda pair: ([0] if pair[0] else []) + pair[1])
return data_dims_.flatmap(lambda data_dims: st.tuples(
arrays(data_dims, dtype, elements),
segment_generator(data_dims[0], is_sorted=is_sorted),
))
def lengths_tensor(min_segments=None, max_segments=None, *args, **kwargs):
gen = functools.partial(
lengths, min_segments=min_segments, max_segments=max_segments)
return segmented_tensor(*args, segment_generator=gen, **kwargs)
def sparse_segmented_tensor(min_dim=1, max_dim=4, dtype=np.float32,
is_sorted=True, elements=None, allow_empty=False,
segment_generator=segment_ids, itype=np.int64,
**kwargs):
gen_empty = st.booleans() if allow_empty else st.just(False)
data_dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim)
all_dims_ = st.tuples(gen_empty, data_dims_).flatmap(
lambda pair: st.tuples(
st.just(pair[1]),
(st.integers(min_value=1, max_value=pair[1][0]) if not pair[0]
else st.just(0)),
))
return all_dims_.flatmap(lambda dims: st.tuples(
arrays(dims[0], dtype, elements),
arrays(dims[1], dtype=itype, elements=st.integers(
min_value=0, max_value=dims[0][0] - 1)),
segment_generator(dims[1], is_sorted=is_sorted),
))
def sparse_lengths_tensor(**kwargs):
return sparse_segmented_tensor(segment_generator=lengths, **kwargs)
def tensors(n, min_dim=1, max_dim=4, dtype=np.float32, elements=None, **kwargs):
dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim)
return dims_.flatmap(
lambda dims: st.lists(
arrays(dims, dtype, elements),
min_size=n,
max_size=n))
def tensors1d(n, min_len=1, max_len=64, dtype=np.float32, elements=None):
return tensors(
n, 1, 1, dtype, elements, min_value=min_len, max_value=max_len
)
cpu_do = caffe2_pb2.DeviceOption()
gpu_do = caffe2_pb2.DeviceOption(device_type=caffe2_pb2.CUDA)
device_options = [cpu_do] + ([gpu_do] if workspace.has_gpu_support else [])
# Include device option for each GPU
expanded_device_options = [cpu_do] + (
[caffe2_pb2.DeviceOption(device_type=caffe2_pb2.CUDA, cuda_gpu_id=i)
for i in range(workspace.NumCudaDevices())]
if workspace.has_gpu_support else [])
def device_checker_device_options():
return st.just(device_options)
def gradient_checker_device_option():
return st.sampled_from(device_options)
gcs = dict(
gc=gradient_checker_device_option(),
dc=device_checker_device_options()
)
gcs_cpu_only = dict(gc=st.sampled_from([cpu_do]), dc=st.just([cpu_do]))
gcs_gpu_only = dict(gc=st.sampled_from([gpu_do]), dc=st.just([gpu_do]))
@contextlib.contextmanager
def temp_workspace(name=b"temp_ws"):
old_ws_name = workspace.CurrentWorkspace()
workspace.SwitchWorkspace(name, True)
yield
workspace.ResetWorkspace()
workspace.SwitchWorkspace(old_ws_name)
def runOpBenchmark(
device_option,
op,
inputs,
input_device_options=None,
iterations=10,
):
if input_device_options is None:
input_device_options = {}
op = copy.deepcopy(op)
op.device_option.CopyFrom(device_option)
net = caffe2_pb2.NetDef()
net.op.extend([op])
net.name = op.name if op.name else "test"
with temp_workspace():
for (n, b) in zip(op.input, inputs):
workspace.FeedBlob(
n,
b,
device_option=input_device_options.get(n, device_option)
)
workspace.CreateNet(net)
ret = workspace.BenchmarkNet(net.name, 1, iterations, True)
return ret
class HypothesisTestCase(test_util.TestCase):
"""
A unittest.TestCase subclass with some helper functions for
utilizing the `hypothesis` (hypothesis.readthedocs.io) library.
"""
def assertDeviceChecks(
self,
device_options,
op,
inputs,
outputs_to_check,
input_device_options=None,
threshold=0.01
):
"""
Asserts that the operator computes the same outputs, regardless of
which device it is executed on.
Useful for checking the consistency of GPU and CPU
implementations of operators.
Usage example:
@given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs)
def test_sum(self, inputs, in_place, gc, dc):
op = core.CreateOperator("Sum", ["X1", "X2"],
["Y" if not in_place else "X1"])
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
"""
dc = device_checker.DeviceChecker(
threshold,
device_options=device_options
)
self.assertTrue(
dc.CheckSimple(op, inputs, outputs_to_check, input_device_options)
)
def assertGradientChecks(
self,
device_option,
op,
inputs,
outputs_to_check,
outputs_with_grads,
grad_ops=None,
threshold=0.005,
stepsize=0.05,
input_device_options=None,
):
"""
Implements a standard numerical gradient checker for the operator
in question.
Useful for checking the consistency of the forward and
backward implementations of operators.
Usage example:
@given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs)
def test_sum(self, inputs, in_place, gc, dc):
op = core.CreateOperator("Sum", ["X1", "X2"],
["Y" if not in_place else "X1"])
X1, X2 = inputs
self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
"""
gc = gradient_checker.GradientChecker(
stepsize=stepsize,
threshold=threshold,
device_option=device_option,
workspace_name=str(device_option),
)
res, grad, grad_estimated = gc.CheckSimple(
op, inputs, outputs_to_check, outputs_with_grads,
grad_ops=grad_ops,
input_device_options=input_device_options
)
self.assertEqual(grad.shape, grad_estimated.shape)
self.assertTrue(
res,
"Gradient check failed for input " + str(op.input[outputs_to_check])
)
def _assertGradReferenceChecks(
self,
op,
inputs,
ref_outputs,
output_to_grad,
grad_reference,
threshold=1e-4,
):
grad_blob_name = output_to_grad + '_grad'
grad_ops, grad_map = core.GradientRegistry.GetBackwardPass(
[op], {output_to_grad: grad_blob_name})
output_grad = workspace.FetchBlob(output_to_grad)
grad_ref_outputs = grad_reference(output_grad, ref_outputs, inputs)
workspace.FeedBlob(grad_blob_name, workspace.FetchBlob(output_to_grad))
workspace.RunOperatorsOnce(grad_ops)
self.assertEqual(len(grad_ref_outputs), len(inputs))
for (n, ref) in zip(op.input, grad_ref_outputs):
grad_names = grad_map.get(n)
if not grad_names:
# no grad for this input
self.assertIsNone(ref)
else:
if isinstance(grad_names, core.BlobReference):
# dense gradient
ref_vals = ref
ref_indices = None
val_name = grad_names
else:
# sparse gradient
ref_vals, ref_indices = ref
val_name = grad_names.values
vals = workspace.FetchBlob(str(val_name))
np.testing.assert_allclose(
vals,
ref_vals,
atol=threshold,
rtol=threshold,
err_msg='Gradient {0} (x) is not matching the reference (y)'
.format(val_name),
)
if ref_indices is not None:
indices = workspace.FetchBlob(str(grad_names.indices))
np.testing.assert_allclose(indices, ref_indices,
atol=1e-4, rtol=1e-4)
def _assertInferTensorChecks(self, name, shapes, types, output):
if name not in shapes:
# No inferred shape or type available
return
output = workspace.FetchBlob(name)
if type(output) is np.ndarray:
if output.dtype == np.dtype('float64'):
correct_type = caffe2_pb2.TensorProto.DOUBLE
elif output.dtype == np.dtype('float32'):
correct_type = caffe2_pb2.TensorProto.FLOAT
elif output.dtype == np.dtype('int32'):
correct_type = caffe2_pb2.TensorProto.INT32
elif output.dtype == np.dtype('int64'):
correct_type = caffe2_pb2.TensorProto.INT64
else:
correct_type = "unknown {}".format(np.dtype)
else:
correct_type = str(type(output))
try:
np.testing.assert_array_equal(
np.array(shapes[name]).astype(np.int32),
np.array(output.shape).astype(np.int32),
err_msg='Shape {} mismatch: {} vs. {}'.format(
name,
shapes[name],
output.shape))
# BUG: Workspace blob type not being set correctly T16121392
if correct_type != caffe2_pb2.TensorProto.INT32:
return
np.testing.assert_equal(
types[name],
correct_type,
err_msg='Type {} mismatch: {} vs. {}'.format(
name, types[name], correct_type,
)
)
except AssertionError as e:
# Temporarily catch these assertion errors when validating
# inferred shape and type info
logging.warning(str(e))
if os.getenv('CAFFE2_ASSERT_SHAPEINFERENCE') == '1':
raise e
def assertReferenceChecks(
self,
device_option,
op,
inputs,
reference,
input_device_options=None,
threshold=1e-4,
output_to_grad=None,
grad_reference=None,
atol=None,
outputs_to_check=None,
):
"""
This runs the reference Python function implementation
(effectively calling `reference(*inputs)`, and compares that
to the output of output, with an absolute/relative tolerance
given by the `threshold` parameter.
Useful for checking the implementation matches the Python
(typically NumPy) implementation of the same functionality.
Usage example:
@given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs)
def test_softsign(self, X, inplace, gc, dc):
op = core.CreateOperator(
"Softsign", ["X"], ["X" if inplace else "Y"])
def softsign(X):
return (X / (1 + np.abs(X)),)
self.assertReferenceChecks(gc, op, [X], softsign)
"""
if input_device_options is None:
input_device_options = {}
op = copy.deepcopy(op)
op.device_option.CopyFrom(device_option)
with temp_workspace():
if (len(op.input) > len(inputs)):
raise ValueError(
'must supply an input for each input on the op: %s vs %s' %
(op.input, inputs))
for (n, b) in zip(op.input, inputs):
workspace.FeedBlob(
n,
b,
device_option=input_device_options.get(n, device_option)
)
net = core.Net("opnet")
net.Proto().op.extend([op])
test_shape_inference = False
try:
(shapes, types) = workspace.InferShapesAndTypes([net])
test_shape_inference = True
except RuntimeError as e:
# Temporarily catch runtime errors when inferring shape
# and type info
logging.warning(str(e))
if os.getenv('CAFFE2_ASSERT_SHAPEINFERENCE') == '1':
raise e
workspace.RunNetOnce(net)
reference_outputs = reference(*inputs)
if not (isinstance(reference_outputs, tuple) or
isinstance(reference_outputs, list)):
raise RuntimeError(
"You are providing a wrong reference implementation. A "
"proper one should return a tuple/list of numpy arrays.")
if not outputs_to_check:
self.assertEqual(len(reference_outputs), len(op.output))
outputs_to_check = list(range(len(op.output)))
outs = []
for (output_index, ref) in zip(outputs_to_check, reference_outputs):
output_blob_name = op.output[output_index]
output = workspace.FetchBlob(output_blob_name)
if output.dtype.kind in ('S', 'O'):
np.testing.assert_array_equal(output, ref)
else:
if atol is None:
atol = threshold
np.testing.assert_allclose(
output, ref, atol=atol, rtol=threshold,
err_msg=(
'Output {0} is not matching the reference'.format(
output_blob_name,
)),
)
if test_shape_inference:
self._assertInferTensorChecks(
output_blob_name, shapes, types, output)
outs.append(output)
if grad_reference is not None:
assert output_to_grad is not None, \
"If grad_reference is set," \
"output_to_grad has to be set as well"
with core.DeviceScope(device_option):
self._assertGradReferenceChecks(
op, inputs, reference_outputs,
output_to_grad, grad_reference,
threshold=threshold)
return outs
def assertValidationChecks(
self,
device_option,
op,
inputs,
validator,
input_device_options=None,
as_kwargs=True,
init_net=None,
):
if input_device_options is None:
input_device_options = {}
if as_kwargs:
assert len(set(list(op.input) + list(op.output))) == \
len(op.input) + len(op.output), \
"in-place ops are not supported in as_kwargs mode"
op = copy.deepcopy(op)
op.device_option.CopyFrom(device_option)
with temp_workspace():
for (n, b) in zip(op.input, inputs):
workspace.FeedBlob(
n,
b,
device_option=input_device_options.get(n, device_option)
)
if init_net:
workspace.RunNetOnce(init_net)
workspace.RunOperatorOnce(op)
outputs = [workspace.FetchBlob(n) for n in op.output]
if as_kwargs:
validator(**dict(zip(
list(op.input) + list(op.output), inputs + outputs)))
else:
validator(inputs=inputs, outputs=outputs)
def assertRunOpRaises(
self,
device_option,
op,
inputs,
input_device_options=None,
exception=(Exception,),
regexp=None,
):
if input_device_options is None:
input_device_options = {}
op = copy.deepcopy(op)
op.device_option.CopyFrom(device_option)
with temp_workspace():
for (n, b) in zip(op.input, inputs):
workspace.FeedBlob(
n,
b,
device_option=input_device_options.get(n, device_option)
)
if regexp is None:
self.assertRaises(exception, workspace.RunOperatorOnce, op)
else:
self.assertRaisesRegexp(
exception, regexp, workspace.RunOperatorOnce, op)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import numpy as np
class TestSparseToDenseMask(TestCase):
def test_sparse_to_dense_mask_float(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default', 'lengths'],
['output'],
mask=[999999999, 2, 6])
workspace.FeedBlob(
'indices',
np.array([2, 4, 6, 1, 2, 999999999, 2], dtype=np.int32))
workspace.FeedBlob(
'values',
np.array([1, 2, 3, 4, 5, 6, 7], dtype=np.float))
workspace.FeedBlob('default', np.array(-1, dtype=np.float))
workspace.FeedBlob('lengths', np.array([3, 4], dtype=np.int32))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
expected = np.array([[-1, 1, 3], [6, 7, -1]], dtype=np.float)
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
def test_sparse_to_dense_mask_invalid_inputs(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default', 'lengths'],
['output'],
mask=[999999999, 2])
workspace.FeedBlob(
'indices',
np.array([2000000000000, 999999999, 2, 3, 4, 5], dtype=np.int32))
workspace.FeedBlob(
'values',
np.array([1, 2, 3, 4, 5, 6], dtype=np.float))
workspace.FeedBlob('default', np.array(-1, dtype=np.float))
workspace.FeedBlob('lengths', np.array([6], dtype=np.int32))
try:
workspace.RunOperatorOnce(op)
except RuntimeError:
self.fail("Exception raised with only one negative index")
workspace.FeedBlob(
'indices',
np.array([2000000000000, 999999999, -2, -3, -4, -5], dtype=np.int32))
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def test_sparse_to_dense_mask_subtensor(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default', 'lengths'],
['output'],
mask=[999999999, 2, 888, 6])
workspace.FeedBlob(
'indices',
np.array([2, 4, 6, 999999999, 2], dtype=np.int64))
workspace.FeedBlob(
'values',
np.array([[[1, -1]], [[2, -2]], [[3, -3]], [[4, -4]], [[5, -5]]],
dtype=np.float))
workspace.FeedBlob('default', np.array([[-1, 0]], dtype=np.float))
workspace.FeedBlob('lengths', np.array([2, 3], dtype=np.int32))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
expected = np.array([
[[[-1, 0]], [[1, -1]], [[-1, 0]], [[-1, 0]]],
[[[4, -4]], [[5, -5]], [[-1, 0]], [[3, -3]]]], dtype=np.float)
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
def test_sparse_to_dense_mask_string(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default', 'lengths'],
['output'],
mask=[999999999, 2, 6])
workspace.FeedBlob(
'indices',
np.array([2, 4, 6, 1, 2, 999999999, 2], dtype=np.int32))
workspace.FeedBlob(
'values',
np.array(['1', '2', '3', '4', '5', '6', '7'], dtype='S'))
workspace.FeedBlob('default', np.array('-1', dtype='S'))
workspace.FeedBlob('lengths', np.array([3, 4], dtype=np.int32))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
expected =\
np.array([['-1', '1', '3'], ['6', '7', '-1']], dtype='S')
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
def test_sparse_to_dense_mask_empty_lengths(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default'],
['output'],
mask=[1, 2, 6])
workspace.FeedBlob('indices', np.array([2, 4, 6], dtype=np.int32))
workspace.FeedBlob('values', np.array([1, 2, 3], dtype=np.float))
workspace.FeedBlob('default', np.array(-1, dtype=np.float))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
expected = np.array([-1, 1, 3], dtype=np.float)
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
def test_sparse_to_dense_mask_no_lengths(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default'],
['output'],
mask=[1, 2, 6])
workspace.FeedBlob('indices', np.array([2, 4, 6], dtype=np.int32))
workspace.FeedBlob('values', np.array([1, 2, 3], dtype=np.float))
workspace.FeedBlob('default', np.array(-1, dtype=np.float))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
expected = np.array([-1, 1, 3], dtype=np.float)
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
def test_sparse_to_dense_mask_presence_mask(self):
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default', 'lengths'],
['output', 'presence_mask'],
mask=[11, 12],
return_presence_mask=True)
workspace.FeedBlob('indices', np.array([11, 12, 13], dtype=np.int32))
workspace.FeedBlob('values', np.array([11, 12, 13], dtype=np.float))
workspace.FeedBlob('default', np.array(-1, dtype=np.float))
workspace.FeedBlob('lengths', np.array([1, 2], dtype=np.int32))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
presence_mask = workspace.FetchBlob('presence_mask')
expected_output = np.array([[11, -1], [-1, 12]], dtype=np.float)
expected_presence_mask = np.array(
[[True, False], [False, True]],
dtype=np.bool)
self.assertEqual(output.shape, expected_output.shape)
np.testing.assert_array_equal(output, expected_output)
self.assertEqual(presence_mask.shape, expected_presence_mask.shape)
np.testing.assert_array_equal(presence_mask, expected_presence_mask)
|
## @package crf
# Module caffe2.python.crf
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, recurrent, model_helper, brew
import numpy as np
'''
Due to a limitation in ReccurentNetworkOp, this layer only supports batch_size=1
In order to support batch_size > 1, we will have to implement the CRFUnit
and its gradient in C++ and handle the different batches there.
'''
class CRFWithLoss(object):
def __init__(self, model, num_classes, transitions_blob=None):
self.model = model
self.num_classes = num_classes
self.num_classes_padded = num_classes + 2 # After adding BOS and EOS
if not transitions_blob:
transitions_blob = self.model.param_init_net.UniformFill(
[],
[core.ScopedBlobReference('crf_transitions')],
shape=[self.num_classes_padded, self.num_classes_padded],
min=-1.0,
max=1.0
)
self.transitions = transitions_blob
self.model.params.append(self.transitions)
def crf_loss(self, predictions, labels, seq_lengths=None):
# Since the transitions matrix is a shared parameter, need to
# take a snapshot of it at the beginning since it can be updated
# in between the operators that uses it when doing parallel updates
transitions_snapshot = self.model.net.Copy(
self.transitions, core.ScopedBlobReference('transitions_snapshot')
)
# Compute best path unary score from the logits
path_unary_score = self._gather_entries_sum(
predictions, labels, self.num_classes
)
# Append BOS and EOS entries to the predictions and labels
predictions = self._pad_predictions(predictions)
labels = self._pad_labels(labels)
# Compute best path binary scores from the transitions matrix
path_binary_score = self._path_binary_scores(
labels, transitions_snapshot, seq_lengths
)
path_total_score = self.model.net.Add(
[path_binary_score, path_unary_score],
core.ScopedBlobReference('path_total')
)
# Compute all paths score
zero_index = self.model.param_init_net.ConstantFill(
[], shape=[1], value=0
)
initial_state = self.model.net.Gather(
[predictions, zero_index],
core.ScopedBlobReference('rnn_initial'),
dense_gradient=True
)
input_data, _ = self.model.net.RemovePadding(
[predictions],
padding_width=1,
end_padding_width=0,
outputs=2,
)
input_data = self.model.net.ExpandDims(
[input_data],
core.ScopedBlobReference('rnn_input_data'),
dims=[1]
)
# Due to a bug in RecurrentNetworkGradientOp, we need to copy the
# transitions blob before sending it to the recurrent network
transitions_copy = self.model.net.Copy(
transitions_snapshot, core.ScopedBlobReference('transitions_copy')
)
all_paths_scores = self._crf_forward(
input_data, initial_state, transitions_copy
)
loss = self.model.net.Sub(
[all_paths_scores, path_total_score],
core.ScopedBlobReference('crf_loss')
)
return loss
def _pad_predictions(self, predictions):
# This function will introduce two labels for beginning of sequence
# And end of sequence, it will make the necessary udpates to the
# the predictions blob
low_score = -1000.0 # An arbitray very low number
b_scores = np.array(
[[low_score] * self.num_classes + [0, low_score]]
).astype(np.float32)
e_scores = np.array(
[[low_score] * self.num_classes + [low_score, 0]]
).astype(np.float32)
b_scores = self.model.param_init_net.GivenTensorFill(
[], "b_scores", shape=[1, self.num_classes_padded], values=b_scores
)
e_scores = self.model.param_init_net.GivenTensorFill(
[], "e_scores", shape=[1, self.num_classes_padded], values=e_scores
)
zero_index = self.model.net.ConstantFill(
[], shape=[1, ], value=0
)
length = self.model.net.Gather(
[self.model.net.Shape([predictions]), zero_index],
)
length = self.model.net.Cast(length, to='int32')
t_range = self.model.net.LengthsRangeFill(length)
padding = self.model.net.ConstantFill([t_range], value=low_score)
padding = self.model.net.ExpandDims(padding, dims=[1])
padded_predictions, _ = self.model.net.Concat(
[predictions, padding, padding],
outputs=2,
axis=1
)
padded_predictions_concat, _ = self.model.net.Concat(
[b_scores, padded_predictions, e_scores],
outputs=2,
axis=0
)
return padded_predictions_concat
def _pad_labels(self, labels):
bos_i = self.num_classes
eos_i = self.num_classes + 1
bos_i_b = self.model.param_init_net.ConstantFill(
[], shape=[1], value=bos_i
)
eos_i_b = self.model.param_init_net.ConstantFill(
[], shape=[1], value=eos_i
)
labels = self.model.net.Cast([labels], to='int64')
padded_labels, _ = self.model.net.Concat(
[bos_i_b, labels, eos_i_b],
axis=0,
outputs=2
)
return padded_labels
def _path_binary_scores(self, labels, transitions, seq_lengths=None):
column_ids, _ = self.model.net.RemovePadding(
[labels],
outputs=2,
padding_width=1,
end_padding_width=0
)
row_ids, _ = self.model.net.RemovePadding(
[labels],
outputs=2,
padding_width=0,
end_padding_width=1
)
# Since there is no multi-dimensional gather, I flatten the matrix to
# a 1-d vector and transform the ids to (row_ids * num_columns +
# column_ids) and do gather in 1-d
num_columns_blob = self.model.net.ConstantFill(
[row_ids],
value=self.num_classes_padded,
)
flattened_ids = self.model.net.Mul([row_ids, num_columns_blob])
flattened_ids = self.model.net.Add([flattened_ids, column_ids])
flattened_transitions = self.model.net.FlattenToVec([transitions])
entries = self.model.net.Gather(
[flattened_transitions, flattened_ids],
dense_gradient=True
)
return self.model.ReduceFrontSum(entries)
def _gather_entries_sum(self, in_data, indices, index_size):
indices = self.model.net.Cast([indices], to='int64')
index_size_blob = self.model.param_init_net.ConstantFill(
[],
shape=[1],
value=index_size,
)
query_one_hot = self.model.net.OneHot(
[indices, index_size_blob]
)
flattend_query = self.model.net.FlattenToVec(query_one_hot)
flattend_data = self.model.net.FlattenToVec(in_data)
query_scores = self.model.net.DotProduct(
[flattend_query, flattend_data]
)
final_sum = self.model.net.ReduceFrontSum([query_scores])
return final_sum
def _crf_forward(
self,
input_blob,
initial_state,
transitions_copy,
seq_lengths=None
):
# Build the RNN net and get the last timestep output
out_last = self.build_crf_net(
input_blob, initial_state, transitions_copy
)
out_last, _ = self.model.net.Reshape(
[out_last],
outputs=2,
shape=(self.num_classes_padded,)
)
zero_segment_id = self.model.param_init_net.ConstantFill(
[],
value=0,
shape=[self.num_classes_padded],
dtype=core.DataType.INT32,
)
# Compute the accumlated total score of all the paths
accum_score = self.model.net.SortedSegmentRangeLogSumExp(
[out_last, zero_segment_id]
)
accum_score, _ = self.model.net.Reshape(
accum_score,
outputs=2,
shape=()
)
return accum_score
def build_crf_net(self, input_blob, initial_state, transitions):
'''
Adds the crf_net recurrent operator to the model.
model: model_helper.ModelHelper object new operators would be added
to
input_blob: the input sequence in a format T x N x D
where T is sequence size, N - batch size and D - input dimention
##Only supports batch-size 1##
seq_lengths: blob containing sequence lengths (unused)
'''
scope = 'crf_net'
def s(name):
''
# We have to manually scope due to our internal/external blob
# relationships.
return "{}/{}".format(str(scope), str(name))
step_model = model_helper.ModelHelper(name='crf_step',
param_model=self.model)
input_t, cell_t_prev, _ = (
step_model.net.AddExternalInputs(
core.ScopedBlobReference('input_t'),
core.ScopedBlobReference('cell_t_prev'),
transitions
)
)
zero_segment_id = step_model.param_init_net.ConstantFill(
[],
[s('zero_segment_id')],
value=0,
shape=[self.num_classes_padded],
dtype=core.DataType.INT32,
)
# A hack to bypass model cloning for test
step_model.param_init_net.AddExternalOutput(zero_segment_id)
""" the CRF step """
# Do tile
prev_transpose = brew.transpose(
step_model,
cell_t_prev,
[s('prev_transpose')],
axes=(0, 2, 1),
)
prev_tiled = step_model.net.Tile(
prev_transpose,
[s('prev_tiled')],
tiles=self.num_classes_padded,
axis=2,
)
input_t_tiled = step_model.net.Tile(
input_t,
[s('input_t_tiled')],
tiles=self.num_classes_padded,
axis=1,
)
input_with_prev = step_model.net.Add(
[prev_tiled, input_t_tiled],
[s('input_with_prev')]
)
all_with_transitions = step_model.net.Add(
[input_with_prev, transitions],
[s('prev_with_transitions')],
broadcast=1,
use_grad_hack=1,
)
all_with_transitions_reshaped, _ = step_model.net.Reshape(
all_with_transitions,
[s('all_with_transitions_reshaped'), s('all_with_transitions_orig')],
shape=(self.num_classes_padded, self.num_classes_padded)
)
cell_t = step_model.net.SortedSegmentRangeLogSumExp(
[all_with_transitions_reshaped, zero_segment_id],
[s('cell_t')],
)
step_model.net.AddExternalOutputs(cell_t)
""" recurrent network """
cell_input_blob = initial_state
out_all, out_last = recurrent.recurrent_net(
net=self.model.net,
cell_net=step_model.net,
inputs=[(input_t, input_blob)],
initial_cell_inputs=[
(cell_t_prev, cell_input_blob),
],
links={
cell_t_prev: cell_t,
},
scope=scope,
outputs_with_grads=(1,)
)
return out_last
def update_predictions(self, classes):
def crf_update_predictions_op(inputs, outputs):
# This operator will compute the best path of classes by performing
# Viterbi decoding and then updates the predictions to make the tag
# On the best path has the highest score among the others
predictions = inputs[0].data
transitions = inputs[1].data
predictions = inputs[0].data
predictions_shape = inputs[0].shape
outputs[0].reshape(predictions_shape)
trellis = np.zeros(predictions_shape)
backpointers = np.zeros(predictions_shape, dtype=np.int32)
trellis[0] = predictions[0]
for t in range(1, predictions_shape[0]):
v = np.expand_dims(trellis[t - 1], 1) + transitions
trellis[t] = predictions[t] + np.max(v, 0)
backpointers[t] = np.argmax(v, 0)
viterbi = [np.argmax(trellis[-1])]
for bp in reversed(backpointers[1:]):
viterbi.append(bp[viterbi[-1]])
viterbi.reverse()
new_predictions = np.zeros(predictions_shape)
old_bests = []
for i, w_predictions in enumerate(predictions):
# Get the current tag with the maximum score
new_predictions[i] = predictions[i]
old_best = np.argmax(w_predictions)
old_bests.append(old_best)
# Swap the scores of the current best tag and the tag on the
# Viterbi path
w_predictions[viterbi[i]], w_predictions[old_best] = \
w_predictions[old_best], w_predictions[viterbi[i]]
new_predictions[i] = w_predictions
# Remove the BOS and EOS entries from the predictions matrix
orig_predictions = new_predictions[1:-1, 0:-2]
outputs[0].reshape(orig_predictions.shape)
outputs[0].data[...] = orig_predictions
padded_classes = self._pad_predictions(classes)
new_classes = self.model.net.Python(crf_update_predictions_op)(
[padded_classes, self.transitions],
core.ScopedBlobReference('post_crf_classes')
)
return new_classes
|
## @package recurrent
# Module caffe2.python.recurrent
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from future.utils import viewitems, viewkeys
def recurrent_net(
net, cell_net, inputs, initial_cell_inputs,
links, timestep=None, scope=None, outputs_with_grads=(0,),
recompute_blobs_on_backward=None, forward_only=False,
):
'''
net: the main net operator should be added to
cell_net: cell_net which is executed in a recurrent fasion
inputs: sequences to be fed into the recurrent net. Currently only one input
is supported. It has to be in a format T x N x (D1...Dk) where T is lengths
of the sequence. N is a batch size and (D1...Dk) are the rest of dimentions
initial_cell_inputs: inputs of the cell_net for the 0 timestamp.
Format for each input is:
(cell_net_input_name, external_blob_with_data)
links: a dictionary from cell_net input names in moment t+1 and
output names of moment t. Currently we assume that each output becomes
an input for the next timestep.
timestep: name of the timestep blob to be used. If not provided "timestep"
is used.
scope: Internal blobs are going to be scoped in a format
<scope_name>/<blob_name>
If not provided we generate a scope name automatically
outputs_with_grads : position indices of output blobs which will receive
error gradient (from outside recurrent network) during backpropagation
recompute_blobs_on_backward: specify a list of blobs that will be
recomputed for backward pass, and thus need not to be
stored for each forward timestep.
forward_only: if True, only forward steps are executed
'''
assert len(inputs) == 1, "Only one input blob is supported so far"
input_blobs = [str(i[0]) for i in inputs]
initial_input_blobs = [str(x[1]) for x in initial_cell_inputs]
op_name = net.NextName('recurrent')
def s(name):
# We have to manually scope due to our internal/external blob
# relationships.
scope_name = op_name if scope is None else scope
return "{}/{}".format(str(scope_name), str(name))
# determine inputs that are considered to be references
# it is those that are not referred to in inputs or initial_cell_inputs
known_inputs = [str(b) for b in input_blobs + initial_input_blobs]
known_inputs += [str(x[0]) for x in initial_cell_inputs]
if timestep is not None:
known_inputs.append(str(timestep))
references = [
core.BlobReference(b) for b in cell_net.Proto().external_input
if b not in known_inputs]
inner_outputs = list(cell_net.Proto().external_output)
# These gradients are expected to be available during the backward pass
inner_outputs_map = {o: o + '_grad' for o in inner_outputs}
# compute the backward pass of the cell net
if not forward_only:
backward_ops, backward_mapping = core.GradientRegistry.GetBackwardPass(
cell_net.Proto().op, inner_outputs_map)
backward_mapping = {str(k): v for k, v in viewitems(backward_mapping)}
backward_cell_net = core.Net("RecurrentBackwardStep")
del backward_cell_net.Proto().op[:]
if recompute_blobs_on_backward is not None:
# Insert operators to re-compute the specified blobs.
# They are added in the same order as for the forward pass, thus
# the order is correct.
recompute_blobs_on_backward = {str(b) for b in
recompute_blobs_on_backward}
for op in cell_net.Proto().op:
if not recompute_blobs_on_backward.isdisjoint(set(op.output)):
backward_cell_net.Proto().op.extend([op])
# This fires if other outputs than the declared
# are computed by the ops that are recomputed
assert set(op.output).issubset(recompute_blobs_on_backward)
backward_cell_net.Proto().op.extend(backward_ops)
# compute blobs used but not defined in the backward pass
backward_ssa, backward_blob_versions = core.get_ssa(
backward_cell_net.Proto())
undefined = core.get_undefined_blobs(backward_ssa)
# also add to the output list the intermediate outputs of fwd_step that
# are used by backward.
ssa, blob_versions = core.get_ssa(cell_net.Proto())
scratches = [
blob
for blob, ver in viewitems(blob_versions)
if (ver > 0 and
blob in undefined and
blob not in cell_net.Proto().external_output)
]
backward_cell_net.Proto().external_input.extend(scratches)
backward_cell_net.Proto().type = 'simple'
else:
backward_cell_net = None
all_inputs = [i[1] for i in inputs] + [
x[1] for x in initial_cell_inputs] + references
all_outputs = []
cell_net.Proto().type = 'simple'
# Internal arguments used by RecurrentNetwork operator
# Links are in the format blob_name, recurrent_states, offset.
# In the moment t we know that corresponding data block is at
# t + offset position in the recurrent_states tensor
forward_links = []
backward_links = []
# Aliases are used to expose outputs to external world
# Format (internal_blob, external_blob, offset)
# Negative offset stands for going from the end,
# positive - from the beginning
aliases = []
# States held inputs to the cell net
recurrent_states = []
for cell_input, _ in initial_cell_inputs:
cell_input = str(cell_input)
# Recurrent_states is going to be (T + 1) x ...
# It stores all inputs and outputs of the cell net over time.
# Or their gradients in the case of the backward pass.
state = s(cell_input + "_states")
states_grad = state + "_grad"
cell_output = links[str(cell_input)]
forward_links.append((cell_input, state, 0))
forward_links.append((cell_output, state, 1))
aliases.append((state, cell_output + "_all", 1))
aliases.append((state, cell_output + "_last", -1))
all_outputs.extend([cell_output + "_all", cell_output + "_last"])
recurrent_states.append(state)
if backward_cell_net is not None:
backward_links.append((cell_output + "_grad", states_grad, 1))
backward_cell_net.Proto().external_input.append(
str(cell_output) + "_grad")
recurrent_input_grad = cell_input + "_grad"
if not backward_blob_versions.get(recurrent_input_grad, 0):
# If nobody writes to this recurrent input gradient, we need
# to make sure it gets to the states grad blob after all.
# We do this by using backward_links which triggers an alias
# This logic is being used for example in a SumOp case
backward_links.append(
(backward_mapping[cell_input], states_grad, 0))
else:
backward_links.append((recurrent_input_grad, states_grad, 0))
for input_t, input_blob in inputs:
forward_links.append((str(input_t), str(input_blob), 0))
if backward_cell_net is not None:
for input_t, input_blob in inputs:
backward_links.append((
backward_mapping[str(input_t)], str(input_blob) + "_grad", 0
))
backward_cell_net.Proto().external_input.extend(
cell_net.Proto().external_input)
backward_cell_net.Proto().external_input.extend(
cell_net.Proto().external_output)
def unpack_triple(x):
if x:
a, b, c = zip(*x)
return a, b, c
return [], [], []
# Splitting to separate lists so we can pass them to c++
# where we ensemle them back
link_internal, link_external, link_offset = unpack_triple(forward_links)
alias_src, alias_dst, alias_offset = unpack_triple(aliases)
recurrent_inputs = [str(x[1]) for x in initial_cell_inputs]
# Make sure that recurrent gradients accumulate with internal gradients
# (if a blob in the backward_cell_net receives gradient from both an
# external connection as well as from within the backward_cell_net,
# those gradients need to be added together, rather than one overwriting
# the other)
if backward_cell_net is not None:
proto = backward_cell_net.Proto()
operators = []
while len(proto.op) > 0:
op = proto.op[-1]
proto.op.remove(op)
operators.append(op)
for op in operators[::-1]:
proto.op.extend([op])
for j, output_blob in enumerate(op.output):
if output_blob in proto.external_input:
# In place operation won't cause issues because it takes
# existing value of a blob into account
if output_blob in op.input:
continue
output_blob = core.BlobReference(output_blob)
accum_blob = output_blob + "_accum"
proto.op[-1].output[j] = str(accum_blob)
backward_cell_net.Sum(
[output_blob, accum_blob],
[output_blob],
)
def map_to_dual_list(m):
return [str(x) for x in list(m.keys())] + \
[str(x) for x in list(m.values())]
backward_args = {}
if backward_cell_net is not None:
backward_mapping_keys = set(viewkeys(backward_mapping))
backward_link_internal, backward_link_external, backward_link_offset = \
unpack_triple(backward_links)
params = [x for x in references if x in backward_mapping_keys]
param_grads = [
str(backward_mapping[x])
for x in references
if x in backward_mapping_keys
]
if recompute_blobs_on_backward is None:
recompute_blobs_on_backward = set()
backward_args = {
'param': [all_inputs.index(p) for p in params],
'backward_link_internal': [str(l) for l in backward_link_internal],
'backward_link_external': [str(l) for l in backward_link_external],
'backward_link_offset': backward_link_offset,
'outputs_with_grads': outputs_with_grads,
'recompute_blobs_on_backward': [
str(b) for b in recompute_blobs_on_backward
],
'param_grads': param_grads,
}
if len(backward_cell_net.Proto().op) != 0:
backward_args['backward_step_net'] = backward_cell_net.Proto()
results = net.RecurrentNetwork(
all_inputs,
all_outputs + [s("step_workspaces")],
alias_src=alias_src,
alias_dst=[str(a) for a in alias_dst],
alias_offset=alias_offset,
recurrent_states=recurrent_states,
initial_recurrent_state_ids=[
all_inputs.index(i) for i in recurrent_inputs
],
link_internal=[str(l) for l in link_internal],
link_external=[str(l) for l in link_external],
link_offset=link_offset,
enable_rnn_executor=1,
step_net=cell_net.Proto(),
timestep="timestep" if timestep is None else str(timestep),
**backward_args
)
# Restore net type since 'rnn' is not recognized outside RNNs
cell_net.Proto().type = 'simple'
# The last output is a list of step workspaces,
# which is only needed internally for gradient propogation
return results[:-1]
def set_rnn_executor_config(rnn_op, num_threads=None, max_cuda_streams=None):
from caffe2.proto import caffe2_pb2
assert rnn_op.type in {'RecurrentNetwork', 'RecurrentNetworkGradient'}
def add_arg(s, v):
a = caffe2_pb2.Argument()
a.name = "rnn_executor." + s
a.i = v
rnn_op.arg.extend([a])
if num_threads is not None:
add_arg('num_threads', num_threads)
if max_cuda_streams is not None:
add_arg('max_cuda_streams', max_cuda_streams)
def retrieve_step_blobs(net, prefix='rnn'):
'''
Retrieves blobs from step workspaces (which contain intermediate recurrent
network computation for each timestep) and puts them in the global
workspace. This allows access to the contents of this intermediate
computation in python. Returns the list of extracted blob names.
net: the net from which the step workspace blobs should be extracted
prefix: prefix to append to extracted blob names when placing them in the
global workspace
'''
count = 1
output_list = []
for op in net.Proto().op:
if op.type == "RecurrentNetwork":
blob_name = prefix + "_" + str(count)
count = count + 1
scratch_workspaces_blob_name = op.output[-1]
workspace.RunOperatorOnce(
core.CreateOperator(
"RecurrentNetworkBlobFetcher",
[scratch_workspaces_blob_name],
[blob_name],
prefix=prefix
)
)
output_list += workspace.FetchBlob(blob_name).tolist()
return output_list
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import numpy as np
class TestSparseToDense(TestCase):
def test_sparse_to_dense(self):
op = core.CreateOperator(
'SparseToDense',
['indices', 'values'],
['output'])
workspace.FeedBlob(
'indices',
np.array([2, 4, 999, 2], dtype=np.int32))
workspace.FeedBlob(
'values',
np.array([1, 2, 6, 7], dtype=np.int32))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
print(output)
expected = np.zeros(1000, dtype=np.int32)
expected[2] = 1 + 7
expected[4] = 2
expected[999] = 6
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
def test_sparse_to_dense_invalid_inputs(self):
op = core.CreateOperator(
'SparseToDense',
['indices', 'values'],
['output'])
workspace.FeedBlob(
'indices',
np.array([2, 4, 999, 2], dtype=np.int32))
workspace.FeedBlob(
'values',
np.array([1, 2, 6], dtype=np.int32))
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def test_sparse_to_dense_with_data_to_infer_dim(self):
op = core.CreateOperator(
'SparseToDense',
['indices', 'values', 'data_to_infer_dim'],
['output'])
workspace.FeedBlob(
'indices',
np.array([2, 4, 999, 2], dtype=np.int32))
workspace.FeedBlob(
'values',
np.array([1, 2, 6, 7], dtype=np.int32))
workspace.FeedBlob(
'data_to_infer_dim',
np.array(np.zeros(1500, ), dtype=np.int32))
workspace.RunOperatorOnce(op)
output = workspace.FetchBlob('output')
print(output)
expected = np.zeros(1500, dtype=np.int32)
expected[2] = 1 + 7
expected[4] = 2
expected[999] = 6
self.assertEqual(output.shape, expected.shape)
np.testing.assert_array_equal(output, expected)
|
## @package data_parallel_model_utils
# Module caffe2.python.data_parallel_model_utils
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from future.utils import viewitems, viewkeys, viewvalues
import logging
from caffe2.python import core
from caffe2.python.data_parallel_model import stripBlobName
log = logging.getLogger("data_parallel_model_utils")
log.setLevel(logging.INFO)
def GetActivationBlobs(model):
# Hacky way to get activations, think of a better way
activations = []
first_gpu_prefix = "{}_{}/".format(model._device_prefix, model._devices[0])
all_inputs = set()
for op in model.net.Proto().op:
for inp in op.input:
all_inputs.add(inp)
params = set(model.GetParams(''))
for op in model.net.Proto().op:
for b in op.output:
if b.startswith(first_gpu_prefix) and not b.endswith("_grad"):
if b in all_inputs and b not in params and b + "_grad" in all_inputs:
activations.append(stripBlobName(b))
return activations
def _ShiftActivationDevices(model, activations, from_device, to_device):
prefix = "{}_{}/".format(model._device_prefix, from_device)
activations = set([prefix + a for a in activations])
all_activations = set([prefix + a for a in GetActivationBlobs(model)])
ops = list(op for op in model.net.Proto().op if
op.device_option.cuda_gpu_id == from_device)
device_mapping = {a: to_device for a in activations}
device_mapping.update({b: from_device for b in all_activations if
b not in activations})
# Assign each blob to a device in a label propagation manner. activations
# override, and if multiple activations in same op, the output activations
# determine.
for op in ops:
op_device = None
for b in list(op.input) + list(op.output):
if b in device_mapping:
if b in all_activations or op_device is None:
op_device = device_mapping[b]
if op_device is None:
op_device = op.device_option.cuda_gpu_id
for b in list(op.input) + list(op.output):
if b not in device_mapping and b.startswith(prefix):
device_mapping[b] = op_device
op.device_option.cuda_gpu_id = op_device
# Change param_init_net accordingly
for op in model.param_init_net.Proto().op:
if op.output[0] in device_mapping:
op.device_option.cuda_gpu_id = device_mapping[op.output[0]]
def ShiftActivationDevices(model, activations, shifts):
'''
Function to enable simple model-parallellism for data_parallel_model
models. 'shifts' is a dictionary from_gpu -> to_gpu, and activations is
a list of activation blobs (wout gpu_x/ prefix -- use GetActivationBlobs()).
Operators handling these activations are shifted to the gpu declared in
'shifts'. Also related operators such as gradient operators will be moved.
Appropriate copy-ops are inserted.
This allows shifting memory usage from one gpu to another, enabling bigger
models to be trained.
'''
assert set(viewvalues(shifts)).intersection(set(viewkeys(shifts))) == set()
for from_device, to_device in viewitems(shifts):
log.info(
"Shifting {} activations from {} --> {}".
format(len(activations), from_device, to_device)
)
_ShiftActivationDevices(model, activations, from_device, to_device)
param_init_net, blob_to_device = core.InjectCrossDeviceCopies(model.param_init_net)
net, _blob_to_device = core.InjectCrossDeviceCopies(model.net, blob_to_device)
model.param_init_net = param_init_net
model.net = net
|
# @package regularizer_context
# Module caffe2.python.regularizer_context
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import context
from caffe2.python.modifier_context import (
ModifierContext, UseModifierBase)
@context.define_context(allow_default=True)
class RegularizerContext(ModifierContext):
"""
provide context to allow param_info to have different regularizers
"""
def has_regularizer(self, name):
return self._has_modifier(name)
def get_regularizer(self, name):
assert self.has_regularizer(name), (
"{} regularizer is not provided!".format(name))
return self._get_modifier(name)
class UseRegularizer(UseModifierBase):
'''
context class to allow setting the current context.
Example useage with layer:
regularizers = {'reg1': reg1, 'reg2': reg2}
with Regularizers(regularizers):
reg = RegularizerContext.current().get_regularizer('reg1')
layer(reg=reg)
'''
def _context_class(self):
return RegularizerContext
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import hypothesis.strategies as st
import caffe2.python.hypothesis_test_util as hu
from caffe2.python import workspace
from caffe2.python.functional import Functional
import numpy as np
@st.composite
def _tensor_splits(draw, add_axis=False):
"""Generates (axis, split_info, tensor_splits) tuples."""
tensor = draw(hu.tensor(min_value=4)) # Each dim has at least 4 elements.
axis = draw(st.integers(0, len(tensor.shape) - 1))
if add_axis:
# Simple case: get individual slices along one axis, where each of them
# is (N-1)-dimensional. The axis will be added back upon concatenation.
return (
axis, np.ones(tensor.shape[axis], dtype=np.int32), [
np.array(tensor.take(i, axis=axis))
for i in range(tensor.shape[axis])
]
)
else:
# General case: pick some (possibly consecutive, even non-unique)
# indices at which we will split the tensor, along the given axis.
splits = sorted(
draw(
st.
lists(elements=st.integers(0, tensor.shape[axis]), max_size=4)
) + [0, tensor.shape[axis]]
)
return (
axis, np.array(np.diff(splits), dtype=np.int32), [
tensor.take(range(splits[i], splits[i + 1]), axis=axis)
for i in range(len(splits) - 1)
],
)
class TestFunctional(hu.HypothesisTestCase):
@given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]))
def test_relu(self, X, engine):
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
output = Functional.Relu(X)
Y_l = output[0]
Y_d = output["output_0"]
with workspace.WorkspaceGuard("tmp_workspace"):
op = core.CreateOperator("Relu", ["X"], ["Y"], engine=engine)
workspace.FeedBlob("X", X)
workspace.RunOperatorOnce(op)
Y_ref = workspace.FetchBlob("Y")
np.testing.assert_array_equal(
Y_l, Y_ref, err_msg='Functional Relu result mismatch'
)
np.testing.assert_array_equal(
Y_d, Y_ref, err_msg='Functional Relu result mismatch'
)
@given(tensor_splits=_tensor_splits())
def test_concat(self, tensor_splits):
# Input Size: 1 -> inf
axis, _, splits = tensor_splits
concat_result, split_info = Functional.Concat(*splits, axis=axis)
concat_result_ref = np.concatenate(splits, axis=axis)
split_info_ref = np.array([a.shape[axis] for a in splits])
np.testing.assert_array_equal(
concat_result,
concat_result_ref,
err_msg='Functional Concat result mismatch'
)
np.testing.assert_array_equal(
split_info,
split_info_ref,
err_msg='Functional Concat split info mismatch'
)
@given(tensor_splits=_tensor_splits(), split_as_arg=st.booleans())
def test_split(self, tensor_splits, split_as_arg):
# Output Size: 1 - inf
axis, split_info, splits = tensor_splits
split_as_arg = True
if split_as_arg:
input_tensors = [np.concatenate(splits, axis=axis)]
kwargs = dict(axis=axis, split=split_info, num_output=len(splits))
else:
input_tensors = [np.concatenate(splits, axis=axis), split_info]
kwargs = dict(axis=axis, num_output=len(splits))
result = Functional.Split(*input_tensors, **kwargs)
def split_ref(input, split=split_info):
s = np.cumsum([0] + list(split))
return [
np.array(input.take(np.arange(s[i], s[i + 1]), axis=axis))
for i in range(len(split))
]
result_ref = split_ref(*input_tensors)
for i, ref in enumerate(result_ref):
np.testing.assert_array_equal(
result[i], ref, err_msg='Functional Relu result mismatch'
)
|
## @package control_ops_util
# Module caffe2.python.control_ops_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
def get_external_blob_names(net, lexical_scope):
"""
Returns a set of blobs a given net depends on and a set of
output blobs that are written by the net
Inputs:
net - net to return input/output blobs for;
lexical_scope - all external blob names visible to the net
"""
# Use the blobs that are actually read/written to as external inputs/outputs
net_proto = net.Proto()
net_ssa, _ = core.get_ssa(net_proto)
input_names = core.get_undefined_blobs(net_ssa)
for input_name in input_names:
assert str(input_name) in lexical_scope, \
"Input blob " + input_name + " is undefined"
output_names = set()
for op in net_proto.op:
for output in op.output:
if output in lexical_scope:
output_names.add(output)
return input_names, output_names
def add_if_op(if_net, cond_blob, lexical_scope, then_net, else_net=None):
"""
A helper function to add an If op to the net.
Automatically determines whether blobs in the then/else subnets are external
(from the outer workspace) or local (visible only inside subnet's workspace)
based on lexical scope - set of all outer blob names visible to the 'If'
operator. All the blobs in then/else subnets with names matching a name in lexical
scope and all the blobs that are first used as the operators' inputs are
considered outer blobs - these blobs must exist in the outer workspace,
then/else subnets can read their values and new values written into these blobs
will be visible outside of the 'If' operator. All other blobs are local - exist
only within inner workspaces for then/else.
Inputs:
if_net - net to add an If op to;
cond_blob - scalar bool blob reference, used as If condition;
lexical_scope - a set of outer blob names visible to then/else branches;
then_net/else_net - nets (core.Net) for then/else branches
"""
then_input_blob_names, then_output_blob_names = get_external_blob_names(
then_net, lexical_scope)
else_input_blob_names = set()
else_output_blob_names = set()
if else_net:
else_input_blob_names, else_output_blob_names = get_external_blob_names(
else_net, lexical_scope)
input_blob_names = then_input_blob_names | else_input_blob_names
output_blob_names = then_output_blob_names | else_output_blob_names
if_inputs = [cond_blob]
if_inputs += [core.BlobReference(name=b, net=None) for b in input_blob_names]
if_outputs = [core.BlobReference(name=b, net=None) for b in output_blob_names]
do_then_net = core.Net('do_then_net')
then_input_blobs = \
[core.BlobReference(name=b, net=None) for b in then_input_blob_names]
then_output_blobs = \
[core.BlobReference(name=b, net=None) for b in then_output_blob_names]
then_input_output_names_ordered = [
str(b) for b in (then_input_blobs + then_output_blobs)]
then_outer_blob_names = list(then_input_blob_names | then_output_blob_names)
then_outer_blob_names_idx = [
then_input_output_names_ordered.index(b) for b in then_outer_blob_names]
# make sure to use net's name to have unique blob name across multiple subnets
do_then_workspace_blob = if_net.NextScopedBlob(if_net.Name() + '/workspace_if_then')
then_input_blobs.append(do_then_workspace_blob)
then_output_blobs.append(do_then_workspace_blob)
# make sure that added workspace pointer blobs are in if inputs/outputs
if_inputs.append(do_then_workspace_blob)
if_outputs.append(do_then_workspace_blob)
do_then_net.Do(
then_input_blobs,
then_output_blobs,
net=then_net.Proto(),
inner_blobs=then_outer_blob_names,
outer_blobs_idx=then_outer_blob_names_idx)
do_then_net.AddExternalOutput(*then_output_blobs)
if_args = {}
if_args['then_net'] = do_then_net.Proto()
do_else_workspace_blob = None
if else_net:
do_else_net = core.Net('do_else_net')
else_input_blobs = \
[core.BlobReference(name=b, net=None) for b in else_input_blob_names]
else_output_blobs = \
[core.BlobReference(name=b, net=None) for b in else_output_blob_names]
else_input_output_names_ordered = [
str(b) for b in (else_input_blobs + else_output_blobs)]
else_outer_blob_names = list(else_input_blob_names | else_output_blob_names)
else_outer_blob_names_idx = [
else_input_output_names_ordered.index(b) for b in else_outer_blob_names]
do_else_workspace_blob = \
if_net.NextScopedBlob(if_net.Name() + '/workspace_if_else')
else_input_blobs.append(do_else_workspace_blob)
else_output_blobs.append(do_else_workspace_blob)
# make sure that added workspace pointer blobs are in if inputs/outputs
if_inputs.append(do_else_workspace_blob)
if_outputs.append(do_else_workspace_blob)
do_else_net.Do(
else_input_blobs,
else_output_blobs,
net=else_net.Proto(),
inner_blobs=else_outer_blob_names,
outer_blobs_idx=else_outer_blob_names_idx)
do_else_net.AddExternalOutput(*else_output_blobs)
if_args['else_net'] = do_else_net.Proto()
if_net.CreateScope([], [do_then_workspace_blob])
if do_else_workspace_blob:
if_net.CreateScope([], [do_else_workspace_blob])
if_net.If(if_inputs, if_outputs, **if_args)
if_net.AddExternalOutput(*if_outputs)
def add_while_op(
while_net, cond_blob, lexical_scope, loop_body_net, condition_body_net=None):
"""
A helper function to add a While op to the net. Same rules for determining
outer and inner blobs as for the 'If' operator apply for the 'While' operator
loop and condition subnets. If specified, condition net is executed in a separate
workspace before the first and after each iteration, the last operator must have
a single scalar boolean output that is written into the condition blob.
Inputs:
while_net - net to add a While op to;
cond_blob - scalar bool blob reference, used as a stop condition;
lexical_scope - a set of outer blob names visible to the loop's body;
loop_body_net - net to execute on each iteration;
condition_body_net - net to compute condition value
"""
input_blob_names, output_blob_names = get_external_blob_names(
loop_body_net, lexical_scope)
# Since it's possible that loop is not going to run even once
# we have to add loop's external outputs into inputs
input_blob_names |= output_blob_names
loop_inputs = [core.BlobReference(name=b, net=None) for b in input_blob_names]
loop_outputs = [core.BlobReference(name=b, net=None) for b in output_blob_names]
while_inputs = [cond_blob] + loop_inputs
while_outputs = [] + loop_outputs
do_loop_body_net = core.Net('do_loop_body_net')
loop_input_output_names_ordered = [
str(b) for b in (loop_inputs + loop_outputs)]
loop_body_outer_blob_names = list(input_blob_names | output_blob_names)
loop_body_outer_blob_names_idx = [
loop_input_output_names_ordered.index(b) for b in loop_body_outer_blob_names]
do_loop_body_workspace_blob = \
while_net.NextScopedBlob(while_net.Name() + '/workspace_loop_body')
loop_inputs.append(do_loop_body_workspace_blob)
loop_outputs.append(do_loop_body_workspace_blob)
# make sure that added workspace pointer blobs are in While inputs/outputs
while_inputs.append(do_loop_body_workspace_blob)
while_outputs.append(do_loop_body_workspace_blob)
do_loop_body_net.Do(
loop_inputs,
loop_outputs,
net=loop_body_net.Proto(),
inner_blobs=loop_body_outer_blob_names,
outer_blobs_idx=loop_body_outer_blob_names_idx,
copy_external_blobs=True)
do_loop_body_net.AddExternalOutput(*loop_outputs)
while_args = {}
while_args['loop_net'] = do_loop_body_net.Proto()
cond_workspace_blob = None
if condition_body_net:
cond_input_blob_names, cond_output_blob_names = get_external_blob_names(
condition_body_net, lexical_scope)
# make sure condition blob is written by condition net and is
# visible outside of it
found_condition_output = False
for op in condition_body_net.Proto().op:
if str(cond_blob) in op.output:
found_condition_output = True
break
assert found_condition_output, \
"Condition net does not write into condition blob"
if str(cond_blob) not in cond_output_blob_names:
cond_output_blob_names.add(str(cond_blob))
cond_inputs = [core.BlobReference(name=b, net=None)
for b in cond_input_blob_names]
assert str(cond_blob) in cond_output_blob_names, \
'Condition blob expected in condition net output'
cond_outputs = [core.BlobReference(name=b, net=None)
for b in cond_output_blob_names]
condition_net = core.Net('do_loop_condition_net')
cond_input_output_names_ordered = [
str(b) for b in (cond_inputs + cond_outputs)]
cond_body_outer_blob_names = \
list(cond_input_blob_names | cond_output_blob_names)
cond_body_outer_blob_names_idx = [
cond_input_output_names_ordered.index(b)
for b in cond_body_outer_blob_names]
cond_workspace_blob = \
while_net.NextScopedBlob(while_net.Name() + '/workspace_loop_cond')
cond_inputs.append(cond_workspace_blob)
cond_outputs.append(cond_workspace_blob)
condition_net.Do(
cond_inputs,
cond_outputs,
net=condition_body_net.Proto(),
inner_blobs=cond_body_outer_blob_names,
outer_blobs_idx=cond_body_outer_blob_names_idx)
condition_net.AddExternalOutput(*cond_outputs)
while_args['cond_net'] = condition_net.Proto()
while_inputs += [b for b in cond_inputs
if str(b) not in input_blob_names]
while_outputs += [b for b in cond_outputs
if str(b) not in output_blob_names]
if str(cond_blob) not in lexical_scope:
while_net.ConstantFill(
[],
cond_blob,
dtype=core.DataType.BOOL,
value=False)
while_net.CreateScope([], [do_loop_body_workspace_blob])
if cond_workspace_blob:
while_net.CreateScope([], [cond_workspace_blob])
while_net.While(while_inputs, while_outputs, **while_args)
while_net.AddExternalOutput(*while_outputs)
|
## @package control
# Module caffe2.python.control
"""
Implement functions for controlling execution of nets and steps, including
Do
DoParallel
For-loop
While-loop
Do-While-loop
Switch
If
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from future.utils import viewitems
# Used to generate names of the steps created by the control functions.
# It is actually the internal index of these steps.
_current_idx = 1
_used_step_names = set()
def _get_next_step_name(control_name, base_name):
global _current_idx, _used_step_names
concat_name = '%s/%s' % (base_name, control_name)
next_name = concat_name
while next_name in _used_step_names:
next_name = '%s_%d' % (concat_name, _current_idx)
_current_idx += 1
_used_step_names.add(next_name)
return next_name
def _MakeList(input):
""" input is a tuple.
Example:
(a, b, c) --> [a, b, c]
(a) --> [a]
([a, b, c]) --> [a, b, c]
"""
if len(input) == 0:
raise ValueError(
'input cannot be empty.')
elif len(input) == 1:
output = input[0]
if not isinstance(output, list):
output = [output]
else:
output = list(input)
return output
def _IsNets(nets_or_steps):
if isinstance(nets_or_steps, list):
return all(isinstance(n, core.Net) for n in nets_or_steps)
else:
return isinstance(nets_or_steps, core.Net)
def _PrependNets(nets_or_steps, *nets):
nets_or_steps = _MakeList((nets_or_steps,))
nets = _MakeList(nets)
if _IsNets(nets_or_steps):
return nets + nets_or_steps
else:
return [Do('prepend', nets)] + nets_or_steps
def _AppendNets(nets_or_steps, *nets):
nets_or_steps = _MakeList((nets_or_steps,))
nets = _MakeList(nets)
if _IsNets(nets_or_steps):
return nets_or_steps + nets
else:
return nets_or_steps + [Do('append', nets)]
def GetConditionBlobFromNet(condition_net):
"""
The condition blob is the last external_output that must
be a single bool
"""
assert len(condition_net.Proto().external_output) > 0, (
"Condition net %s must has at least one external output" %
condition_net.Proto.name)
# we need to use a blob reference here instead of a string
# otherwise, it will add another name_scope to the input later
# when we create new ops (such as OR of two inputs)
return core.BlobReference(condition_net.Proto().external_output[-1])
def BoolNet(*blobs_with_bool_value):
"""A net assigning constant bool values to blobs. It is mainly used for
initializing condition blobs, for example, in multi-task learning, we
need to access reader_done blobs before reader_net run. In that case,
the reader_done blobs must be initialized.
Args:
blobs_with_bool_value: one or more (blob, bool_value) pairs. The net will
assign each bool_value to the corresponding blob.
returns
bool_net: A net assigning constant bool values to blobs.
Examples:
- BoolNet((blob_1, bool_value_1), ..., (blob_n, bool_value_n))
- BoolNet([(blob_1, net1), ..., (blob_n, bool_value_n)])
- BoolNet((cond_1, bool_value_1))
"""
blobs_with_bool_value = _MakeList(blobs_with_bool_value)
bool_net = core.Net('bool_net')
for blob, bool_value in blobs_with_bool_value:
out_blob = bool_net.ConstantFill(
[],
[blob],
shape=[],
value=bool_value,
dtype=core.DataType.BOOL)
bool_net.AddExternalOutput(out_blob)
return bool_net
def NotNet(condition_blob_or_net):
"""Not of a condition blob or net
Args:
condition_blob_or_net can be either blob or net. If condition_blob_or_net
is Net, the condition is its last external_output
that must be a single bool.
returns
not_net: the net NOT the input
out_blob: the output blob of the not_net
"""
if isinstance(condition_blob_or_net, core.Net):
condition_blob = GetConditionBlobFromNet(condition_blob_or_net)
else:
condition_blob = condition_blob_or_net
not_net = core.Net('not_net')
out_blob = not_net.Not(condition_blob)
not_net.AddExternalOutput(out_blob)
return not_net, out_blob
def _CopyConditionBlobNet(condition_blob):
"""Make a condition net that copies the condition_blob
Args:
condition_blob is a single bool.
returns
not_net: the net NOT the input
out_blob: the output blob of the not_net
"""
condition_net = core.Net('copy_condition_blob_net')
out_blob = condition_net.Copy(condition_blob)
condition_net.AddExternalOutput(out_blob)
return condition_net, out_blob
def MergeConditionNets(name, condition_nets, relation):
"""
Merge multi condition nets into a single condition nets.
Args:
name: name of the new condition net.
condition_nets: a list of condition nets. The last external_output
of each condition net must be single bool value.
relation: can be 'And' or 'Or'.
Returns:
- A new condition net. Its last external output is relation of all
condition_nets.
"""
if not isinstance(condition_nets, list):
return condition_nets
if len(condition_nets) <= 1:
return condition_nets[0] if condition_nets else None
merged_net = core.Net(name)
for i in range(len(condition_nets)):
net_proto = condition_nets[i].Proto()
assert net_proto.device_option == merged_net.Proto().device_option
assert net_proto.type == merged_net.Proto().type
merged_net.Proto().op.extend(net_proto.op)
merged_net.Proto().external_input.extend(net_proto.external_input)
# discard external outputs as we're combining them together
curr_cond = GetConditionBlobFromNet(condition_nets[i])
if i == 0:
last_cond = curr_cond
else:
last_cond = merged_net.__getattr__(relation)([last_cond, curr_cond])
# merge attributes
for k, v in viewitems(condition_nets[i]._attr_dict):
merged_net._attr_dict[k] += v
merged_net.AddExternalOutput(last_cond)
return merged_net
def CombineConditions(name, condition_nets, relation):
"""
Combine conditions of multi nets into a single condition nets. Unlike
MergeConditionNets, the actual body of condition_nets is not copied into
the combine condition net.
One example is about multi readers. Each reader net has a reader_done
condition. When we want to check whether all readers are done, we can
use this function to build a new net.
Args:
name: name of the new condition net.
condition_nets: a list of condition nets. The last external_output
of each condition net must be single bool value.
relation: can be 'And' or 'Or'.
Returns:
- A new condition net. Its last external output is relation of all
condition_nets.
"""
if not condition_nets:
return None
if not isinstance(condition_nets, list):
raise ValueError('condition_nets must be a list of nets.')
if len(condition_nets) == 1:
condition_blob = GetConditionBlobFromNet(condition_nets[0])
condition_net, _ = _CopyConditionBlobNet(condition_blob)
return condition_net
combined_net = core.Net(name)
for i in range(len(condition_nets)):
curr_cond = GetConditionBlobFromNet(condition_nets[i])
if i == 0:
last_cond = curr_cond
else:
last_cond = combined_net.__getattr__(relation)(
[last_cond, curr_cond])
combined_net.AddExternalOutput(last_cond)
return combined_net
def Do(name, *nets_or_steps):
"""
Execute the sequence of nets or steps once.
Examples:
- Do('myDo', net1, net2, ..., net_n)
- Do('myDo', list_of_nets)
- Do('myDo', step1, step2, ..., step_n)
- Do('myDo', list_of_steps)
"""
nets_or_steps = _MakeList(nets_or_steps)
if (len(nets_or_steps) == 1 and isinstance(
nets_or_steps[0], core.ExecutionStep)):
return nets_or_steps[0]
else:
return core.scoped_execution_step(
_get_next_step_name('Do', name), nets_or_steps)
def DoParallel(name, *nets_or_steps):
"""
Execute the nets or steps in parallel, waiting for all of them to finish
Examples:
- DoParallel('pDo', net1, net2, ..., net_n)
- DoParallel('pDo', list_of_nets)
- DoParallel('pDo', step1, step2, ..., step_n)
- DoParallel('pDo', list_of_steps)
"""
nets_or_steps = _MakeList(nets_or_steps)
if (len(nets_or_steps) == 1 and isinstance(
nets_or_steps[0], core.ExecutionStep)):
return nets_or_steps[0]
else:
return core.scoped_execution_step(
_get_next_step_name('DoParallel', name),
nets_or_steps,
concurrent_substeps=True)
def _RunOnceIf(name, condition_blob_or_net, nets_or_steps):
"""
Execute nets_or_steps once if condition_blob_or_net evaluates as true.
If condition_blob_or_net is Net, the condition is its last external_output
that must be a single bool. And this net will be executed before
nets_or_steps so as to get the condition.
"""
condition_not_net, stop_blob = NotNet(condition_blob_or_net)
if isinstance(condition_blob_or_net, core.Net):
nets_or_steps = _PrependNets(
nets_or_steps, condition_blob_or_net, condition_not_net)
else:
nets_or_steps = _PrependNets(nets_or_steps, condition_not_net)
def if_step(control_name):
return core.scoped_execution_step(
_get_next_step_name(control_name, name),
nets_or_steps,
should_stop_blob=stop_blob,
only_once=True,
)
if _IsNets(nets_or_steps):
bool_net = BoolNet((stop_blob, False))
return Do(name + '/_RunOnceIf',
bool_net, if_step('_RunOnceIf-inner'))
else:
return if_step('_RunOnceIf')
def _RunOnceIfNot(name, condition_blob_or_net, nets_or_steps):
"""
Similar to _RunOnceIf() but Execute nets_or_steps once if
condition_blob_or_net evaluates as false.
"""
if isinstance(condition_blob_or_net, core.Net):
condition_blob = GetConditionBlobFromNet(condition_blob_or_net)
nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net)
else:
copy_net, condition_blob = _CopyConditionBlobNet(condition_blob_or_net)
nets_or_steps = _PrependNets(nets_or_steps, copy_net)
return core.scoped_execution_step(
_get_next_step_name('_RunOnceIfNot', name),
nets_or_steps,
should_stop_blob=condition_blob,
only_once=True,
)
def For(name, nets_or_steps, iter_num):
"""
Execute nets_or_steps iter_num times.
Args:
nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or
a list nets.
iter_num: the number times to execute the nets_or_steps.
Returns:
A ExecutionStep instance.
"""
init_net = core.Net('init-net')
iter_cnt = init_net.CreateCounter([], init_count=iter_num)
iter_net = core.Net('For-iter')
iter_done = iter_net.CountDown([iter_cnt])
for_step = core.scoped_execution_step(
_get_next_step_name('For-inner', name),
_PrependNets(nets_or_steps, iter_net),
should_stop_blob=iter_done)
return Do(name + '/For',
Do(name + '/For-init-net', init_net),
for_step)
def While(name, condition_blob_or_net, nets_or_steps):
"""
Execute nets_or_steps when condition_blob_or_net returns true.
Args:
condition_blob_or_net: If it is an instance of Net, its last
external_output must be a single bool.
nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or
a list nets.
Returns:
A ExecutionStep instance.
"""
condition_not_net, stop_blob = NotNet(condition_blob_or_net)
if isinstance(condition_blob_or_net, core.Net):
nets_or_steps = _PrependNets(
nets_or_steps, condition_blob_or_net, condition_not_net)
else:
nets_or_steps = _PrependNets(nets_or_steps, condition_not_net)
def while_step(control_name):
return core.scoped_execution_step(
_get_next_step_name(control_name, name),
nets_or_steps,
should_stop_blob=stop_blob,
)
if _IsNets(nets_or_steps):
# In this case, while_step has sub-nets:
# [condition_blob_or_net, condition_not_net, nets_or_steps]
# If stop_blob is pre-set to True (this may happen when While() is
# called twice), the loop will exit after executing
# condition_blob_or_net. So we use BootNet to set stop_blob to
# False.
bool_net = BoolNet((stop_blob, False))
return Do(name + '/While', bool_net, while_step('While-inner'))
else:
return while_step('While')
def Until(name, condition_blob_or_net, nets_or_steps):
"""
Similar to While() but execute nets_or_steps when
condition_blob_or_net returns false
"""
if isinstance(condition_blob_or_net, core.Net):
stop_blob = GetConditionBlobFromNet(condition_blob_or_net)
nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net)
else:
stop_blob = core.BlobReference(str(condition_blob_or_net))
return core.scoped_execution_step(
_get_next_step_name('Until', name),
nets_or_steps,
should_stop_blob=stop_blob)
def DoWhile(name, condition_blob_or_net, nets_or_steps):
"""
Execute nets_or_steps when condition_blob_or_net returns true. It will
execute nets_or_steps before evaluating condition_blob_or_net.
Args:
condition_blob_or_net: if it is an instance of Net, tts last external_output
must be a single bool.
nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or
a list nets.
Returns:
A ExecutionStep instance.
"""
condition_not_net, stop_blob = NotNet(condition_blob_or_net)
if isinstance(condition_blob_or_net, core.Net):
nets_or_steps = _AppendNets(
nets_or_steps, condition_blob_or_net, condition_not_net)
else:
nets_or_steps = _AppendNets(nets_or_steps, condition_not_net)
# If stop_blob is pre-set to True (this may happen when DoWhile() is
# called twice), the loop will exit after executing the first net/step
# in nets_or_steps. This is not what we want. So we use BootNet to
# set stop_blob to False.
bool_net = BoolNet((stop_blob, False))
return Do(name + '/DoWhile', bool_net, core.scoped_execution_step(
_get_next_step_name('DoWhile-inner', name),
nets_or_steps,
should_stop_blob=stop_blob,
))
def DoUntil(name, condition_blob_or_net, nets_or_steps):
"""
Similar to DoWhile() but execute nets_or_steps when
condition_blob_or_net returns false. It will execute
nets_or_steps before evaluating condition_blob_or_net.
Special case: if condition_blob_or_net is a blob and is pre-set to
true, then only the first net/step of nets_or_steps will be executed and
loop is exited. So you need to be careful about the initial value the
condition blob when using DoUntil(), esp when DoUntil() is called twice.
"""
if not isinstance(condition_blob_or_net, core.Net):
stop_blob = core.BlobReference(condition_blob_or_net)
return core.scoped_execution_step(
_get_next_step_name('DoUntil', name),
nets_or_steps,
should_stop_blob=stop_blob)
nets_or_steps = _AppendNets(nets_or_steps, condition_blob_or_net)
stop_blob = GetConditionBlobFromNet(condition_blob_or_net)
# If stop_blob is pre-set to True (this may happen when DoWhile() is
# called twice), the loop will exit after executing the first net/step
# in nets_or_steps. This is not what we want. So we use BootNet to
# set stop_blob to False.
bool_net = BoolNet((stop_blob, False))
return Do(name + '/DoUntil', bool_net, core.scoped_execution_step(
_get_next_step_name('DoUntil-inner', name),
nets_or_steps,
should_stop_blob=stop_blob,
))
def Switch(name, *conditions):
"""
Execute the steps for which the condition is true.
Each condition is a tuple (condition_blob_or_net, nets_or_steps).
Note:
1. Multi steps can be executed if their conditions are true.
2. The conditions_blob_or_net (if it is Net) of all steps will be
executed once.
Examples:
- Switch('name', (cond_1, net_1), (cond_2, net_2), ..., (cond_n, net_n))
- Switch('name', [(cond_1, net1), (cond_2, net_2), ..., (cond_n, net_n)])
- Switch('name', (cond_1, net_1))
"""
conditions = _MakeList(conditions)
return core.scoped_execution_step(
_get_next_step_name('Switch', name),
[_RunOnceIf(name + '/Switch', cond, step) for cond, step in conditions])
def SwitchNot(name, *conditions):
"""
Similar to Switch() but execute the steps for which the condition is False.
"""
conditions = _MakeList(conditions)
return core.scoped_execution_step(
_get_next_step_name('SwitchNot', name),
[_RunOnceIfNot(name + '/SwitchNot', cond, step)
for cond, step in conditions])
def If(name, condition_blob_or_net,
true_nets_or_steps, false_nets_or_steps=None):
"""
condition_blob_or_net is first evaluated or executed. If the condition is
true, true_nets_or_steps is then executed, otherwise, false_nets_or_steps
is executed.
If condition_blob_or_net is Net, the condition is its last external_output
that must be a single bool. And this Net will be executred before both
true/false_nets_or_steps so as to get the condition.
"""
if not false_nets_or_steps:
return _RunOnceIf(name + '/If',
condition_blob_or_net, true_nets_or_steps)
if isinstance(condition_blob_or_net, core.Net):
condition_blob = GetConditionBlobFromNet(condition_blob_or_net)
else:
condition_blob = condition_blob_or_net
return Do(
name + '/If',
_RunOnceIf(name + '/If-true',
condition_blob_or_net, true_nets_or_steps),
_RunOnceIfNot(name + '/If-false', condition_blob, false_nets_or_steps)
)
def IfNot(name, condition_blob_or_net,
true_nets_or_steps, false_nets_or_steps=None):
"""
If condition_blob_or_net returns false, executes true_nets_or_steps,
otherwise executes false_nets_or_steps
"""
if not false_nets_or_steps:
return _RunOnceIfNot(name + '/IfNot',
condition_blob_or_net, true_nets_or_steps)
if isinstance(condition_blob_or_net, core.Net):
condition_blob = GetConditionBlobFromNet(condition_blob_or_net)
else:
condition_blob = condition_blob_or_net
return Do(
name + '/IfNot',
_RunOnceIfNot(name + '/IfNot-true',
condition_blob_or_net, true_nets_or_steps),
_RunOnceIf(name + '/IfNot-false', condition_blob, false_nets_or_steps)
)
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from hypothesis import given
import hypothesis.strategies as st
from multiprocessing import Process
import numpy as np
import tempfile
import shutil
import caffe2.python.hypothesis_test_util as hu
op_engine = 'GLOO'
class TemporaryDirectory:
def __enter__(self):
self.tmpdir = tempfile.mkdtemp()
return self.tmpdir
def __exit__(self, type, value, traceback):
shutil.rmtree(self.tmpdir)
def allcompare_process(filestore_dir, process_id, data, num_procs):
from caffe2.python import core, data_parallel_model, workspace, dyndep
from caffe2.python.model_helper import ModelHelper
from caffe2.proto import caffe2_pb2
dyndep.InitOpsLibrary("@/caffe2/caffe2/distributed:file_store_handler_ops")
workspace.RunOperatorOnce(
core.CreateOperator(
"FileStoreHandlerCreate", [], ["store_handler"], path=filestore_dir
)
)
rendezvous = dict(
kv_handler="store_handler",
shard_id=process_id,
num_shards=num_procs,
engine=op_engine,
exit_nets=None
)
model = ModelHelper()
model._rendezvous = rendezvous
workspace.FeedBlob("test_data", data)
data_parallel_model._RunComparison(
model, "test_data", core.DeviceOption(caffe2_pb2.CPU, 0)
)
class TestAllCompare(hu.HypothesisTestCase):
@given(
d=st.integers(1, 5), n=st.integers(2, 11), num_procs=st.integers(1, 8)
)
def test_allcompare(self, d, n, num_procs):
dims = []
for _ in range(d):
dims.append(np.random.randint(1, high=n))
test_data = np.random.ranf(size=tuple(dims)).astype(np.float32)
with TemporaryDirectory() as tempdir:
processes = []
for idx in range(num_procs):
process = Process(
target=allcompare_process,
args=(tempdir, idx, test_data, num_procs)
)
processes.append(process)
process.start()
while len(processes) > 0:
process = processes.pop()
process.join()
if __name__ == "__main__":
import unittest
unittest.main()
|
## @package timeout_guard
# Module caffe2.python.timeout_guard
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import contextlib
import threading
import os
import time
import signal
import logging
from future.utils import viewitems
'''
Sometimes CUDA devices can get stuck, 'deadlock'. In this case it is often
better just the kill the process automatically. Use this guard to set a
maximum timespan for a python call, such as RunNet(). If it does not complete
in time, process is killed.
Example usage:
with timeout_guard.CompleteInTimeOrDie(10.0):
core.RunNet(...)
'''
class WatcherThread(threading.Thread):
def __init__(self, timeout_secs):
threading.Thread.__init__(self)
self.timeout_secs = timeout_secs
self.completed = False
self.condition = threading.Condition()
self.daemon = True
self.caller_thread = threading.current_thread()
def run(self):
started = time.time()
self.condition.acquire()
while time.time() - started < self.timeout_secs and not self.completed:
self.condition.wait(self.timeout_secs - (time.time() - started))
self.condition.release()
if not self.completed:
log = logging.getLogger("timeout_guard")
log.error("Call did not finish in time. Timeout:{}s PID: {}".format(
self.timeout_secs,
os.getpid(),
))
# First try dying cleanly, but in 10 secs, exit properly
def forcequit():
time.sleep(10.0)
log.info("Prepared output, dumping threads. ")
print("Caller thread was: {}".format(self.caller_thread))
print("-----After force------")
import sys
import traceback
code = []
for threadId, stack in viewitems(sys._current_frames()):
if threadId == self.caller_thread.ident:
code.append("\n# ThreadID: %s" % threadId)
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print("\n".join(code))
log.error("Process did not terminate cleanly in 10 s, forcing")
os.abort()
forcet = threading.Thread(target=forcequit, args=())
forcet.daemon = True
forcet.start()
print("Caller thread was: {}".format(self.caller_thread))
print("-----Before forcing------")
import sys
import traceback
code = []
for threadId, stack in viewitems(sys._current_frames()):
code.append("\n# ThreadID: %s" % threadId)
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print("\n".join(code))
os.kill(os.getpid(), signal.SIGINT)
@contextlib.contextmanager
def CompleteInTimeOrDie(timeout_secs):
watcher = WatcherThread(timeout_secs)
watcher.start()
yield
watcher.completed = True
watcher.condition.acquire()
watcher.condition.notify()
watcher.condition.release()
def EuthanizeIfNecessary(timeout_secs=120):
'''
Call this if you have problem with process getting stuck at shutdown.
It will kill the process if it does not terminate in timeout_secs.
'''
watcher = WatcherThread(timeout_secs)
watcher.start()
|
# @package modifier_context
# Module caffe2.python.modifier_context
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
DEFAULT_MODIFIER = 'DEFAULT'
class ModifierContext(object):
"""
provide context to allow param_info to have different modifiers
"""
def __init__(self):
self._modifiers = {}
self._modifiers_list = []
def _rebuild_modifiers(self):
self._modifiers = {}
for m in self._modifiers_list:
self._modifiers.update(m)
def _has_modifier(self, name):
return name in self._modifiers
def _get_modifier(self, name):
return self._modifiers.get(name)
def push_modifiers(self, modifiers):
# modifier override is allowed
self._modifiers_list.append(modifiers)
self._modifiers.update(modifiers)
def pop_modifiers(self):
assert len(self._modifiers_list) > 0
self._modifiers_list.pop()
self._rebuild_modifiers()
class UseModifierBase(object):
'''
context class to allow setting the current context.
Example useage with layer:
modifiers = {'modifier1': modifier1, 'modifier2': modifier2}
with Modifiers(modifiers):
modifier = ModifierContext.current().get_modifier('modifier1')
layer(modifier=modifier)
'''
def __init__(self, modifier_or_dict):
if isinstance(modifier_or_dict, dict):
self._modifiers = modifier_or_dict
else:
self._modifiers = {DEFAULT_MODIFIER: modifier_or_dict}
def _context_class(self):
raise NotImplementedError
def __enter__(self):
self._context_class().current().push_modifiers(self._modifiers)
return self
def __exit__(self, type, value, traceback):
self._context_class().current().pop_modifiers()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import os
import unittest
from caffe2.proto import caffe2_pb2
from caffe2.python import core, test_util, workspace, model_helper, brew
import caffe2.python.hypothesis_test_util as htu
import hypothesis.strategies as st
from hypothesis import given
class TestWorkspace(unittest.TestCase):
def setUp(self):
self.net = core.Net("test-net")
self.testblob_ref = self.net.ConstantFill(
[], "testblob", shape=[1, 2, 3, 4], value=1.0)
workspace.ResetWorkspace()
def testRootFolder(self):
self.assertEqual(workspace.ResetWorkspace(), True)
self.assertEqual(workspace.RootFolder(), ".")
self.assertEqual(
workspace.ResetWorkspace("/tmp/caffe-workspace-test"), True)
self.assertEqual(workspace.RootFolder(), "/tmp/caffe-workspace-test")
def testWorkspaceHasBlobWithNonexistingName(self):
self.assertEqual(workspace.HasBlob("non-existing"), False)
def testRunOperatorOnce(self):
self.assertEqual(
workspace.RunOperatorOnce(
self.net.Proto().op[0].SerializeToString()
), True
)
self.assertEqual(workspace.HasBlob("testblob"), True)
blobs = workspace.Blobs()
self.assertEqual(len(blobs), 1)
self.assertEqual(blobs[0], "testblob")
def testGetOperatorCost(self):
op = core.CreateOperator(
"Conv2D",
["X", "W"], ["Y"],
stride_h=1,
stride_w=1,
pad_t=1,
pad_l=1,
pad_b=1,
pad_r=1,
kernel=3,
)
X = np.zeros((1, 8, 8, 8))
W = np.zeros((1, 1, 3, 3))
workspace.FeedBlob("X", X)
workspace.FeedBlob("W", W)
flops, _ = workspace.GetOperatorCost(op.SerializeToString(), ["X", "W"])
self.assertEqual(flops, 1152)
def testRunNetOnce(self):
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
self.assertEqual(workspace.HasBlob("testblob"), True)
def testCurrentWorkspaceWrapper(self):
self.assertNotIn("testblob", workspace.C.Workspace.current.blobs)
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
self.assertEqual(workspace.HasBlob("testblob"), True)
self.assertIn("testblob", workspace.C.Workspace.current.blobs)
workspace.ResetWorkspace()
self.assertNotIn("testblob", workspace.C.Workspace.current.blobs)
def testRunPlan(self):
plan = core.Plan("test-plan")
plan.AddStep(core.ExecutionStep("test-step", self.net))
self.assertEqual(
workspace.RunPlan(plan.Proto().SerializeToString()), True)
self.assertEqual(workspace.HasBlob("testblob"), True)
def testConstructPlanFromSteps(self):
step = core.ExecutionStep("test-step-as-plan", self.net)
self.assertEqual(workspace.RunPlan(step), True)
self.assertEqual(workspace.HasBlob("testblob"), True)
def testResetWorkspace(self):
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
self.assertEqual(workspace.HasBlob("testblob"), True)
self.assertEqual(workspace.ResetWorkspace(), True)
self.assertEqual(workspace.HasBlob("testblob"), False)
def testTensorAccess(self):
ws = workspace.C.Workspace()
""" test in-place modification """
ws.create_blob("tensor").feed(np.array([1.1, 1.2, 1.3]))
tensor = ws.blobs["tensor"].tensor()
tensor.data[0] = 3.3
val = np.array([3.3, 1.2, 1.3])
np.testing.assert_array_equal(tensor.data, val)
np.testing.assert_array_equal(ws.blobs["tensor"].fetch(), val)
""" test in-place initialization """
tensor.init([2, 3], core.DataType.INT32)
tensor.data[1, 1] = 100
val = np.zeros([2, 3], dtype=np.int32)
val[1, 1] = 100
np.testing.assert_array_equal(tensor.data, val)
np.testing.assert_array_equal(ws.blobs["tensor"].fetch(), val)
""" strings cannot be initialized from python """
with self.assertRaises(RuntimeError):
tensor.init([3, 4], core.DataType.STRING)
""" feed (copy) data into tensor """
val = np.array([[b'abc', b'def'], [b'ghi', b'jkl']], dtype=np.object)
tensor.feed(val)
self.assertEquals(tensor.data[0, 0], b'abc')
np.testing.assert_array_equal(ws.blobs["tensor"].fetch(), val)
val = np.array([1.1, 10.2])
tensor.feed(val)
val[0] = 5.2
self.assertEquals(tensor.data[0], 1.1)
""" fetch (copy) data from tensor """
val = np.array([1.1, 1.2])
tensor.feed(val)
val2 = tensor.fetch()
tensor.data[0] = 5.2
val3 = tensor.fetch()
np.testing.assert_array_equal(val, val2)
self.assertEquals(val3[0], 5.2)
def testFetchFeedBlob(self):
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
fetched = workspace.FetchBlob("testblob")
# check if fetched is correct.
self.assertEqual(fetched.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched, 1.0)
fetched[:] = 2.0
self.assertEqual(workspace.FeedBlob("testblob", fetched), True)
fetched_again = workspace.FetchBlob("testblob")
self.assertEqual(fetched_again.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched_again, 2.0)
def testFetchFeedBlobViaBlobReference(self):
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
fetched = workspace.FetchBlob(self.testblob_ref)
# check if fetched is correct.
self.assertEqual(fetched.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched, 1.0)
fetched[:] = 2.0
self.assertEqual(workspace.FeedBlob(self.testblob_ref, fetched), True)
fetched_again = workspace.FetchBlob("testblob") # fetch by name now
self.assertEqual(fetched_again.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched_again, 2.0)
def testFetchFeedBlobTypes(self):
for dtype in [np.float16, np.float32, np.float64, np.bool,
np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16]:
try:
rng = np.iinfo(dtype).max * 2
except ValueError:
rng = 1000
data = ((np.random.rand(2, 3, 4) - 0.5) * rng).astype(dtype)
self.assertEqual(workspace.FeedBlob("testblob_types", data), True)
fetched_back = workspace.FetchBlob("testblob_types")
self.assertEqual(fetched_back.shape, (2, 3, 4))
self.assertEqual(fetched_back.dtype, dtype)
np.testing.assert_array_equal(fetched_back, data)
def testFetchFeedBlobBool(self):
"""Special case for bool to ensure coverage of both true and false."""
data = np.zeros((2, 3, 4)).astype(np.bool)
data.flat[::2] = True
self.assertEqual(workspace.FeedBlob("testblob_types", data), True)
fetched_back = workspace.FetchBlob("testblob_types")
self.assertEqual(fetched_back.shape, (2, 3, 4))
self.assertEqual(fetched_back.dtype, np.bool)
np.testing.assert_array_equal(fetched_back, data)
def testFetchFeedBlobZeroDim(self):
data = np.empty(shape=(2, 0, 3), dtype=np.float32)
self.assertEqual(workspace.FeedBlob("testblob_empty", data), True)
fetched_back = workspace.FetchBlob("testblob_empty")
self.assertEqual(fetched_back.shape, (2, 0, 3))
self.assertEqual(fetched_back.dtype, np.float32)
def testFetchFeedLongStringTensor(self):
# long strings trigger array of object creation
strs = np.array([
b' '.join(10 * [b'long string']),
b' '.join(128 * [b'very long string']),
b'small \0\1\2 string',
b"Hello, world! I have special \0 symbols \1!"])
workspace.FeedBlob('my_str_tensor', strs)
strs2 = workspace.FetchBlob('my_str_tensor')
self.assertEqual(strs.shape, strs2.shape)
for i in range(0, strs.shape[0]):
self.assertEqual(strs[i], strs2[i])
def testFetchFeedShortStringTensor(self):
# small strings trigger NPY_STRING array
strs = np.array([b'elem1', b'elem 2', b'element 3'])
workspace.FeedBlob('my_str_tensor_2', strs)
strs2 = workspace.FetchBlob('my_str_tensor_2')
self.assertEqual(strs.shape, strs2.shape)
for i in range(0, strs.shape[0]):
self.assertEqual(strs[i], strs2[i])
def testFetchFeedPlainString(self):
# this is actual string, not a tensor of strings
s = b"Hello, world! I have special \0 symbols \1!"
workspace.FeedBlob('my_plain_string', s)
s2 = workspace.FetchBlob('my_plain_string')
self.assertEqual(s, s2)
def testFetchBlobs(self):
s1 = b"test1"
s2 = b"test2"
workspace.FeedBlob('s1', s1)
workspace.FeedBlob('s2', s2)
fetch1, fetch2 = workspace.FetchBlobs(['s1', 's2'])
self.assertEquals(s1, fetch1)
self.assertEquals(s2, fetch2)
def testFetchFeedViaBlobDict(self):
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
fetched = workspace.blobs["testblob"]
# check if fetched is correct.
self.assertEqual(fetched.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched, 1.0)
fetched[:] = 2.0
workspace.blobs["testblob"] = fetched
fetched_again = workspace.blobs["testblob"]
self.assertEqual(fetched_again.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched_again, 2.0)
self.assertTrue("testblob" in workspace.blobs)
self.assertFalse("non_existant" in workspace.blobs)
self.assertEqual(len(workspace.blobs), 1)
for key in workspace.blobs:
self.assertEqual(key, "testblob")
class TestMultiWorkspaces(unittest.TestCase):
def setUp(self):
workspace.SwitchWorkspace("default")
workspace.ResetWorkspace()
def testCreateWorkspace(self):
self.net = core.Net("test-net")
self.net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0)
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True
)
self.assertEqual(workspace.HasBlob("testblob"), True)
self.assertEqual(workspace.SwitchWorkspace("test", True), None)
self.assertEqual(workspace.HasBlob("testblob"), False)
self.assertEqual(workspace.SwitchWorkspace("default"), None)
self.assertEqual(workspace.HasBlob("testblob"), True)
try:
# The following should raise an error.
workspace.SwitchWorkspace("non-existing")
# so this should never happen.
self.assertEqual(True, False)
except RuntimeError:
pass
workspaces = workspace.Workspaces()
self.assertTrue("default" in workspaces)
self.assertTrue("test" in workspaces)
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support.")
class TestWorkspaceGPU(test_util.TestCase):
def setUp(self):
workspace.ResetWorkspace()
self.net = core.Net("test-net")
self.net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0)
self.net.RunAllOnGPU()
def testFetchBlobGPU(self):
self.assertEqual(
workspace.RunNetOnce(self.net.Proto().SerializeToString()), True)
fetched = workspace.FetchBlob("testblob")
# check if fetched is correct.
self.assertEqual(fetched.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched, 1.0)
fetched[:] = 2.0
self.assertEqual(workspace.FeedBlob("testblob", fetched), True)
fetched_again = workspace.FetchBlob("testblob")
self.assertEqual(fetched_again.shape, (1, 2, 3, 4))
np.testing.assert_array_equal(fetched_again, 2.0)
def testGetCudaPeerAccessPattern(self):
pattern = workspace.GetCudaPeerAccessPattern()
self.assertEqual(type(pattern), np.ndarray)
self.assertEqual(pattern.ndim, 2)
self.assertEqual(pattern.shape[0], pattern.shape[1])
self.assertEqual(pattern.shape[0], workspace.NumCudaDevices())
@unittest.skipIf(not workspace.C.has_mkldnn, "No MKLDNN support.")
class TestWorkspaceMKLDNN(test_util.TestCase):
def testFeedFetchBlobMKLDNN(self):
arr = np.random.randn(2, 3).astype(np.float32)
workspace.FeedBlob(
"testblob_mkldnn", arr, core.DeviceOption(caffe2_pb2.MKLDNN))
fetched = workspace.FetchBlob("testblob_mkldnn")
np.testing.assert_array_equal(arr, fetched)
class TestImmedibate(test_util.TestCase):
def testImmediateEnterExit(self):
workspace.StartImmediate(i_know=True)
self.assertTrue(workspace.IsImmediate())
workspace.StopImmediate()
self.assertFalse(workspace.IsImmediate())
def testImmediateRunsCorrectly(self):
workspace.StartImmediate(i_know=True)
net = core.Net("test-net")
net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0)
self.assertEqual(
workspace.ImmediateBlobs(), ["testblob"])
content = workspace.FetchImmediate("testblob")
# Also, the immediate mode should not invade the original namespace,
# so we check if this is so.
with self.assertRaises(RuntimeError):
workspace.FetchBlob("testblob")
np.testing.assert_array_equal(content, 1.0)
content[:] = 2.0
self.assertTrue(workspace.FeedImmediate("testblob", content))
np.testing.assert_array_equal(
workspace.FetchImmediate("testblob"), 2.0)
workspace.StopImmediate()
with self.assertRaises(RuntimeError):
content = workspace.FetchImmediate("testblob")
def testImmediateRootFolder(self):
workspace.StartImmediate(i_know=True)
# for testing we will look into the _immediate_root_folder variable
# but in normal usage you should not access that.
self.assertTrue(len(workspace._immediate_root_folder) > 0)
root_folder = workspace._immediate_root_folder
self.assertTrue(os.path.isdir(root_folder))
workspace.StopImmediate()
self.assertTrue(len(workspace._immediate_root_folder) == 0)
# After termination, immediate mode should have the root folder
# deleted.
self.assertFalse(os.path.exists(root_folder))
class TestCppEnforceAsException(test_util.TestCase):
def testEnforce(self):
op = core.CreateOperator("Relu", ["X"], ["Y"])
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
class TestCWorkspace(htu.HypothesisTestCase):
def test_net_execution(self):
ws = workspace.C.Workspace()
self.assertEqual(ws.nets, {})
self.assertEqual(ws.blobs, {})
net = core.Net("test-net")
net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0)
ws.create_net(net)
# If we do not specify overwrite, this should raise an error.
with self.assertRaises(RuntimeError):
ws.create_net(net)
# But, if we specify overwrite, this should pass.
ws.create_net(net, True)
# Overwrite can also be a kwarg.
ws.create_net(net, overwrite=True)
self.assertIn("testblob", ws.blobs)
self.assertEqual(len(ws.nets), 1)
net_name = net.Proto().name
self.assertIn("test-net", net_name)
net = ws.nets[net_name].run()
blob = ws.blobs["testblob"]
np.testing.assert_array_equal(
np.ones((1, 2, 3, 4), dtype=np.float32),
blob.fetch())
@given(name=st.text(), value=st.floats(min_value=-1, max_value=1.0))
def test_operator_run(self, name, value):
ws = workspace.C.Workspace()
op = core.CreateOperator(
"ConstantFill", [], [name], shape=[1], value=value)
ws.run(op)
self.assertIn(name, ws.blobs)
np.testing.assert_allclose(
[value], ws.blobs[name].fetch(), atol=1e-4, rtol=1e-4)
@given(blob_name=st.text(),
net_name=st.text(),
value=st.floats(min_value=-1, max_value=1.0))
def test_net_run(self, blob_name, net_name, value):
ws = workspace.C.Workspace()
net = core.Net(net_name)
net.ConstantFill([], [blob_name], shape=[1], value=value)
ws.run(net)
self.assertIn(blob_name, ws.blobs)
self.assertNotIn(net_name, ws.nets)
np.testing.assert_allclose(
[value], ws.blobs[blob_name].fetch(), atol=1e-4, rtol=1e-4)
@given(blob_name=st.text(),
net_name=st.text(),
plan_name=st.text(),
value=st.floats(min_value=-1, max_value=1.0))
def test_plan_run(self, blob_name, plan_name, net_name, value):
ws = workspace.C.Workspace()
plan = core.Plan(plan_name)
net = core.Net(net_name)
net.ConstantFill([], [blob_name], shape=[1], value=value)
plan.AddStep(core.ExecutionStep("step", nets=[net], num_iter=1))
ws.run(plan)
self.assertIn(blob_name, ws.blobs)
self.assertIn(net.Name(), ws.nets)
np.testing.assert_allclose(
[value], ws.blobs[blob_name].fetch(), atol=1e-4, rtol=1e-4)
@given(blob_name=st.text(),
net_name=st.text(),
value=st.floats(min_value=-1, max_value=1.0))
def test_net_create(self, blob_name, net_name, value):
ws = workspace.C.Workspace()
net = core.Net(net_name)
net.ConstantFill([], [blob_name], shape=[1], value=value)
ws.create_net(net).run()
self.assertIn(blob_name, ws.blobs)
self.assertIn(net.Name(), ws.nets)
np.testing.assert_allclose(
[value], ws.blobs[blob_name].fetch(), atol=1e-4, rtol=1e-4)
@given(name=st.text(),
value=htu.tensor(),
device_option=st.sampled_from(htu.device_options))
def test_array_serde(self, name, value, device_option):
ws = workspace.C.Workspace()
ws.create_blob(name).feed(value, device_option=device_option)
self.assertIn(name, ws.blobs)
blob = ws.blobs[name]
np.testing.assert_equal(value, ws.blobs[name].fetch())
serde_blob = ws.create_blob("{}_serde".format(name))
serde_blob.deserialize(blob.serialize(name))
np.testing.assert_equal(value, serde_blob.fetch())
@given(name=st.text(), value=st.text())
def test_string_serde(self, name, value):
value = value.encode('ascii', 'ignore')
ws = workspace.C.Workspace()
ws.create_blob(name).feed(value)
self.assertIn(name, ws.blobs)
blob = ws.blobs[name]
self.assertEqual(value, ws.blobs[name].fetch())
serde_blob = ws.create_blob("{}_serde".format(name))
serde_blob.deserialize(blob.serialize(name))
self.assertEqual(value, serde_blob.fetch())
def test_exception(self):
ws = workspace.C.Workspace()
with self.assertRaises(TypeError):
ws.create_net("...")
class TestPredictor(unittest.TestCase):
def _create_model(self):
m = model_helper.ModelHelper()
y = brew.fc(m, "data", "y",
dim_in=4, dim_out=2,
weight_init=('ConstantFill', dict(value=1.0)),
bias_init=('ConstantFill', dict(value=0.0)),
axis=0)
m.net.AddExternalOutput(y)
return m
# Use this test with a bigger model to see how using Predictor allows to
# avoid issues with low protobuf size limit in Python
#
# def test_predictor_predefined(self):
# workspace.ResetWorkspace()
# path = 'caffe2/caffe2/test/assets/'
# with open(path + 'squeeze_predict_net.pb') as f:
# self.predict_net = f.read()
# with open(path + 'squeeze_init_net.pb') as f:
# self.init_net = f.read()
# self.predictor = workspace.Predictor(self.init_net, self.predict_net)
# inputs = [np.zeros((1, 3, 256, 256), dtype='f')]
# outputs = self.predictor.run(inputs)
# self.assertEqual(len(outputs), 1)
# self.assertEqual(outputs[0].shape, (1, 1000, 1, 1))
# self.assertAlmostEqual(outputs[0][0][0][0][0], 5.19026289e-05)
def test_predictor_memory_model(self):
workspace.ResetWorkspace()
m = self._create_model()
workspace.FeedBlob("data", np.zeros([4], dtype='float32'))
self.predictor = workspace.Predictor(
workspace.StringifyProto(m.param_init_net.Proto()),
workspace.StringifyProto(m.net.Proto()))
inputs = np.array([1, 3, 256, 256], dtype='float32')
outputs = self.predictor.run([inputs])
np.testing.assert_array_almost_equal(
np.array([[516, 516]], dtype='float32'), outputs)
class TestTransform(htu.HypothesisTestCase):
@given(input_dim=st.integers(min_value=1, max_value=10),
output_dim=st.integers(min_value=1, max_value=10),
batch_size=st.integers(min_value=1, max_value=10))
def test_simple_transform(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
fc1 = brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
fc2 = brew.fc(m, fc1, "fc2", dim_in=output_dim, dim_out=output_dim)
conv = brew.conv(m, fc2, "conv",
dim_in=output_dim,
dim_out=output_dim,
use_cudnn=True,
engine="CUDNN",
kernel=3)
conv.Relu([], conv)\
.Softmax([], "pred") \
.LabelCrossEntropy(["label"], ["xent"]) \
.AveragedLoss([], "loss")
transformed_net_proto = workspace.ApplyTransform(
"ConvToNNPack",
m.net.Proto())
self.assertEqual(transformed_net_proto.op[2].engine, "NNPACK")
@given(input_dim=st.integers(min_value=1, max_value=10),
output_dim=st.integers(min_value=1, max_value=10),
batch_size=st.integers(min_value=1, max_value=10))
def test_registry_invalid(self, input_dim, output_dim, batch_size):
m = model_helper.ModelHelper()
brew.fc(m, "data", "fc1", dim_in=input_dim, dim_out=output_dim)
with self.assertRaises(RuntimeError):
workspace.ApplyTransform(
"definitely_not_a_real_transform",
m.net.Proto())
@given(value=st.floats(min_value=-1, max_value=1))
def test_apply_transform_if_faster(self, value):
init_net = core.Net("init_net")
init_net.ConstantFill([], ["data"], shape=[5, 5, 5, 5], value=value)
init_net.ConstantFill([], ["conv_w"], shape=[5, 5, 3, 3], value=value)
init_net.ConstantFill([], ["conv_b"], shape=[5], value=value)
self.assertEqual(
workspace.RunNetOnce(init_net.Proto().SerializeToString()), True)
m = model_helper.ModelHelper()
conv = brew.conv(m, "data", "conv",
dim_in=5,
dim_out=5,
kernel=3,
use_cudnn=True,
engine="CUDNN")
conv.Relu([], conv)\
.Softmax([], "pred") \
.AveragedLoss([], "loss")
self.assertEqual(
workspace.RunNetOnce(m.net.Proto().SerializeToString()), True)
proto = workspace.ApplyTransformIfFaster(
"ConvToNNPack",
m.net.Proto(),
init_net.Proto())
self.assertEqual(
workspace.RunNetOnce(proto.SerializeToString()), True)
proto = workspace.ApplyTransformIfFaster(
"ConvToNNPack",
m.net.Proto(),
init_net.Proto(),
warmup_runs=10,
main_runs=100,
improvement_threshold=2.0)
self.assertEqual(
workspace.RunNetOnce(proto.SerializeToString()), True)
if __name__ == '__main__':
unittest.main()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import numpy as np
from hypothesis import given
import hypothesis.strategies as st
class TestLengthsReducerOpsFused8BitRowwise(hu.HypothesisTestCase):
@given(
input_data=hu.tensor(min_dim=2, max_dim=2),
weighted=st.booleans(),
seed=st.integers(0, 2**32 - 1),
)
def test_sparse_lengths_sum(self, input_data, weighted, seed):
net = core.Net("bench")
np.random.seed(seed)
input_data = input_data.astype(np.float32)
indices = np.random.randint(
low=0,
high=len(input_data),
size=[np.random.randint(len(input_data))],
dtype=np.int32
)
weights = np.random.uniform(size=[len(indices)]).astype(np.float32)
lengths_split = np.clip(1, len(indices) // 2, 10)
lengths = np.ones(
[len(indices) // lengths_split], dtype=np.int32
) * lengths_split
print(indices, weights, lengths)
quantized_data = net.FloatToFused8BitRowwiseQuantized(
'input_data', 'quantized_data'
)
dequantized_data = net.Fused8BitRowwiseQuantizedToFloat(
quantized_data, 'dequantized_data'
)
if weighted:
net.SparseLengthsWeightedSum(
[dequantized_data, 'weights', 'indices', 'lengths'],
'sum_reference',
engine='fp16'
)
net.SparseLengthsWeightedSumFused8BitRowwise(
[quantized_data, 'weights', 'indices', 'lengths'],
'sum_quantized'
)
else:
net.SparseLengthsSum(
[dequantized_data, 'indices', 'lengths'],
'sum_reference',
engine='fp16'
)
net.SparseLengthsSumFused8BitRowwise(
[quantized_data, 'indices', 'lengths'], 'sum_quantized'
)
workspace.FeedBlob('input_data', input_data)
workspace.FeedBlob('weights', weights)
workspace.FeedBlob('indices', indices)
workspace.FeedBlob('lengths', lengths)
workspace.GlobalInit(['caffe2', '--caffe2_log_level=0'])
workspace.CreateNet(net)
workspace.RunNetOnce(net)
sum_reference = workspace.FetchBlob('sum_reference')
sum_quantized = workspace.FetchBlob('sum_quantized')
np.testing.assert_array_almost_equal(sum_reference, sum_quantized)
@given(
input_data=hu.tensor(min_dim=2, max_dim=2),
seed=st.integers(0, 2**32 - 1),
)
def test_sparse_lengths_mean(self, input_data, seed):
net = core.Net("bench")
np.random.seed(seed)
input_data = input_data.astype(np.float32)
indices = np.random.randint(
low=0,
high=len(input_data),
size=[np.random.randint(len(input_data))],
dtype=np.int32
)
lengths_split = np.clip(1, len(indices) // 2, 10)
lengths = np.ones(
[len(indices) // lengths_split], dtype=np.int32
) * lengths_split
print(indices, lengths)
quantized_data = net.FloatToFused8BitRowwiseQuantized(
'input_data', 'quantized_data'
)
dequantized_data = net.Fused8BitRowwiseQuantizedToFloat(
quantized_data, 'dequantized_data'
)
net.SparseLengthsMean(
[dequantized_data, 'indices', 'lengths'],
'mean_reference',
engine='fp16'
)
net.SparseLengthsMeanFused8BitRowwise(
[quantized_data, 'indices', 'lengths'], 'mean_quantized'
)
workspace.FeedBlob('input_data', input_data)
workspace.FeedBlob('indices', indices)
workspace.FeedBlob('lengths', lengths)
workspace.GlobalInit(['caffe2', '--caffe2_log_level=0'])
workspace.CreateNet(net)
workspace.RunNetOnce(net)
mean_reference = workspace.FetchBlob('mean_reference')
mean_quantized = workspace.FetchBlob('mean_quantized')
np.testing.assert_array_almost_equal(mean_reference, mean_quantized)
|
## @package experiment_util
# Module caffe2.python.experiment_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import time
import logging
import socket
import abc
import six
from collections import OrderedDict
from future.utils import viewkeys, viewvalues
'''
Utilities for logging experiment run stats, such as accuracy
and loss over time for different runs. Runtime arguments are stored
in the log.
Optionally, ModelTrainerLog calls out to a logger to log to
an external log destination.
'''
class ExternalLogger(object):
six.add_metaclass(abc.ABCMeta)
@abc.abstractmethod
def set_runtime_args(self, runtime_args):
"""
Set runtime arguments for the logger.
runtime_args: dict of runtime arguments.
"""
raise NotImplementedError(
'Must define set_runtime_args function to use this base class'
)
@abc.abstractmethod
def log(self, log_dict):
"""
log a dict of key/values to an external destination
log_dict: input dict
"""
raise NotImplementedError(
'Must define log function to use this base class'
)
class ModelTrainerLog():
def __init__(self, expname, runtime_args, external_loggers=None):
now = datetime.datetime.fromtimestamp(time.time())
self.experiment_id = \
"{}_{}".format(expname, now.strftime('%Y%m%d_%H%M%S'))
self.filename = "{}.log".format(self.experiment_id)
self.logstr("# %s" % str(runtime_args))
self.headers = None
self.start_time = time.time()
self.last_time = self.start_time
self.last_input_count = 0
self.external_loggers = None
if external_loggers is not None:
self.external_loggers = external_loggers
if not isinstance(runtime_args, dict):
runtime_args = dict(vars(runtime_args))
runtime_args['experiment_id'] = self.experiment_id
runtime_args['hostname'] = socket.gethostname()
for logger in self.external_loggers:
logger.set_runtime_args(runtime_args)
else:
self.external_loggers = []
def logstr(self, str):
with open(self.filename, "a") as f:
f.write(str + "\n")
f.close()
logging.getLogger("experiment_logger").info(str)
def log(self, input_count, batch_count, additional_values):
logdict = OrderedDict()
delta_t = time.time() - self.last_time
delta_count = input_count - self.last_input_count
self.last_time = time.time()
self.last_input_count = input_count
logdict['time_spent'] = delta_t
logdict['cumulative_time_spent'] = time.time() - self.start_time
logdict['input_count'] = delta_count
logdict['cumulative_input_count'] = input_count
logdict['cumulative_batch_count'] = batch_count
if delta_t > 0:
logdict['inputs_per_sec'] = delta_count / delta_t
else:
logdict['inputs_per_sec'] = 0.0
for k in sorted(viewkeys(additional_values)):
logdict[k] = additional_values[k]
# Write the headers if they are not written yet
if self.headers is None:
self.headers = list(viewkeys(logdict))
self.logstr(",".join(self.headers))
self.logstr(",".join(str(v) for v in viewvalues(logdict)))
for logger in self.external_loggers:
try:
logger.log(logdict)
except Exception as e:
logging.warn(
"Failed to call ExternalLogger: {}".format(e), e)
|
## @package session
# Module caffe2.python.session
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from caffe2.python.task import Cluster, Task, TaskGroup, WorkspaceType
class CompiledRunnable(object):
""" Wrapper for compiled runnable returned from session.compile() """
def __init__(self, obj, session_class):
self.obj = obj
self.session_class = session_class
class Session(object):
"""
Allows to run Nets, ExecutionSteps, Plans, Tasks and TaskGroups.
A session can potentially run in multiple nodes concurrently.
Example:
from core import Net
from caffe2.python.task import Task, TaskGroup, WorkspaceType
net = Net('test1')
net.Add([net.Const(1), net.Const(2)])
net2 = net.Clone()
step = core.execution_step('step1', [net2])
with TaskGroup(WorkspaceType.GLOBAL) as init_tg:
with Node('node1'):
n1setup = net.Net('n1setup')
n1msg = n1setup.Const('Hello from node 1.')
Task(step=n1setup)
with TaskGroup() as private_tg:
with Node('node1'):
n1 = net.Net('n1')
n1.Print(n1msg, 0)
Task(step=n1)
with Node('node2'):
n2 = net.Net('n2')
n2.Print(n2.Const('Hello from node 2.'), 0)
Task(step=n2)
session = LocalSession()
session.run(net)
session.run(step)
session.run(init_tg)
session.run(private_tg)
Global Workspace:
At the beggining of the session, a global workspace is created and kept
alive for the duration of the session.
Private Workspace:
Tasks can be run either directly on the global workspace, or they can
instantiate a private child workspace that is released after each run.
Blob visibility:
Tasks running in different nodes in parallel will always run under
different workspaces, so it must be assumed that they won't be able to
access each other's blobs. Tasks running on the same node will follow
Workspace hierarchy rules: tasks running on separate private workspaces
will only be able to share blobs defined on a common parent Workspace.
"""
_compiled_cache = {}
def __init__(self):
self._open = True
def is_open(self):
return self._open
@classmethod
def compile(cls, runnable, workspace_type=None, setup_net_list=None):
if isinstance(runnable, CompiledRunnable):
assert cls == runnable.session_class, (
'Runnable was compiled for different session type. ' +
'Need: %s, got: %s' % (
cls.__name__, runnable.session_class.__name__))
return runnable
if runnable in cls._compiled_cache:
return cls._compiled_cache[runnable]
if isinstance(runnable, TaskGroup):
if workspace_type:
if runnable.workspace_type():
assert runnable.workspace_type() == workspace_type, \
"Require {} but already have {}".format(
workspace_type, runnable.workspace_type())
else:
runnable._workspace_type = workspace_type
tg = runnable
else:
if workspace_type is None:
workspace_type = WorkspaceType.GLOBAL
tg = TaskGroup(workspace_type=workspace_type)
if isinstance(runnable, Task):
tg.add(runnable)
elif isinstance(runnable, core.ExecutionStep):
tg.add(Task(step=runnable))
elif isinstance(runnable, core.Plan):
# ExecutionSteps in Plan() object is supposed to run sequentially, while
# tasks in TaskGroup run in parallel. So if we have multiple
# ExecutionSteps in Plan() object, we choose to have a root
# ExecutionStep to wrap all ExecutionSteps.
assert len(runnable.Steps()) > 0
if len(runnable.Steps()) == 1:
tg.add(Task(step=runnable.Steps()[0]))
else:
# Task takes a list of ExecutionSteps and automatically wrap into
# a root ExecutionStep
tg.add(Task(step=runnable.Steps()))
else:
step = core.execution_step('runnable', runnable)
tg.add(Task(step=step))
compiled = CompiledRunnable(
cls._compile_task_group(tg, setup_net_list), session_class=cls)
cls._compiled_cache[runnable] = compiled
return compiled
def run(self, runnable, workspace_type=None, setup_net_list=None):
"""Run the given runnable.
Args:
runnable: Object recognized by the Session. Currently, we support
TaskGroup, Task, Plan, ExecutionStep, and Net.
workspace_type: A string defined in the WorkspaceType object.
setup_net_list: A list of Net objects or a list of NetDef protos.
So far this is only used by the DistributedSession, in which we
need to pass a list of special nets to setup the master.
"""
assert self.is_open(), 'Session is closed.'
assert runnable is not None, 'Got a none runnable.'
self._run_compiled(self.compile(runnable, workspace_type,
setup_net_list).obj)
def close(self):
if self.is_open():
self._do_close()
self._open = False
def fetch_output(self, output):
raise NotImplementedError()
def _run_compiled(self, task_group):
raise NotImplementedError()
@classmethod
def _compile_task_group(cls, task_group, setup_net_list=None):
return task_group
def _do_close(self):
pass
def __enter__(self):
assert self._open, 'Session already closed.'
return self
def __exit__(self, ex_type, value, traceback):
if ex_type is None:
self.close()
class LocalSession(Session):
"""
Session that runs in a single node.
Tasks are all remapped to run in parallel in the 'local' node.
Currently, LocalSession runs all parallel tasks in the same workspace,
but this behavior may change in the future. Only tasks pointing to the
same logical node are guaranteed to always run in the same workspace.
"""
def __init__(self, ws=None):
Session.__init__(self)
self._ws = ws or workspace.C.Workspace.current
@classmethod
def _compile_task_group(cls, task_group, setup_net_list=None):
with Cluster():
task = task_group.to_task()
plan = core.Plan('task_group_plan')
plan.AddStep(task.get_step())
return (plan, task.output_list(), task.workspace_type)
def _run_compiled(self, compiled):
plan, output_list, workspace_type = compiled
# make sure the output blobs belong to the parent workspace
outputs = []
for name in output_list.names():
self._ws.create_blob(str(name))
outputs.append(core.BlobReference(str(name)))
output_list.set_values(outputs, _fetch_func=self._fetch_output)
task_ws = (
workspace.C.Workspace(self._ws)
if workspace_type == WorkspaceType.PRIVATE else self._ws)
with workspace.WorkspaceGuard(task_ws):
task_ws.run(plan)
def _fetch_output(self, output):
return self._ws.blobs[str(output)].fetch()
|
## @package record_queue
# Module caffe2.python.record_queue
"""
Implementation of a queue wrapper.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from caffe2.python.dataio import Reader, Writer
from caffe2.python.schema import (
Struct, Field, from_column_list)
class _QueueReader(Reader):
def __init__(self, blobs_queue, schema, name=None):
"""Don't call this directly. Instead, use dataset.reader()"""
super(_QueueReader, self).__init__(schema)
self.blobs_queue = blobs_queue
self.name = name
def read(self, read_net):
with core.NameScope(read_net.NextName(self.name)):
status = read_net.NextName()
fields = read_net.SafeDequeueBlobs(
self.blobs_queue, self._schema.field_names() + [status])
return (fields[-1], fields[:-1])
class _QueueWriter(Writer):
def __init__(self, blobs_queue, schema):
self.blobs_queue = blobs_queue
self.schema = schema
def write(self, writer_net, fields):
if isinstance(fields, Field):
fields = fields.field_blobs()
writer_net.CheckDatasetConsistency(
fields, [], fields=self.schema.field_names())
status = writer_net.NextName()
writer_net.SafeEnqueueBlobs(
[self.blobs_queue] + fields, fields + [status])
return status
class RecordQueue(object):
""" The class is used to feed data with some process from a reader into a
queue and provider a reader interface for data fetching from the queue.
"""
def __init__(self, fields, name=None, capacity=1,
enforce_unique_name=False, num_threads=1):
assert isinstance(fields, list) or isinstance(fields, Struct), (
'fields must be either a Struct or a list of raw field names.')
if isinstance(fields, list):
fields = from_column_list(fields)
self.schema = fields
self.name = name or 'queue'
self.num_threads = num_threads
num_blobs = len(self.schema.field_names())
init_net = core.Net(self.name + '/init_net')
self.blobs_queue = init_net.CreateBlobsQueue(
[], 1,
capacity=capacity,
num_blobs=num_blobs,
enforce_unique_name=enforce_unique_name)
core.workspace.RunNetOnce(init_net)
self.writer = _QueueWriter(self.blobs_queue, self.schema)
reader_name = self.name + '_reader'
self.reader = _QueueReader(self.blobs_queue, self.schema, reader_name)
exit_net = core.Net(self.name + '/exit_net')
exit_net.CloseBlobsQueue(self.blobs_queue, 0)
self.exit_step = core.execution_step(
'{}_close_step'.format(str(exit_net)),
exit_net)
def build(self, reader, process=None):
"""
Build the producer_step to feed data from reader into the queue, and
return the reader interface.
Inputs:
reader: read data which will be stored in the queue.
process: preprocess data before enqueue.
Outputs:
reader: reader to fetch the data from the queue.
producer_step: the step insert the data into the queue. Should be
run with comsume_step together.
exit_step: the step to close queue
schema: the schema for the reader.
"""
producer_steps = []
for i in range(self.num_threads):
name = 'reader_' + str(i)
net_reader = core.Net(name)
should_stop, fields = reader.read_record(net_reader)
step_read = core.execution_step(name, net_reader)
name = 'queue_writer' + str(i)
net_prod = core.Net(name)
field_blobs = fields.field_blobs()
if process:
field_blobs = process(net_prod, fields).field_blobs()
self.writer.write(net_prod, field_blobs)
step_prod = core.execution_step(name, net_prod)
step = core.execution_step(
'producer_' + str(i),
[step_read, step_prod],
should_stop_blob=should_stop)
producer_steps.append(step)
producer_step = core.execution_step(
'producers',
producer_steps,
concurrent_substeps=True)
return self.reader, producer_step, self.exit_step, self.schema
|
## @package layer_model_instantiator
# Module caffe2.python.layer_model_instantiator
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import InstantiationContext
from caffe2.python.layers.tags import Tags
def _filter_layers(layers, include_tags):
if include_tags is None:
return layers
include_tags = set(include_tags)
return [l for l in layers if not include_tags.isdisjoint(l.tags)]
def shrink_output_schema(net, out_schema):
if len(out_schema.field_names()) <= 1:
return out_schema
exists = [net.BlobIsDefined(blob) for blob in out_schema.field_blobs()]
return schema.from_column_list(
[
col_name for ok, col_name in
zip(exists, out_schema.field_names()) if ok
],
[
col_type for ok, col_type in
zip(exists, out_schema.field_types()) if ok
],
[
col_blob for ok, col_blob in
zip(exists, out_schema.field_blobs()) if ok
],
[
col_meta for ok, col_meta in
zip(exists, out_schema.field_metadata()) if ok
]
)
def generate_predict_net(model, include_tags=None):
predict_net = core.Net('predict_net')
for layer in _filter_layers(model.layers, include_tags):
if Tags.EXCLUDE_FROM_PREDICTION not in layer.tags:
layer.add_operators(
predict_net, context=InstantiationContext.PREDICTION)
predict_net.set_input_record(model.input_feature_schema.clone())
output_schema = shrink_output_schema(
predict_net, model.output_schema.clone()
)
predict_net.set_output_record(output_schema)
return predict_net
def generate_eval_net(model, include_tags=None):
eval_net = core.Net('eval_net')
for layer in _filter_layers(model.layers, include_tags):
if Tags.EXCLUDE_FROM_EVAL not in layer.tags:
layer.add_operators(eval_net, context=InstantiationContext.EVAL)
input_schema = model.input_feature_schema + model.trainer_extra_schema
eval_net.set_input_record(input_schema)
output_schema = shrink_output_schema(
eval_net, model.output_schema + model.metrics_schema
)
eval_net.set_output_record(output_schema)
return eval_net
def _generate_training_net_only(model, include_tags=None):
train_net = core.Net('train_net')
train_init_net = model.create_init_net('train_init_net')
for layer in _filter_layers(model.layers, include_tags):
if Tags.EXCLUDE_FROM_TRAIN not in layer.tags:
layer.add_operators(train_net, train_init_net)
input_schema = model.input_feature_schema + model.trainer_extra_schema
train_net.set_input_record(input_schema)
output_schema = shrink_output_schema(
train_net, model.output_schema + model.metrics_schema
)
train_net.set_output_record(output_schema)
return train_init_net, train_net
def generate_training_nets_forward_only(model, include_tags=None):
train_init_net, train_net = _generate_training_net_only(model, include_tags)
return train_init_net, train_net
def generate_training_nets(model, include_tags=None):
train_init_net, train_net = _generate_training_net_only(model, include_tags)
model.apply_regularizers_on_loss(train_net, train_init_net)
if not model.has_loss():
return train_init_net, train_net
loss = model.loss
grad_map = train_net.AddGradientOperators(loss.field_blobs())
model.apply_post_grad_net_modifiers(train_net, train_init_net, grad_map)
model.apply_optimizers(train_net, train_init_net, grad_map)
model.apply_regularizers_after_optimizer(train_net, train_init_net, grad_map)
model.apply_final_net_modifiers(train_net, train_init_net, grad_map)
return train_init_net, train_net
|
## @package rnn_cell
# Module caffe2.python.rnn_cell
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import inspect
import itertools
import logging
import numpy as np
import random
import six
from future.utils import viewkeys
from caffe2.proto import caffe2_pb2
from caffe2.python.attention import (
apply_dot_attention,
apply_recurrent_attention,
apply_regular_attention,
apply_soft_coverage_attention,
AttentionType,
)
from caffe2.python import core, recurrent, workspace, brew, scope, utils
from caffe2.python.modeling.parameter_sharing import ParameterSharing
from caffe2.python.modeling.parameter_info import ParameterTags
from caffe2.python.modeling.initializers import Initializer
from caffe2.python.model_helper import ModelHelper
def _RectifyName(blob_reference_or_name):
if blob_reference_or_name is None:
return None
if isinstance(blob_reference_or_name, six.string_types):
return core.ScopedBlobReference(blob_reference_or_name)
if not isinstance(blob_reference_or_name, core.BlobReference):
raise Exception("Unknown blob reference type")
return blob_reference_or_name
def _RectifyNames(blob_references_or_names):
if blob_references_or_names is None:
return None
return list(map(_RectifyName, blob_references_or_names))
class RNNCell(object):
'''
Base class for writing recurrent / stateful operations.
One needs to implement 2 methods: apply_override
and get_state_names_override.
As a result base class will provice apply_over_sequence method, which
allows you to apply recurrent operations over a sequence of any length.
As optional you could add input and output preparation steps by overriding
corresponding methods.
'''
def __init__(self, name=None, forward_only=False, initializer=None):
self.name = name
self.recompute_blobs = []
self.forward_only = forward_only
self._initializer = initializer
@property
def initializer(self):
return self._initializer
@initializer.setter
def initializer(self, value):
self._initializer = value
def scope(self, name):
return self.name + '/' + name if self.name is not None else name
def apply_over_sequence(
self,
model,
inputs,
seq_lengths=None,
initial_states=None,
outputs_with_grads=None,
):
if initial_states is None:
with scope.NameScope(self.name):
if self.initializer is None:
raise Exception("Either initial states "
"or initializer have to be set")
initial_states = self.initializer.create_states(model)
preprocessed_inputs = self.prepare_input(model, inputs)
step_model = ModelHelper(name=self.name, param_model=model)
input_t, timestep = step_model.net.AddScopedExternalInputs(
'input_t',
'timestep',
)
utils.raiseIfNotEqual(
len(initial_states), len(self.get_state_names()),
"Number of initial state values provided doesn't match the number "
"of states"
)
states_prev = step_model.net.AddScopedExternalInputs(*[
s + '_prev' for s in self.get_state_names()
])
states = self._apply(
model=step_model,
input_t=input_t,
seq_lengths=seq_lengths,
states=states_prev,
timestep=timestep,
)
external_outputs = set(step_model.net.Proto().external_output)
for state in states:
if state not in external_outputs:
step_model.net.AddExternalOutput(state)
if outputs_with_grads is None:
outputs_with_grads = [self.get_output_state_index() * 2]
# states_for_all_steps consists of combination of
# states gather for all steps and final states. It looks like this:
# (state_1_all, state_1_final, state_2_all, state_2_final, ...)
states_for_all_steps = recurrent.recurrent_net(
net=model.net,
cell_net=step_model.net,
inputs=[(input_t, preprocessed_inputs)],
initial_cell_inputs=list(zip(states_prev, initial_states)),
links=dict(zip(states_prev, states)),
timestep=timestep,
scope=self.name,
forward_only=self.forward_only,
outputs_with_grads=outputs_with_grads,
recompute_blobs_on_backward=self.recompute_blobs,
)
output = self._prepare_output_sequence(
model,
states_for_all_steps,
)
return output, states_for_all_steps
def apply(self, model, input_t, seq_lengths, states, timestep):
input_t = self.prepare_input(model, input_t)
states = self._apply(
model, input_t, seq_lengths, states, timestep)
output = self._prepare_output(model, states)
return output, states
def _apply(
self,
model, input_t, seq_lengths, states, timestep, extra_inputs=None
):
'''
This method uses apply_override provided by a custom cell.
On the top it takes care of applying self.scope() to all the outputs.
While all the inputs stay within the scope this function was called
from.
'''
args = self._rectify_apply_inputs(
input_t, seq_lengths, states, timestep, extra_inputs)
with core.NameScope(self.name):
return self.apply_override(model, *args)
def _rectify_apply_inputs(
self, input_t, seq_lengths, states, timestep, extra_inputs):
'''
Before applying a scope we make sure that all external blob names
are converted to blob reference. So further scoping doesn't affect them
'''
input_t, seq_lengths, timestep = _RectifyNames(
[input_t, seq_lengths, timestep])
states = _RectifyNames(states)
if extra_inputs:
extra_input_names, extra_input_sizes = zip(*extra_inputs)
extra_inputs = _RectifyNames(extra_input_names)
extra_inputs = zip(extra_input_names, extra_input_sizes)
arg_names = inspect.getargspec(self.apply_override).args
rectified = [input_t, seq_lengths, states, timestep]
if 'extra_inputs' in arg_names:
rectified.append(extra_inputs)
return rectified
def apply_override(
self,
model, input_t, seq_lengths, timestep, extra_inputs=None,
):
'''
A single step of a recurrent network to be implemented by each custom
RNNCell.
model: ModelHelper object new operators would be added to
input_t: singlse input with shape (1, batch_size, input_dim)
seq_lengths: blob containing sequence lengths which would be passed to
LSTMUnit operator
states: previous recurrent states
timestep: current recurrent iteration. Could be used together with
seq_lengths in order to determine, if some shorter sequences
in the batch have already ended.
extra_inputs: list of tuples (input, dim). specifies additional input
which is not subject to prepare_input(). (useful when a cell is a
component of a larger recurrent structure, e.g., attention)
'''
raise NotImplementedError('Abstract method')
def prepare_input(self, model, input_blob):
'''
If some operations in _apply method depend only on the input,
not on recurrent states, they could be computed in advance.
model: ModelHelper object new operators would be added to
input_blob: either the whole input sequence with shape
(sequence_length, batch_size, input_dim) or a single input with shape
(1, batch_size, input_dim).
'''
return input_blob
def get_output_state_index(self):
'''
Return index into state list of the "primary" step-wise output.
'''
return 0
def get_state_names(self):
'''
Returns recurrent state names with self.name scoping applied
'''
return list(map(self.scope, self.get_state_names_override()))
def get_state_names_override(self):
'''
Override this funtion in your custom cell.
It should return the names of the recurrent states.
It's required by apply_over_sequence method in order to allocate
recurrent states for all steps with meaningful names.
'''
raise NotImplementedError('Abstract method')
def get_output_dim(self):
'''
Specifies the dimension (number of units) of stepwise output.
'''
raise NotImplementedError('Abstract method')
def _prepare_output(self, model, states):
'''
Allows arbitrary post-processing of primary output.
'''
return states[self.get_output_state_index()]
def _prepare_output_sequence(self, model, state_outputs):
'''
Allows arbitrary post-processing of primary sequence output.
(Note that state_outputs alternates between full-sequence and final
output for each state, thus the index multiplier 2.)
'''
output_sequence_index = 2 * self.get_output_state_index()
return state_outputs[output_sequence_index]
class LSTMInitializer(object):
def __init__(self, hidden_size):
self.hidden_size = hidden_size
def create_states(self, model):
return [
model.create_param(
param_name='initial_hidden_state',
initializer=Initializer(operator_name='ConstantFill',
value=0.0),
shape=[self.hidden_size],
),
model.create_param(
param_name='initial_cell_state',
initializer=Initializer(operator_name='ConstantFill',
value=0.0),
shape=[self.hidden_size],
)
]
# based on http://pytorch.org/docs/master/nn.html#torch.nn.RNNCell
class BasicRNNCell(RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias,
memory_optimization,
drop_states=False,
initializer=None,
activation=None,
**kwargs
):
super(BasicRNNCell, self).__init__(**kwargs)
self.drop_states = drop_states
self.input_size = input_size
self.hidden_size = hidden_size
self.activation = activation
if self.activation not in ['relu', 'tanh']:
raise RuntimeError(
'BasicRNNCell with unknown activation function (%s)'
% self.activation)
def apply_override(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev = states[0]
gates_t = brew.fc(
model,
hidden_t_prev,
'gates_t',
dim_in=self.hidden_size,
dim_out=self.hidden_size,
axis=2,
)
brew.sum(model, [gates_t, input_t], gates_t)
if self.activation == 'tanh':
hidden_t = model.net.Tanh(gates_t, 'hidden_t')
elif self.activation == 'relu':
hidden_t = model.net.Relu(gates_t, 'hidden_t')
else:
raise RuntimeError(
'BasicRNNCell with unknown activation function (%s)'
% self.activation)
if seq_lengths is not None:
# TODO If this codepath becomes popular, it may be worth
# taking a look at optimizing it - for now a simple
# implementation is used to round out compatibility with
# ONNX.
timestep = model.net.CopyFromCPUInput(
timestep, 'timestep_gpu')
valid_b = model.net.GT(
[seq_lengths, timestep], 'valid_b', broadcast=1)
invalid_b = model.net.LE(
[seq_lengths, timestep], 'invalid_b', broadcast=1)
valid = model.net.Cast(valid_b, 'valid', to='float')
invalid = model.net.Cast(invalid_b, 'invalid', to='float')
hidden_valid = model.net.Mul(
[hidden_t, valid],
'hidden_valid',
broadcast=1,
axis=1,
)
if self.drop_states:
hidden_t = hidden_valid
else:
hidden_invalid = model.net.Mul(
[hidden_t_prev, invalid],
'hidden_invalid',
broadcast=1, axis=1)
hidden_t = model.net.Add(
[hidden_valid, hidden_invalid], hidden_t)
return (hidden_t,)
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=self.hidden_size,
axis=2,
)
def get_state_names(self):
return (self.scope('hidden_t'),)
def get_output_dim(self):
return self.hidden_size
class LSTMCell(RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias,
memory_optimization,
drop_states=False,
initializer=None,
**kwargs
):
super(LSTMCell, self).__init__(initializer=initializer, **kwargs)
self.initializer = initializer or LSTMInitializer(
hidden_size=hidden_size)
self.input_size = input_size
self.hidden_size = hidden_size
self.forget_bias = float(forget_bias)
self.memory_optimization = memory_optimization
self.drop_states = drop_states
self.gates_size = 4 * self.hidden_size
def apply_override(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
'gates_concatenated_input_t',
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
gates_t = brew.fc(
model,
fc_input,
'gates_t',
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
brew.sum(model, [gates_t, input_t], gates_t)
if seq_lengths is not None:
inputs = [hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep]
else:
inputs = [hidden_t_prev, cell_t_prev, gates_t, timestep]
hidden_t, cell_t = model.net.LSTMUnit(
inputs,
['hidden_state', 'cell_state'],
forget_bias=self.forget_bias,
drop_states=self.drop_states,
sequence_lengths=(seq_lengths is not None),
)
model.net.AddExternalOutputs(hidden_t, cell_t)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
def get_input_params(self):
return {
'weights': self.scope('i2h') + '_w',
'biases': self.scope('i2h') + '_b',
}
def get_recurrent_params(self):
return {
'weights': self.scope('gates_t') + '_w',
'biases': self.scope('gates_t') + '_b',
}
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=self.gates_size,
axis=2,
)
def get_state_names_override(self):
return ['hidden_t', 'cell_t']
def get_output_dim(self):
return self.hidden_size
class LayerNormLSTMCell(RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias,
memory_optimization,
drop_states=False,
initializer=None,
**kwargs
):
super(LayerNormLSTMCell, self).__init__(
initializer=initializer, **kwargs
)
self.initializer = initializer or LSTMInitializer(
hidden_size=hidden_size
)
self.input_size = input_size
self.hidden_size = hidden_size
self.forget_bias = float(forget_bias)
self.memory_optimization = memory_optimization
self.drop_states = drop_states
self.gates_size = 4 * self.hidden_size
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
self.scope('gates_concatenated_input_t'),
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
gates_t = brew.fc(
model,
fc_input,
self.scope('gates_t'),
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
brew.sum(model, [gates_t, input_t], gates_t)
# brew.layer_norm call is only difference from LSTMCell
gates_t, _, _ = brew.layer_norm(
model,
self.scope('gates_t'),
self.scope('gates_t_norm'),
dim_in=self.gates_size,
axis=-1,
)
hidden_t, cell_t = model.net.LSTMUnit(
[
hidden_t_prev,
cell_t_prev,
gates_t,
seq_lengths,
timestep,
],
self.get_state_names(),
forget_bias=self.forget_bias,
drop_states=self.drop_states,
)
model.net.AddExternalOutputs(hidden_t, cell_t)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
def get_input_params(self):
return {
'weights': self.scope('i2h') + '_w',
'biases': self.scope('i2h') + '_b',
}
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=self.gates_size,
axis=2,
)
def get_state_names(self):
return (self.scope('hidden_t'), self.scope('cell_t'))
class MILSTMCell(LSTMCell):
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
self.scope('gates_concatenated_input_t'),
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
prev_t = brew.fc(
model,
fc_input,
self.scope('prev_t'),
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
# defining initializers for MI parameters
alpha = model.create_param(
self.scope('alpha'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_h = model.create_param(
self.scope('beta1'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_i = model.create_param(
self.scope('beta2'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
b = model.create_param(
self.scope('b'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=0.0),
)
# alpha * input_t + beta_h
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h = model.net.ElementwiseLinear(
[input_t, alpha, beta_h],
self.scope('alpha_by_input_t_plus_beta_h'),
axis=2,
)
# (alpha * input_t + beta_h) * prev_t =
# alpha * input_t * prev_t + beta_h * prev_t
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h_by_prev_t = model.net.Mul(
[alpha_by_input_t_plus_beta_h, prev_t],
self.scope('alpha_by_input_t_plus_beta_h_by_prev_t')
)
# beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
beta_i_by_input_t_plus_b = model.net.ElementwiseLinear(
[input_t, beta_i, b],
self.scope('beta_i_by_input_t_plus_b'),
axis=2,
)
# alpha * input_t * prev_t + beta_h * prev_t + beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
gates_t = brew.sum(
model,
[alpha_by_input_t_plus_beta_h_by_prev_t, beta_i_by_input_t_plus_b],
self.scope('gates_t')
)
hidden_t, cell_t = model.net.LSTMUnit(
[hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep],
[self.scope('hidden_t_intermediate'), self.scope('cell_t')],
forget_bias=self.forget_bias,
drop_states=self.drop_states,
)
model.net.AddExternalOutputs(
cell_t,
hidden_t,
)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
class LayerNormMILSTMCell(LSTMCell):
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
self.scope('gates_concatenated_input_t'),
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
prev_t = brew.fc(
model,
fc_input,
self.scope('prev_t'),
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
# defining initializers for MI parameters
alpha = model.create_param(
self.scope('alpha'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_h = model.create_param(
self.scope('beta1'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_i = model.create_param(
self.scope('beta2'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
b = model.create_param(
self.scope('b'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=0.0),
)
# alpha * input_t + beta_h
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h = model.net.ElementwiseLinear(
[input_t, alpha, beta_h],
self.scope('alpha_by_input_t_plus_beta_h'),
axis=2,
)
# (alpha * input_t + beta_h) * prev_t =
# alpha * input_t * prev_t + beta_h * prev_t
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h_by_prev_t = model.net.Mul(
[alpha_by_input_t_plus_beta_h, prev_t],
self.scope('alpha_by_input_t_plus_beta_h_by_prev_t')
)
# beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
beta_i_by_input_t_plus_b = model.net.ElementwiseLinear(
[input_t, beta_i, b],
self.scope('beta_i_by_input_t_plus_b'),
axis=2,
)
# alpha * input_t * prev_t + beta_h * prev_t + beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
gates_t = brew.sum(
model,
[alpha_by_input_t_plus_beta_h_by_prev_t, beta_i_by_input_t_plus_b],
self.scope('gates_t')
)
# brew.layer_norm call is only difference from MILSTMCell._apply
gates_t, _, _ = brew.layer_norm(
model,
self.scope('gates_t'),
self.scope('gates_t_norm'),
dim_in=self.gates_size,
axis=-1,
)
hidden_t, cell_t = model.net.LSTMUnit(
[hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep],
[self.scope('hidden_t_intermediate'), self.scope('cell_t')],
forget_bias=self.forget_bias,
drop_states=self.drop_states,
)
model.net.AddExternalOutputs(
cell_t,
hidden_t,
)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
class DropoutCell(RNNCell):
'''
Wraps arbitrary RNNCell, applying dropout to its output (but not to the
recurrent connection for the corresponding state).
'''
def __init__(
self,
internal_cell,
dropout_ratio=None,
use_cudnn=False,
**kwargs
):
self.internal_cell = internal_cell
self.dropout_ratio = dropout_ratio
assert 'is_test' in kwargs, "Argument 'is_test' is required"
self.is_test = kwargs.pop('is_test')
self.use_cudnn = use_cudnn
super(DropoutCell, self).__init__(**kwargs)
self.prepare_input = internal_cell.prepare_input
self.get_output_state_index = internal_cell.get_output_state_index
self.get_state_names = internal_cell.get_state_names
self.get_output_dim = internal_cell.get_output_dim
self.mask = 0
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
return self.internal_cell._apply(
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs,
)
def _prepare_output(self, model, states):
output = self.internal_cell._prepare_output(
model,
states,
)
if self.dropout_ratio is not None:
output = self._apply_dropout(model, output)
return output
def _prepare_output_sequence(self, model, state_outputs):
output = self.internal_cell._prepare_output_sequence(
model,
state_outputs,
)
if self.dropout_ratio is not None:
output = self._apply_dropout(model, output)
return output
def _apply_dropout(self, model, output):
if self.dropout_ratio and not self.forward_only:
with core.NameScope(self.name or ''):
output = brew.dropout(
model,
output,
str(output) + '_with_dropout_mask{}'.format(self.mask),
ratio=float(self.dropout_ratio),
is_test=self.is_test,
use_cudnn=self.use_cudnn,
)
self.mask += 1
return output
class MultiRNNCellInitializer(object):
def __init__(self, cells):
self.cells = cells
def create_states(self, model):
states = []
for i, cell in enumerate(self.cells):
if cell.initializer is None:
raise Exception("Either initial states "
"or initializer have to be set")
with core.NameScope("layer_{}".format(i)),\
core.NameScope(cell.name):
states.extend(cell.initializer.create_states(model))
return states
class MultiRNNCell(RNNCell):
'''
Multilayer RNN via the composition of RNNCell instance.
It is the resposibility of calling code to ensure the compatibility
of the successive layers in terms of input/output dimensiality, etc.,
and to ensure that their blobs do not have name conflicts, typically by
creating the cells with names that specify layer number.
Assumes first state (recurrent output) for each layer should be the input
to the next layer.
'''
def __init__(self, cells, residual_output_layers=None, **kwargs):
'''
cells: list of RNNCell instances, from input to output side.
name: string designating network component (for scoping)
residual_output_layers: list of indices of layers whose input will
be added elementwise to their output elementwise. (It is the
responsibility of the client code to ensure shape compatibility.)
Note that layer 0 (zero) cannot have residual output because of the
timing of prepare_input().
forward_only: used to construct inference-only network.
'''
super(MultiRNNCell, self).__init__(**kwargs)
self.cells = cells
if residual_output_layers is None:
self.residual_output_layers = []
else:
self.residual_output_layers = residual_output_layers
output_index_per_layer = []
base_index = 0
for cell in self.cells:
output_index_per_layer.append(
base_index + cell.get_output_state_index(),
)
base_index += len(cell.get_state_names())
self.output_connected_layers = []
self.output_indices = []
for i in range(len(self.cells) - 1):
if (i + 1) in self.residual_output_layers:
self.output_connected_layers.append(i)
self.output_indices.append(output_index_per_layer[i])
else:
self.output_connected_layers = []
self.output_indices = []
self.output_connected_layers.append(len(self.cells) - 1)
self.output_indices.append(output_index_per_layer[-1])
self.state_names = []
for i, cell in enumerate(self.cells):
self.state_names.extend(
map(self.layer_scoper(i), cell.get_state_names())
)
self.initializer = MultiRNNCellInitializer(cells)
def layer_scoper(self, layer_id):
def helper(name):
return "{}/layer_{}/{}".format(self.name, layer_id, name)
return helper
def prepare_input(self, model, input_blob):
input_blob = _RectifyName(input_blob)
with core.NameScope(self.name or ''):
return self.cells[0].prepare_input(model, input_blob)
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
'''
Because below we will do scoping across layers, we need
to make sure that string blob names are convereted to BlobReference
objects.
'''
input_t, seq_lengths, states, timestep, extra_inputs = \
self._rectify_apply_inputs(
input_t, seq_lengths, states, timestep, extra_inputs)
states_per_layer = [len(cell.get_state_names()) for cell in self.cells]
assert len(states) == sum(states_per_layer)
next_states = []
states_index = 0
layer_input = input_t
for i, layer_cell in enumerate(self.cells):
# # If cells don't have different names we still
# take care of scoping
with core.NameScope(self.name), core.NameScope("layer_{}".format(i)):
num_states = states_per_layer[i]
layer_states = states[states_index:(states_index + num_states)]
states_index += num_states
if i > 0:
prepared_input = layer_cell.prepare_input(
model, layer_input)
else:
prepared_input = layer_input
layer_next_states = layer_cell._apply(
model,
prepared_input,
seq_lengths,
layer_states,
timestep,
extra_inputs=(None if i > 0 else extra_inputs),
)
# Since we're using here non-public method _apply,
# instead of apply, we have to manually extract output
# from states
if i != len(self.cells) - 1:
layer_output = layer_cell._prepare_output(
model,
layer_next_states,
)
if i > 0 and i in self.residual_output_layers:
layer_input = brew.sum(
model,
[layer_output, layer_input],
self.scope('residual_output_{}'.format(i)),
)
else:
layer_input = layer_output
next_states.extend(layer_next_states)
return next_states
def get_state_names(self):
return self.state_names
def get_output_state_index(self):
index = 0
for cell in self.cells[:-1]:
index += len(cell.get_state_names())
index += self.cells[-1].get_output_state_index()
return index
def _prepare_output(self, model, states):
connected_outputs = []
state_index = 0
for i, cell in enumerate(self.cells):
num_states = len(cell.get_state_names())
if i in self.output_connected_layers:
layer_states = states[state_index:state_index + num_states]
layer_output = cell._prepare_output(
model,
layer_states
)
connected_outputs.append(layer_output)
state_index += num_states
if len(connected_outputs) > 1:
output = brew.sum(
model,
connected_outputs,
self.scope('residual_output'),
)
else:
output = connected_outputs[0]
return output
def _prepare_output_sequence(self, model, states):
connected_outputs = []
state_index = 0
for i, cell in enumerate(self.cells):
num_states = 2 * len(cell.get_state_names())
if i in self.output_connected_layers:
layer_states = states[state_index:state_index + num_states]
layer_output = cell._prepare_output_sequence(
model,
layer_states
)
connected_outputs.append(layer_output)
state_index += num_states
if len(connected_outputs) > 1:
output = brew.sum(
model,
connected_outputs,
self.scope('residual_output_sequence'),
)
else:
output = connected_outputs[0]
return output
class AttentionCell(RNNCell):
def __init__(
self,
encoder_output_dim,
encoder_outputs,
encoder_lengths,
decoder_cell,
decoder_state_dim,
attention_type,
weighted_encoder_outputs,
attention_memory_optimization,
**kwargs
):
super(AttentionCell, self).__init__(**kwargs)
self.encoder_output_dim = encoder_output_dim
self.encoder_outputs = encoder_outputs
self.encoder_lengths = encoder_lengths
self.decoder_cell = decoder_cell
self.decoder_state_dim = decoder_state_dim
self.weighted_encoder_outputs = weighted_encoder_outputs
self.encoder_outputs_transposed = None
assert attention_type in [
AttentionType.Regular,
AttentionType.Recurrent,
AttentionType.Dot,
AttentionType.SoftCoverage,
]
self.attention_type = attention_type
self.attention_memory_optimization = attention_memory_optimization
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
if self.attention_type == AttentionType.SoftCoverage:
decoder_prev_states = states[:-2]
attention_weighted_encoder_context_t_prev = states[-2]
coverage_t_prev = states[-1]
else:
decoder_prev_states = states[:-1]
attention_weighted_encoder_context_t_prev = states[-1]
assert extra_inputs is None
decoder_states = self.decoder_cell._apply(
model,
input_t,
seq_lengths,
decoder_prev_states,
timestep,
extra_inputs=[(
attention_weighted_encoder_context_t_prev,
self.encoder_output_dim,
)],
)
self.hidden_t_intermediate = self.decoder_cell._prepare_output(
model,
decoder_states,
)
if self.attention_type == AttentionType.Recurrent:
(
attention_weighted_encoder_context_t,
self.attention_weights_3d,
attention_blobs,
) = apply_recurrent_attention(
model=model,
encoder_output_dim=self.encoder_output_dim,
encoder_outputs_transposed=self.encoder_outputs_transposed,
weighted_encoder_outputs=self.weighted_encoder_outputs,
decoder_hidden_state_t=self.hidden_t_intermediate,
decoder_hidden_state_dim=self.decoder_state_dim,
scope=self.name,
attention_weighted_encoder_context_t_prev=(
attention_weighted_encoder_context_t_prev
),
encoder_lengths=self.encoder_lengths,
)
elif self.attention_type == AttentionType.Regular:
(
attention_weighted_encoder_context_t,
self.attention_weights_3d,
attention_blobs,
) = apply_regular_attention(
model=model,
encoder_output_dim=self.encoder_output_dim,
encoder_outputs_transposed=self.encoder_outputs_transposed,
weighted_encoder_outputs=self.weighted_encoder_outputs,
decoder_hidden_state_t=self.hidden_t_intermediate,
decoder_hidden_state_dim=self.decoder_state_dim,
scope=self.name,
encoder_lengths=self.encoder_lengths,
)
elif self.attention_type == AttentionType.Dot:
(
attention_weighted_encoder_context_t,
self.attention_weights_3d,
attention_blobs,
) = apply_dot_attention(
model=model,
encoder_output_dim=self.encoder_output_dim,
encoder_outputs_transposed=self.encoder_outputs_transposed,
decoder_hidden_state_t=self.hidden_t_intermediate,
decoder_hidden_state_dim=self.decoder_state_dim,
scope=self.name,
encoder_lengths=self.encoder_lengths,
)
elif self.attention_type == AttentionType.SoftCoverage:
(
attention_weighted_encoder_context_t,
self.attention_weights_3d,
attention_blobs,
coverage_t,
) = apply_soft_coverage_attention(
model=model,
encoder_output_dim=self.encoder_output_dim,
encoder_outputs_transposed=self.encoder_outputs_transposed,
weighted_encoder_outputs=self.weighted_encoder_outputs,
decoder_hidden_state_t=self.hidden_t_intermediate,
decoder_hidden_state_dim=self.decoder_state_dim,
scope=self.name,
encoder_lengths=self.encoder_lengths,
coverage_t_prev=coverage_t_prev,
coverage_weights=self.coverage_weights,
)
else:
raise Exception('Attention type {} not implemented'.format(
self.attention_type
))
if self.attention_memory_optimization:
self.recompute_blobs.extend(attention_blobs)
output = list(decoder_states) + [attention_weighted_encoder_context_t]
if self.attention_type == AttentionType.SoftCoverage:
output.append(coverage_t)
output[self.decoder_cell.get_output_state_index()] = model.Copy(
output[self.decoder_cell.get_output_state_index()],
self.scope('hidden_t_external'),
)
model.net.AddExternalOutputs(*output)
return output
def get_attention_weights(self):
# [batch_size, encoder_length, 1]
return self.attention_weights_3d
def prepare_input(self, model, input_blob):
if self.encoder_outputs_transposed is None:
self.encoder_outputs_transposed = brew.transpose(
model,
self.encoder_outputs,
self.scope('encoder_outputs_transposed'),
axes=[1, 2, 0],
)
if (
self.weighted_encoder_outputs is None and
self.attention_type != AttentionType.Dot
):
self.weighted_encoder_outputs = brew.fc(
model,
self.encoder_outputs,
self.scope('weighted_encoder_outputs'),
dim_in=self.encoder_output_dim,
dim_out=self.encoder_output_dim,
axis=2,
)
return self.decoder_cell.prepare_input(model, input_blob)
def build_initial_coverage(self, model):
"""
initial_coverage is always zeros of shape [encoder_length],
which shape must be determined programmatically dureing network
computation.
This method also sets self.coverage_weights, a separate transform
of encoder_outputs which is used to determine coverage contribution
tp attention.
"""
assert self.attention_type == AttentionType.SoftCoverage
# [encoder_length, batch_size, encoder_output_dim]
self.coverage_weights = brew.fc(
model,
self.encoder_outputs,
self.scope('coverage_weights'),
dim_in=self.encoder_output_dim,
dim_out=self.encoder_output_dim,
axis=2,
)
encoder_length = model.net.Slice(
model.net.Shape(self.encoder_outputs),
starts=[0],
ends=[1],
)
if (
scope.CurrentDeviceScope() is not None and
scope.CurrentDeviceScope().device_type == caffe2_pb2.CUDA
):
encoder_length = model.net.CopyGPUToCPU(
encoder_length,
'encoder_length_cpu',
)
# total attention weight applied across decoding steps_per_checkpoint
# shape: [encoder_length]
initial_coverage = model.net.ConstantFill(
encoder_length,
self.scope('initial_coverage'),
value=0.0,
input_as_shape=1,
)
return initial_coverage
def get_state_names(self):
state_names = list(self.decoder_cell.get_state_names())
state_names[self.get_output_state_index()] = self.scope(
'hidden_t_external',
)
state_names.append(self.scope('attention_weighted_encoder_context_t'))
if self.attention_type == AttentionType.SoftCoverage:
state_names.append(self.scope('coverage_t'))
return state_names
def get_output_dim(self):
return self.decoder_state_dim + self.encoder_output_dim
def get_output_state_index(self):
return self.decoder_cell.get_output_state_index()
def _prepare_output(self, model, states):
if self.attention_type == AttentionType.SoftCoverage:
attention_context = states[-2]
else:
attention_context = states[-1]
with core.NameScope(self.name or ''):
output = brew.concat(
model,
[self.hidden_t_intermediate, attention_context],
'states_and_context_combination',
axis=2,
)
return output
def _prepare_output_sequence(self, model, state_outputs):
if self.attention_type == AttentionType.SoftCoverage:
decoder_state_outputs = state_outputs[:-4]
else:
decoder_state_outputs = state_outputs[:-2]
decoder_output = self.decoder_cell._prepare_output_sequence(
model,
decoder_state_outputs,
)
if self.attention_type == AttentionType.SoftCoverage:
attention_context_index = 2 * (len(self.get_state_names()) - 2)
else:
attention_context_index = 2 * (len(self.get_state_names()) - 1)
with core.NameScope(self.name or ''):
output = brew.concat(
model,
[
decoder_output,
state_outputs[attention_context_index],
],
'states_and_context_combination',
axis=2,
)
return output
class LSTMWithAttentionCell(AttentionCell):
def __init__(
self,
encoder_output_dim,
encoder_outputs,
encoder_lengths,
decoder_input_dim,
decoder_state_dim,
name,
attention_type,
weighted_encoder_outputs,
forget_bias,
lstm_memory_optimization,
attention_memory_optimization,
forward_only=False,
):
decoder_cell = LSTMCell(
input_size=decoder_input_dim,
hidden_size=decoder_state_dim,
forget_bias=forget_bias,
memory_optimization=lstm_memory_optimization,
name='{}/decoder'.format(name),
forward_only=False,
drop_states=False,
)
super(LSTMWithAttentionCell, self).__init__(
encoder_output_dim=encoder_output_dim,
encoder_outputs=encoder_outputs,
encoder_lengths=encoder_lengths,
decoder_cell=decoder_cell,
decoder_state_dim=decoder_state_dim,
name=name,
attention_type=attention_type,
weighted_encoder_outputs=weighted_encoder_outputs,
attention_memory_optimization=attention_memory_optimization,
forward_only=forward_only,
)
class MILSTMWithAttentionCell(AttentionCell):
def __init__(
self,
encoder_output_dim,
encoder_outputs,
decoder_input_dim,
decoder_state_dim,
name,
attention_type,
weighted_encoder_outputs,
forget_bias,
lstm_memory_optimization,
attention_memory_optimization,
forward_only=False,
):
decoder_cell = MILSTMCell(
input_size=decoder_input_dim,
hidden_size=decoder_state_dim,
forget_bias=forget_bias,
memory_optimization=lstm_memory_optimization,
name='{}/decoder'.format(name),
forward_only=False,
drop_states=False,
)
super(MILSTMWithAttentionCell, self).__init__(
encoder_output_dim=encoder_output_dim,
encoder_outputs=encoder_outputs,
decoder_cell=decoder_cell,
decoder_state_dim=decoder_state_dim,
name=name,
attention_type=attention_type,
weighted_encoder_outputs=weighted_encoder_outputs,
attention_memory_optimization=attention_memory_optimization,
forward_only=forward_only,
)
def _LSTM(
cell_class,
model,
input_blob,
seq_lengths,
initial_states,
dim_in,
dim_out,
scope=None,
outputs_with_grads=(0,),
return_params=False,
memory_optimization=False,
forget_bias=0.0,
forward_only=False,
drop_states=False,
return_last_layer_only=True,
static_rnn_unroll_size=None,
**cell_kwargs
):
'''
Adds a standard LSTM recurrent network operator to a model.
cell_class: LSTMCell or compatible subclass
model: ModelHelper object new operators would be added to
input_blob: the input sequence in a format T x N x D
where T is sequence size, N - batch size and D - input dimension
seq_lengths: blob containing sequence lengths which would be passed to
LSTMUnit operator
initial_states: a list of (2 * num_layers) blobs representing the initial
hidden and cell states of each layer. If this argument is None,
these states will be added to the model as network parameters.
dim_in: input dimension
dim_out: number of units per LSTM layer
(use int for single-layer LSTM, list of ints for multi-layer)
outputs_with_grads : position indices of output blobs for LAST LAYER which
will receive external error gradient during backpropagation.
These outputs are: (h_all, h_last, c_all, c_last)
return_params: if True, will return a dictionary of parameters of the LSTM
memory_optimization: if enabled, the LSTM step is recomputed on backward
step so that we don't need to store forward activations for each
timestep. Saves memory with cost of computation.
forget_bias: forget gate bias (default 0.0)
forward_only: whether to create a backward pass
drop_states: drop invalid states, passed through to LSTMUnit operator
return_last_layer_only: only return outputs from final layer
(so that length of results does depend on number of layers)
static_rnn_unroll_size: if not None, we will use static RNN which is
unrolled into Caffe2 graph. The size of the unroll is the value of
this parameter.
'''
if type(dim_out) is not list and type(dim_out) is not tuple:
dim_out = [dim_out]
num_layers = len(dim_out)
cells = []
for i in range(num_layers):
cell = cell_class(
input_size=(dim_in if i == 0 else dim_out[i - 1]),
hidden_size=dim_out[i],
forget_bias=forget_bias,
memory_optimization=memory_optimization,
name=scope if num_layers == 1 else None,
forward_only=forward_only,
drop_states=drop_states,
**cell_kwargs
)
cells.append(cell)
cell = MultiRNNCell(
cells,
name=scope,
forward_only=forward_only,
) if num_layers > 1 else cells[0]
cell = (
cell if static_rnn_unroll_size is None
else UnrolledCell(cell, static_rnn_unroll_size))
# outputs_with_grads argument indexes into final layer
outputs_with_grads = [4 * (num_layers - 1) + i for i in outputs_with_grads]
_, result = cell.apply_over_sequence(
model=model,
inputs=input_blob,
seq_lengths=seq_lengths,
initial_states=initial_states,
outputs_with_grads=outputs_with_grads,
)
if return_last_layer_only:
result = result[4 * (num_layers - 1):]
if return_params:
result = list(result) + [{
'input': cell.get_input_params(),
'recurrent': cell.get_recurrent_params(),
}]
return tuple(result)
LSTM = functools.partial(_LSTM, LSTMCell)
BasicRNN = functools.partial(_LSTM, BasicRNNCell)
MILSTM = functools.partial(_LSTM, MILSTMCell)
LayerNormLSTM = functools.partial(_LSTM, LayerNormLSTMCell)
LayerNormMILSTM = functools.partial(_LSTM, LayerNormMILSTMCell)
class UnrolledCell(RNNCell):
def __init__(self, cell, T):
self.T = T
self.cell = cell
def apply_over_sequence(
self,
model,
inputs,
seq_lengths,
initial_states,
outputs_with_grads=None,
):
inputs = self.cell.prepare_input(model, inputs)
# Now they are blob references - outputs of splitting the input sequence
split_inputs = model.net.Split(
inputs,
[str(inputs) + "_timestep_{}".format(i)
for i in range(self.T)],
axis=0)
if self.T == 1:
split_inputs = [split_inputs]
states = initial_states
all_states = []
for t in range(0, self.T):
scope_name = "timestep_{}".format(t)
# Parameters of all timesteps are shared
with ParameterSharing({scope_name: ''}),\
scope.NameScope(scope_name):
timestep = model.param_init_net.ConstantFill(
[], "timestep", value=t, shape=[1],
dtype=core.DataType.INT32,
device_option=core.DeviceOption(caffe2_pb2.CPU))
states = self.cell._apply(
model=model,
input_t=split_inputs[t],
seq_lengths=seq_lengths,
states=states,
timestep=timestep,
)
all_states.append(states)
all_states = zip(*all_states)
all_states = [
model.net.Concat(
list(full_output),
[
str(full_output[0])[len("timestep_0/"):] + "_concat",
str(full_output[0])[len("timestep_0/"):] + "_concat_info"
],
axis=0)[0]
for full_output in all_states
]
outputs = tuple(
six.next(it) for it in
itertools.cycle([iter(all_states), iter(states)])
)
outputs_without_grad = set(range(len(outputs))) - set(
outputs_with_grads)
for i in outputs_without_grad:
model.net.ZeroGradient(outputs[i], [])
logging.debug("Added 0 gradients for blobs:",
[outputs[i] for i in outputs_without_grad])
final_output = self.cell._prepare_output_sequence(model, outputs)
return final_output, outputs
def GetLSTMParamNames():
weight_params = ["input_gate_w", "forget_gate_w", "output_gate_w", "cell_w"]
bias_params = ["input_gate_b", "forget_gate_b", "output_gate_b", "cell_b"]
return {'weights': weight_params, 'biases': bias_params}
def InitFromLSTMParams(lstm_pblobs, param_values):
'''
Set the parameters of LSTM based on predefined values
'''
weight_params = GetLSTMParamNames()['weights']
bias_params = GetLSTMParamNames()['biases']
for input_type in viewkeys(param_values):
weight_values = [
param_values[input_type][w].flatten()
for w in weight_params
]
wmat = np.array([])
for w in weight_values:
wmat = np.append(wmat, w)
bias_values = [
param_values[input_type][b].flatten()
for b in bias_params
]
bm = np.array([])
for b in bias_values:
bm = np.append(bm, b)
weights_blob = lstm_pblobs[input_type]['weights']
bias_blob = lstm_pblobs[input_type]['biases']
cur_weight = workspace.FetchBlob(weights_blob)
cur_biases = workspace.FetchBlob(bias_blob)
workspace.FeedBlob(
weights_blob,
wmat.reshape(cur_weight.shape).astype(np.float32))
workspace.FeedBlob(
bias_blob,
bm.reshape(cur_biases.shape).astype(np.float32))
def cudnn_LSTM(model, input_blob, initial_states, dim_in, dim_out,
scope, recurrent_params=None, input_params=None,
num_layers=1, return_params=False):
'''
CuDNN version of LSTM for GPUs.
input_blob Blob containing the input. Will need to be available
when param_init_net is run, because the sequence lengths
and batch sizes will be inferred from the size of this
blob.
initial_states tuple of (hidden_init, cell_init) blobs
dim_in input dimensions
dim_out output/hidden dimension
scope namescope to apply
recurrent_params dict of blobs containing values for recurrent
gate weights, biases (if None, use random init values)
See GetLSTMParamNames() for format.
input_params dict of blobs containing values for input
gate weights, biases (if None, use random init values)
See GetLSTMParamNames() for format.
num_layers number of LSTM layers
return_params if True, returns (param_extract_net, param_mapping)
where param_extract_net is a net that when run, will
populate the blobs specified in param_mapping with the
current gate weights and biases (input/recurrent).
Useful for assigning the values back to non-cuDNN
LSTM.
'''
with core.NameScope(scope):
weight_params = GetLSTMParamNames()['weights']
bias_params = GetLSTMParamNames()['biases']
input_weight_size = dim_out * dim_in
upper_layer_input_weight_size = dim_out * dim_out
recurrent_weight_size = dim_out * dim_out
input_bias_size = dim_out
recurrent_bias_size = dim_out
def init(layer, pname, input_type):
input_weight_size_for_layer = input_weight_size if layer == 0 else \
upper_layer_input_weight_size
if pname in weight_params:
sz = input_weight_size_for_layer if input_type == 'input' \
else recurrent_weight_size
elif pname in bias_params:
sz = input_bias_size if input_type == 'input' \
else recurrent_bias_size
else:
assert False, "unknown parameter type {}".format(pname)
return model.param_init_net.UniformFill(
[],
"lstm_init_{}_{}_{}".format(input_type, pname, layer),
shape=[sz])
# Multiply by 4 since we have 4 gates per LSTM unit
first_layer_sz = input_weight_size + recurrent_weight_size + \
input_bias_size + recurrent_bias_size
upper_layer_sz = upper_layer_input_weight_size + \
recurrent_weight_size + input_bias_size + \
recurrent_bias_size
total_sz = 4 * (first_layer_sz + (num_layers - 1) * upper_layer_sz)
weights = model.create_param(
'lstm_weight',
shape=[total_sz],
initializer=Initializer('UniformFill'),
tags=ParameterTags.WEIGHT,
)
lstm_args = {
'hidden_size': dim_out,
'rnn_mode': 'lstm',
'bidirectional': 0, # TODO
'dropout': 1.0, # TODO
'input_mode': 'linear', # TODO
'num_layers': num_layers,
'engine': 'CUDNN'
}
param_extract_net = core.Net("lstm_param_extractor")
param_extract_net.AddExternalInputs([input_blob, weights])
param_extract_mapping = {}
# Populate the weights-blob from blobs containing parameters for
# the individual components of the LSTM, such as forget/input gate
# weights and bises. Also, create a special param_extract_net that
# can be used to grab those individual params from the black-box
# weights blob. These results can be then fed to InitFromLSTMParams()
for input_type in ['input', 'recurrent']:
param_extract_mapping[input_type] = {}
p = recurrent_params if input_type == 'recurrent' else input_params
if p is None:
p = {}
for pname in weight_params + bias_params:
for j in range(0, num_layers):
values = p[pname] if pname in p else init(j, pname, input_type)
model.param_init_net.RecurrentParamSet(
[input_blob, weights, values],
weights,
layer=j,
input_type=input_type,
param_type=pname,
**lstm_args
)
if pname not in param_extract_mapping[input_type]:
param_extract_mapping[input_type][pname] = {}
b = param_extract_net.RecurrentParamGet(
[input_blob, weights],
["lstm_{}_{}_{}".format(input_type, pname, j)],
layer=j,
input_type=input_type,
param_type=pname,
**lstm_args
)
param_extract_mapping[input_type][pname][j] = b
(hidden_input_blob, cell_input_blob) = initial_states
output, hidden_output, cell_output, rnn_scratch, dropout_states = \
model.net.Recurrent(
[input_blob, hidden_input_blob, cell_input_blob, weights],
["lstm_output", "lstm_hidden_output", "lstm_cell_output",
"lstm_rnn_scratch", "lstm_dropout_states"],
seed=random.randint(0, 100000), # TODO: dropout seed
**lstm_args
)
model.net.AddExternalOutputs(
hidden_output, cell_output, rnn_scratch, dropout_states)
if return_params:
param_extract = param_extract_net, param_extract_mapping
return output, hidden_output, cell_output, param_extract
else:
return output, hidden_output, cell_output
def LSTMWithAttention(
model,
decoder_inputs,
decoder_input_lengths,
initial_decoder_hidden_state,
initial_decoder_cell_state,
initial_attention_weighted_encoder_context,
encoder_output_dim,
encoder_outputs,
encoder_lengths,
decoder_input_dim,
decoder_state_dim,
scope,
attention_type=AttentionType.Regular,
outputs_with_grads=(0, 4),
weighted_encoder_outputs=None,
lstm_memory_optimization=False,
attention_memory_optimization=False,
forget_bias=0.0,
forward_only=False,
):
'''
Adds a LSTM with attention mechanism to a model.
The implementation is based on https://arxiv.org/abs/1409.0473, with
a small difference in the order
how we compute new attention context and new hidden state, similarly to
https://arxiv.org/abs/1508.04025.
The model uses encoder-decoder naming conventions,
where the decoder is the sequence the op is iterating over,
while computing the attention context over the encoder.
model: ModelHelper object new operators would be added to
decoder_inputs: the input sequence in a format T x N x D
where T is sequence size, N - batch size and D - input dimension
decoder_input_lengths: blob containing sequence lengths
which would be passed to LSTMUnit operator
initial_decoder_hidden_state: initial hidden state of LSTM
initial_decoder_cell_state: initial cell state of LSTM
initial_attention_weighted_encoder_context: initial attention context
encoder_output_dim: dimension of encoder outputs
encoder_outputs: the sequence, on which we compute the attention context
at every iteration
encoder_lengths: a tensor with lengths of each encoder sequence in batch
(may be None, meaning all encoder sequences are of same length)
decoder_input_dim: input dimension (last dimension on decoder_inputs)
decoder_state_dim: size of hidden states of LSTM
attention_type: One of: AttentionType.Regular, AttentionType.Recurrent.
Determines which type of attention mechanism to use.
outputs_with_grads : position indices of output blobs which will receive
external error gradient during backpropagation
weighted_encoder_outputs: encoder outputs to be used to compute attention
weights. In the basic case it's just linear transformation of
encoder outputs (that the default, when weighted_encoder_outputs is None).
However, it can be something more complicated - like a separate
encoder network (for example, in case of convolutional encoder)
lstm_memory_optimization: recompute LSTM activations on backward pass, so
we don't need to store their values in forward passes
attention_memory_optimization: recompute attention for backward pass
forward_only: whether to create only forward pass
'''
cell = LSTMWithAttentionCell(
encoder_output_dim=encoder_output_dim,
encoder_outputs=encoder_outputs,
encoder_lengths=encoder_lengths,
decoder_input_dim=decoder_input_dim,
decoder_state_dim=decoder_state_dim,
name=scope,
attention_type=attention_type,
weighted_encoder_outputs=weighted_encoder_outputs,
forget_bias=forget_bias,
lstm_memory_optimization=lstm_memory_optimization,
attention_memory_optimization=attention_memory_optimization,
forward_only=forward_only,
)
initial_states = [
initial_decoder_hidden_state,
initial_decoder_cell_state,
initial_attention_weighted_encoder_context,
]
if attention_type == AttentionType.SoftCoverage:
initial_states.append(cell.build_initial_coverage(model))
_, result = cell.apply_over_sequence(
model=model,
inputs=decoder_inputs,
seq_lengths=decoder_input_lengths,
initial_states=initial_states,
outputs_with_grads=outputs_with_grads,
)
return result
def _layered_LSTM(
model, input_blob, seq_lengths, initial_states,
dim_in, dim_out, scope, outputs_with_grads=(0,), return_params=False,
memory_optimization=False, forget_bias=0.0, forward_only=False,
drop_states=False, create_lstm=None):
params = locals() # leave it as a first line to grab all params
params.pop('create_lstm')
if not isinstance(dim_out, list):
return create_lstm(**params)
elif len(dim_out) == 1:
params['dim_out'] = dim_out[0]
return create_lstm(**params)
assert len(dim_out) != 0, "dim_out list can't be empty"
assert return_params is False, "return_params not supported for layering"
for i, output_dim in enumerate(dim_out):
params.update({
'dim_out': output_dim
})
output, last_output, all_states, last_state = create_lstm(**params)
params.update({
'input_blob': output,
'dim_in': output_dim,
'initial_states': (last_output, last_state),
'scope': scope + '_layer_{}'.format(i + 1)
})
return output, last_output, all_states, last_state
layered_LSTM = functools.partial(_layered_LSTM, create_lstm=LSTM)
|
## @package _import_c_extension
# Module caffe2.python._import_c_extension
import atexit
import logging
import sys
from caffe2.python import extension_loader
# We will first try to load the gpu-enabled caffe2. If it fails, we will then
# attempt to load the cpu version. The cpu backend is the minimum required, so
# if that still fails, we will exit loud.
with extension_loader.DlopenGuard():
try:
from caffe2.python.caffe2_pybind11_state_gpu import * # noqa
if num_cuda_devices(): # noqa
has_gpu_support = True
else:
has_gpu_support = False
except ImportError as e:
logging.warning(
'This caffe2 python run does not have GPU support. '
'Will run in CPU only mode.')
logging.warning('Debug message: {0}'.format(str(e)))
has_gpu_support = False
try:
from caffe2.python.caffe2_pybind11_state import * # noqa
except ImportError as e:
logging.critical(
'Cannot load caffe2.python. Error: {0}'.format(str(e)))
sys.exit(1)
# libcaffe2_python contains a global Workspace that we need to properly delete
# when exiting. Otherwise, cudart will cause segfaults sometimes.
atexit.register(on_module_exit) # noqa
# Add functionalities for the TensorCPU interface.
def _TensorCPU_shape(self):
return tuple(self._shape)
def _TensorCPU_reshape(self, shape):
return self._reshape(list(shape))
TensorCPU.shape = property(_TensorCPU_shape) # noqa
TensorCPU.reshape = _TensorCPU_reshape # noqa
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from multiprocessing import Process, Manager
import numpy as np
import unittest
import tempfile
import shutil
import logging
from hypothesis import given
import hypothesis.strategies as st
log = logging.getLogger("parallelize_bmuf_distributed_test")
log.setLevel(logging.INFO)
def bmuf_process(filestore_dir, process_id, shared_results,
cpu_device=False, nesterov=False):
# We need to import caffe2 in every process to initialize CUDA independently.
from caffe2.python import core, cnn, data_parallel_model, dyndep, workspace
from caffe2.proto import caffe2_pb2
dyndep.InitOpsLibrary("@/caffe2/caffe2/distributed:file_store_handler_ops")
if not cpu_device:
if not workspace.has_gpu_support:
log.info('No GPU support test is Ignored.')
return
if workspace.NumCudaDevices() < 4:
log.info('Not enough GPU support, test IGNORED')
return
model = cnn.CNNModelHelper(
order="NHWC",
name="test"
)
if not cpu_device:
device_type = caffe2_pb2.CUDA
device_prefix = "gpu"
else:
device_type = caffe2_pb2.CPU
device_prefix = "cpu"
devices = [0, 1] if process_id == 0 else [2, 3]
def _model_build_fun(model, loss_scale):
fc = model.FC(
"data", "fc", 16, 1, ("ConstantFill", {}), ("ConstantFill", {})
)
fc_fl = model.FlattenToVec(fc, "fc_fl")
sigm = model.Sigmoid(fc_fl, "sigm")
sq = model.SquaredL2Distance([sigm, "label"], "sq")
loss = model.AveragedLoss(sq, "loss")
loss = model.Scale(loss, scale=loss_scale)
# For testing explicit sync
model.param_init_net.UniformFill([], ["sync_num"], shape=[1])
return [loss]
def _input_builder_fun(model):
return None
def _param_update_fun(model):
ITER = model.Iter("ITER")
LR = model.net.LearningRate(
[ITER],
"LR",
base_lr=(-0.1),
policy="fixed",
)
ONE = model.param_init_net.ConstantFill(
[], "ONE", shape=[1], value=1.0,
)
for param in model.GetParams():
grad = model.param_to_grad[param]
model.WeightedSum([param, ONE, grad, LR], param)
def _generate_data(devices, process_id, device_type, device_prefix):
np.random.seed(26 + process_id * 10)
# Each run has same input, independent of number of gpus
batch_size = 64
for _ in range(0, 10):
full_data = np.random.rand(batch_size, 16)
full_labels = np.round(full_data[:, 0])
batch_per_device = batch_size // len(devices)
for (j, g) in enumerate(devices):
st = j * batch_per_device
en = st + batch_per_device
data = full_data[st:en, :].astype(np.float32)
labels = full_labels[st:en].astype(np.float32)
with core.DeviceScope(core.DeviceOption(device_type, g)):
workspace.FeedBlob("{}_{}/data".format(device_prefix, g), data)
workspace.FeedBlob("{}_{}/label".format(device_prefix, g), labels)
_generate_data(devices, process_id, device_type, device_prefix)
workspace.RunOperatorOnce(
core.CreateOperator(
"FileStoreHandlerCreate", [], ["store_handler"],
path=filestore_dir
)
)
rendezvous = dict(
kv_handler="store_handler",
shard_id=process_id,
num_shards=2,
engine="GLOO",
exit_nets=None
)
data_parallel_model.Parallelize_BMUF(
model,
_input_builder_fun,
_model_build_fun,
_param_update_fun,
devices=devices,
rendezvous=rendezvous,
nesterov=nesterov,
add_blobs_to_sync=["sync_num"],
cpu_device=cpu_device
)
data_parallel_model.RunInitNet(model)
def _device_pid(device, pid):
if pid == 1:
return device + 2
return device
np.testing.assert_equal(
workspace.FetchBlob("{}_{}/fc_w_v".format(
device_prefix, _device_pid(0, process_id))),
np.zeros(16).astype(np.float32).reshape(1, 16)
)
# Run the algorithm for one iteration to have non-zero params.
data_parallel_model.RunNet(model, 1)
# Save iteration momentum and post local update params
results = {}
v_b_ = workspace.FetchBlob(
"{}_{}/fc_b_v".format(device_prefix, _device_pid(0, process_id)))
v_w_ = workspace.FetchBlob(
"{}_{}/fc_w_v".format(device_prefix, _device_pid(0, process_id)))
results['v_b_'] = v_b_
results['v_w_'] = v_w_
workspace.RunNetOnce(model.net)
b_0_ = workspace.FetchBlob(
"{}_{}/fc_b".format(device_prefix, _device_pid(0, process_id)))
w_0_ = workspace.FetchBlob(
"{}_{}/fc_w".format(device_prefix, _device_pid(0, process_id)))
b_1_ = workspace.FetchBlob(
"{}_{}/fc_b".format(device_prefix, _device_pid(1, process_id)))
w_1_ = workspace.FetchBlob(
"{}_{}/fc_w".format(device_prefix, _device_pid(1, process_id)))
results['b_0_'] = b_0_
results['w_0_'] = w_0_
results['b_1_'] = b_1_
results['w_1_'] = w_1_
# Test sync
if process_id == 0:
workspace.FeedBlob(
device_prefix + "_0/sync_num",
np.array([2603]).astype(np.float32),
device_option=core.DeviceOption(device_type, 0))
# Compute block gradients.
b_g_ = workspace.FetchBlob(
"{}_{}/fc_b_g".format(device_prefix, _device_pid(0, process_id)))
w_g_ = workspace.FetchBlob(
"{}_{}/fc_w_g".format(device_prefix, _device_pid(0, process_id)))
results['b_g_'] = b_g_
results['w_g_'] = w_g_
workspace.RunNetOnce(model._global_model_param_updates_net)
# g_b = (b_0_ + b_1_) / 2 - b_g_
# g_w = (w_0_ + w_1_) / 2 - w_g_
v_b = workspace.FetchBlob(
"{}_{}/fc_b_v".format(device_prefix, _device_pid(0, process_id)))
v_w = workspace.FetchBlob(
"{}_{}/fc_w_v".format(device_prefix, _device_pid(0, process_id)))
w_g = workspace.FetchBlob(
"{}_{}/fc_w_g".format(device_prefix, _device_pid(0, process_id)))
b_g = workspace.FetchBlob(
"{}_{}/fc_b_g".format(device_prefix, _device_pid(0, process_id)))
w_0 = workspace.FetchBlob(
"{}_{}/fc_w".format(device_prefix, _device_pid(0, process_id)))
b_0 = workspace.FetchBlob(
"{}_{}/fc_b".format(device_prefix, _device_pid(0, process_id)))
w_1 = workspace.FetchBlob(
"{}_{}/fc_w".format(device_prefix, _device_pid(1, process_id)))
b_1 = workspace.FetchBlob(
"{}_{}/fc_b".format(device_prefix, _device_pid(1, process_id)))
results['v_b'] = v_b
results['v_w'] = v_w
results['w_g'] = w_g
results['b_g'] = b_g
results['w_0'] = w_0
results['b_0'] = b_0
results['w_1'] = w_1
results['b_1'] = b_1
# Test add_blobs_to_sync
for j in devices:
sync = workspace.FetchBlob(
device_prefix + "_{}/sync_num".format(j))[0]
results['sync_{}'.format(j)] = sync
shared_results[process_id] = results
class DistributedTest(unittest.TestCase):
@given(
cpu_device=st.booleans(),
nesterov=st.booleans()
)
def test_bmuf_distributed(self, cpu_device, nesterov):
self._test_bmuf_distributed(cpu_device=cpu_device, nesterov=nesterov)
def _test_bmuf_distributed(self, cpu_device=False, nesterov=False):
processes = []
filestore_dir = tempfile.mkdtemp()
results = Manager().dict()
for idx in range(0, 2):
process = Process(
target=bmuf_process,
args=(filestore_dir, idx, results, cpu_device, nesterov)
)
processes.append(process)
process.start()
while len(processes) > 0:
process = processes.pop()
process.join()
shutil.rmtree(filestore_dir)
if len(results) == 0:
return
w_0 = results[0]['w_0']
w_1 = results[0]['w_1']
b_0 = results[0]['b_0']
b_1 = results[0]['b_1']
# Check parameters are in sync.
np.testing.assert_equal(w_0, w_1)
np.testing.assert_equal(w_0, results[1]['w_0'])
np.testing.assert_equal(w_0, results[1]['w_1'])
np.testing.assert_equal(b_0, b_1)
np.testing.assert_equal(b_0, results[1]['b_0'])
np.testing.assert_equal(b_0, results[1]['b_1'])
w_g_ = results[0]['w_g_']
b_g_ = results[0]['b_g_']
g_b = (results[0]['b_0_'] + results[1]['b_0_'] + results[0]['b_1_'] +
results[1]['b_1_']) / 4 - b_g_
g_w = (results[0]['w_0_'] + results[1]['w_0_'] + results[0]['w_1_'] +
results[1]['w_1_']) / 4 - w_g_
v_b_ = results[0]['v_b_']
v_b = results[0]['v_b']
v_w_ = results[0]['v_w_']
v_w = results[0]['v_w']
for pid in results.keys():
for k in results[pid].keys():
if k.startswith("sync_num"):
self.assertEqual(2603, results[pid][k])
# Check block gradients are correct.
np.testing.assert_almost_equal(v_b, 0.75 * v_b_ + g_b)
np.testing.assert_almost_equal(v_w, 0.75 * v_w_ + g_w)
# Check params update step
if nesterov:
np.testing.assert_equal(w_0, w_g_ + v_w - 0.75 * (v_w - v_w_))
np.testing.assert_equal(b_0, b_g_ + v_b - 0.75 * (v_b - v_b_))
else:
np.testing.assert_equal(w_0, w_g_ + v_w)
np.testing.assert_equal(b_0, b_g_ + v_b)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
from caffe2.python import brew, rnn_cell
class GRUCell(rnn_cell.RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias, # Currently unused! Values here will be ignored.
memory_optimization,
drop_states=False,
linear_before_reset=False,
**kwargs
):
super(GRUCell, self).__init__(**kwargs)
self.input_size = input_size
self.hidden_size = hidden_size
self.forget_bias = float(forget_bias)
self.memory_optimization = memory_optimization
self.drop_states = drop_states
self.linear_before_reset = linear_before_reset
# Unlike LSTMCell, GRUCell needs the output of one gate to feed into another.
# (reset gate -> output_gate)
# So, much of the logic to calculate the reset gate output and modified
# output gate input is set here, in the graph definition.
# The remaining logic lives in in gru_unit_op.{h,cc}.
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev = states[0]
# Split input tensors to get inputs for each gate.
input_t_reset, input_t_update, input_t_output = model.net.Split(
[
input_t,
],
[
self.scope('input_t_reset'),
self.scope('input_t_update'),
self.scope('input_t_output'),
],
axis=2,
)
# Fully connected layers for reset and update gates.
reset_gate_t = brew.fc(
model,
hidden_t_prev,
self.scope('reset_gate_t'),
dim_in=self.hidden_size,
dim_out=self.hidden_size,
axis=2,
)
update_gate_t = brew.fc(
model,
hidden_t_prev,
self.scope('update_gate_t'),
dim_in=self.hidden_size,
dim_out=self.hidden_size,
axis=2,
)
# Calculating the modified hidden state going into output gate.
reset_gate_t = model.net.Sum(
[reset_gate_t, input_t_reset],
self.scope('reset_gate_t')
)
reset_gate_t_sigmoid = model.net.Sigmoid(
reset_gate_t,
self.scope('reset_gate_t_sigmoid')
)
# `self.linear_before_reset = True` matches cudnn semantics
if self.linear_before_reset:
output_gate_fc = brew.fc(
model,
hidden_t_prev,
self.scope('output_gate_t'),
dim_in=self.hidden_size,
dim_out=self.hidden_size,
axis=2,
)
output_gate_t = model.net.Mul(
[reset_gate_t_sigmoid, output_gate_fc],
self.scope('output_gate_t_mul')
)
else:
modified_hidden_t_prev = model.net.Mul(
[reset_gate_t_sigmoid, hidden_t_prev],
self.scope('modified_hidden_t_prev')
)
output_gate_t = brew.fc(
model,
modified_hidden_t_prev,
self.scope('output_gate_t'),
dim_in=self.hidden_size,
dim_out=self.hidden_size,
axis=2,
)
# Add input contributions to update and output gate.
# We already (in-place) added input contributions to the reset gate.
update_gate_t = model.net.Sum(
[update_gate_t, input_t_update],
self.scope('update_gate_t'),
)
output_gate_t = model.net.Sum(
[output_gate_t, input_t_output],
self.scope('output_gate_t_summed'),
)
# Join gate outputs and add input contributions
gates_t, _gates_t_concat_dims = model.net.Concat(
[
reset_gate_t,
update_gate_t,
output_gate_t,
],
[
self.scope('gates_t'),
self.scope('_gates_t_concat_dims'),
],
axis=2,
)
if seq_lengths is not None:
inputs = [hidden_t_prev, gates_t, seq_lengths, timestep]
else:
inputs = [hidden_t_prev, gates_t, timestep]
hidden_t = model.net.GRUUnit(
inputs,
list(self.get_state_names()),
forget_bias=self.forget_bias,
drop_states=self.drop_states,
sequence_lengths=(seq_lengths is not None),
)
model.net.AddExternalOutputs(hidden_t)
return (hidden_t,)
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=3 * self.hidden_size,
axis=2,
)
def get_state_names(self):
return (self.scope('hidden_t'),)
def get_output_dim(self):
return self.hidden_size
GRU = functools.partial(rnn_cell._LSTM, GRUCell)
|
"""A tool to inspect the binary size of a built binary file.
This script prints out a tree of symbols and their corresponding sizes, using
Linux's nm functionality.
Usage:
python binary_size.py -- \
--target=/path/to/your/target/binary \
[--nm_command=/path/to/your/custom/nm] \
[--max_depth=10] [--min_size=1024] \
[--color] \
To assist visualization, pass in '--color' to make the symbols color coded to
green, assuming that you have a xterm connection that supports color.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import subprocess
import sys
class Trie(object):
"""A simple class that represents a Trie."""
def __init__(self, name):
"""Initializes a Trie object."""
self.name = name
self.size = 0
self.dictionary = {}
def GetSymbolTrie(target, nm_command, max_depth):
"""Gets a symbol trie with the passed in target.
Args:
target: the target binary to inspect.
nm_command: the command to run nm.
max_depth: the maximum depth to create the trie.
"""
# Run nm to get a dump on the strings.
proc = subprocess.Popen(
[nm_command, '--radix=d', '--size-sort', '--print-size', target],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
nm_out, _ = proc.communicate()
if proc.returncode != 0:
print('NM command failed. Output is as follows:')
print(nm_out)
sys.exit(1)
# Run c++filt to get proper symbols.
proc = subprocess.Popen(['c++filt'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, _ = proc.communicate(input=nm_out)
if proc.returncode != 0:
print('c++filt failed. Output is as follows:')
print(out)
sys.exit(1)
# Splits the output to size and function name.
data = []
for line in out.split('\n'):
if line:
content = line.split(' ')
if len(content) < 4:
# This is a line not representing symbol sizes. skip.
continue
data.append([int(content[1]), ' '.join(content[3:])])
symbol_trie = Trie('')
for size, name in data:
curr = symbol_trie
for c in name:
if c not in curr.dictionary:
curr.dictionary[c] = Trie(curr.name + c)
curr = curr.dictionary[c]
curr.size += size
if len(curr.name) > max_depth:
break
symbol_trie.size = sum(t.size for t in symbol_trie.dictionary.values())
return symbol_trie
def MaybeAddColor(s, color):
"""Wrap the input string to the xterm green color, if color is set.
"""
if color:
return '\033[92m{0}\033[0m'.format(s)
else:
return s
def ReadableSize(num):
"""Get a human-readable size."""
for unit in ['B', 'KB', 'MB', 'GB']:
if abs(num) <= 1024.0:
return '%3.2f%s' % (num, unit)
num /= 1024.0
return '%.1f TB' % (num,)
# Note(jiayq): I know, I know, this is a recursive function, but it is
# convenient to write.
def PrintTrie(trie, prefix, max_depth, min_size, color):
"""Prints the symbol trie in a readable manner.
"""
if len(trie.name) == max_depth or not trie.dictionary.keys():
# If we are reaching a leaf node or the maximum depth, we will print the
# result.
if trie.size > min_size:
print('{0}{1} {2}'.format(
prefix,
MaybeAddColor(trie.name, color),
ReadableSize(trie.size)))
elif len(trie.dictionary.keys()) == 1:
# There is only one child in this dictionary, so we will just delegate
# to the downstream trie to print stuff.
PrintTrie(
trie.dictionary.values()[0], prefix, max_depth, min_size, color)
elif trie.size > min_size:
print('{0}{1} {2}'.format(
prefix,
MaybeAddColor(trie.name, color),
ReadableSize(trie.size)))
keys_with_sizes = [
(k, trie.dictionary[k].size) for k in trie.dictionary.keys()]
keys_with_sizes.sort(key=lambda x: x[1])
for k, _ in keys_with_sizes[::-1]:
PrintTrie(
trie.dictionary[k], prefix + ' |', max_depth, min_size, color)
def main(argv):
if not sys.platform.startswith('linux'):
raise RuntimeError('Currently this tool only supports Linux.')
parser = argparse.ArgumentParser(
description="Tool to inspect binary size.")
parser.add_argument(
'--max_depth', type=int, default=10,
help='The maximum depth to print the symbol tree.')
parser.add_argument(
'--min_size', type=int, default=1024,
help='The mininum symbol size to print.')
parser.add_argument(
'--nm_command', type=str, default='nm',
help='The path to the nm command that the tool needs.')
parser.add_argument(
'--color', action='store_true',
help='If set, use ascii color for output.')
parser.add_argument(
'--target', type=str,
help='The binary target to inspect.')
args = parser.parse_args(argv)
if not args.target:
raise RuntimeError('You must specify a target to inspect.')
symbol_trie = GetSymbolTrie(
args.target, args.nm_command, args.max_depth)
PrintTrie(symbol_trie, '', args.max_depth, args.min_size, args.color)
if __name__ == '__main__':
main(sys.argv[1:])
|
## @package core
# Module caffe2.python.core
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple, OrderedDict, defaultdict
from past.builtins import basestring
from future.utils import viewitems, viewkeys, viewvalues
from itertools import chain
from six import binary_type, string_types, text_type
from caffe2.proto import caffe2_pb2
from caffe2.python import scope, utils, workspace
from caffe2.python.control_ops_grad import \
gen_do_gradient, gen_if_gradient, gen_while_gradient
import caffe2.python._import_c_extension as C
import pickle
import numpy as np
import sys
import traceback
import os
# Mac os specific message
if (sys.platform == 'darwin' and 'leveldb' in C.registered_dbs()):
print('If you are using homebrew leveldb on a Mac OS, you might see an '
'error warning you that malloc_zone_unregister() failed. This is '
'not a caffe2 issue but is due to the homebrew leveldb having an '
'incompatible memory allocator. It does not affect usage.')
# Convenience redirections to functions inside scope.
DeviceScope = scope.DeviceScope
NameScope = scope.NameScope
# Bring datatype enums to the main namespace
class DataType:
pass
def _InitDataType():
for name, value in caffe2_pb2.TensorProto.DataType.items():
setattr(DataType, name, value)
_InitDataType()
def _GetRegisteredOperators():
return set(workspace.RegisteredOperators())
_REGISTERED_OPERATORS = _GetRegisteredOperators()
def RefreshRegisteredOperators():
global _REGISTERED_OPERATORS
_REGISTERED_OPERATORS = _GetRegisteredOperators()
_GLOBAL_INIT_ARGS = []
def GlobalInit(args):
_GLOBAL_INIT_ARGS.extend(args[1:])
C.global_init(args)
def GetGlobalInitArgs():
return _GLOBAL_INIT_ARGS[:]
def IsOperator(op_type):
return IsOperatorWithEngine(op_type, engine='DEFAULT')
def IsOperatorWithEngine(op_type, engine):
return C.op_registry_key(op_type, engine) in _REGISTERED_OPERATORS
def DeviceOption(device_type, cuda_gpu_id=0, random_seed=None, node_name=None):
option = caffe2_pb2.DeviceOption()
option.device_type = device_type
option.cuda_gpu_id = cuda_gpu_id
if node_name is not None:
option.node_name = node_name
if random_seed is not None:
option.random_seed = random_seed
return option
def device_option_equal(opt1, opt2, ignore_node_name=True, ignore_random_seed=True):
if not opt1 or not opt2:
return opt1 == opt2
if not ignore_node_name and opt1.node_name != opt2.node_name:
return False
if not ignore_random_seed and opt1.random_seed != opt2.random_seed:
return False
if not opt1.device_type or not opt2.device_type:
# At least one option is for CPU, check if both are for CPU.
return not opt1.device_type and not opt2.device_type
return opt1.cuda_gpu_id == opt2.cuda_gpu_id
def InferBlobDevices(net):
'''
Compute mapping from parameters to devices by looking at the
device option of the op that creates the blob has
'''
mapping = {}
for op in net.Proto().op:
op_device = op.device_option
if op_device is None:
op_device = caffe2_pb2.DeviceOption(caffe2_pb2.CPU)
# TODO: T18892922, use device annotations
for b in op.output:
mapping[b] = op_device
return mapping
def InferOpBlobDevices(op):
device_info = C.infer_op_input_output_device(op.SerializeToString())
input_info = []
output_info = []
for dev_str in device_info[0]:
device_option = caffe2_pb2.DeviceOption()
device_option.ParseFromString(dev_str)
input_info.append(device_option)
for dev_str in device_info[1]:
device_option = caffe2_pb2.DeviceOption()
device_option.ParseFromString(dev_str)
output_info.append(device_option)
return input_info, output_info
def InferOpDeviceAsBlobDevices(op):
op_dev = op.device_option if op.device_option else caffe2_pb2.DeviceOption()
input_dev = [op_dev] * len(op.input)
output_dev = [op_dev] * len(op.output)
return input_dev, output_dev
GradientSlice = namedtuple('GradientSlice', ['indices', 'values'])
class BlobReference(object):
"""A wrapper around a blob in a net.
BlobReference gives us a way to refer to the network that the blob is
generated from. Note that blobs are, essentially, just strings in the
current workspace.
"""
def __init__(self, name, net=None):
"""Initializes a blob reference.
Note that this does not prepends the namescope. If needed, use
ScopedBlobReference() to prepend the existing namespace.
"""
if isinstance(name, string_types):
self._name = name
elif isinstance(name, binary_type):
self._name = name.decode('utf-8')
else:
self._name = str(name)
self._from_net = net
# meta allows helper functions to put whatever metainformation needed
# there.
self.meta = {}
def __hash__(self):
return hash(self._name)
def __eq__(self, other):
if isinstance(other, string_types):
return self._name == other
elif isinstance(other, binary_type):
return self._name == other.decode('utf-8')
elif isinstance(other, BlobReference):
return self._name == other._name
else:
return False
def __ne__(self, other):
return not(self == other)
def __str__(self):
return self._name
def __repr__(self):
return 'BlobReference("{}")'.format(self._name)
def __add__(self, other):
if not isinstance(other, string_types):
raise RuntimeError('Cannot add BlobReference to a non-string.')
return BlobReference(self._name + other, self._from_net)
def __radd__(self, other):
if not isinstance(other, string_types):
raise RuntimeError('Cannot add a non-string to BlobReference.')
return BlobReference(other + self._name, self._from_net)
def Net(self):
return self._from_net
def GetNameScope(self):
return self._name[:self._name.rfind(scope._NAMESCOPE_SEPARATOR) + 1]
def _CreateAndAddToNet(self, op_type, inputs=None, *args, **kwargs):
"""Internal function that routes the operator generation to the
network's __getattr__ function.
"""
inputs = [] if inputs is None else inputs
if isinstance(inputs, BlobReference) or isinstance(inputs, string_types):
inputs = [inputs]
# add self to the input list.
inputs.insert(0, self)
return self._from_net.__getattr__(op_type)(inputs, *args, **kwargs)
def __getattr__(self, op_type):
"""A wrapper allowing one to initiate operators from a blob reference.
Example: for a blob reference b that comes from network n, doing
b.Relu(...)
is equivalent to doing
net.Relu([b], ...)
"""
if op_type.startswith('__'):
raise AttributeError('Attribute {} not found.'.format(op_type))
if self._from_net is None:
raise RuntimeError(
'You cannot use a blob reference that does not have a net '
'source to create operators. Create the operator from an '
'explicit net object.')
if not IsOperator(op_type):
raise RuntimeError(
'Method ' + op_type + ' is not a registered operator.' +
' Did you mean: [' +
",".join(workspace.C.nearby_opnames(op_type)) + ']'
)
return lambda *args, **kwargs: self._CreateAndAddToNet(
op_type, *args, **kwargs)
def __dir__(self):
additional_methods = [
op
for op in _REGISTERED_OPERATORS
if '_ENGINE_' not in op or '_ENGINE_CUDNN' in op]
return sorted(set(chain(
dir(type(self)),
viewkeys(self.__dict__),
additional_methods
)))
def ScopedName(name):
"""prefix the name with the current scope."""
if isinstance(name, binary_type):
name = name.decode('ascii')
return scope.CurrentNameScope() + name
def ScopedBlobReference(name, *args, **kwargs):
"""Returns a blob reference with scope prefixed."""
return BlobReference(ScopedName(name), *args, **kwargs)
def _RectifyInputOutput(blobs, net=None):
"""A helper function to rectify the input or output of the CreateOperator
interface.
"""
if isinstance(blobs, string_types) or isinstance(blobs, binary_type):
# If blobs is a single string, prepend scope.CurrentNameScope()
# and put it as a list.
# TODO(jiayq): enforce using BlobReference instead of raw strings.
return [ScopedBlobReference(blobs, net=net)]
elif type(blobs) is BlobReference:
# If blob is a BlobReference, simply put it as a list.
return [blobs]
elif type(blobs) in (list, tuple):
# If blob is a list, we go through it and type check.
rectified = []
for blob in blobs:
if isinstance(blob, string_types) or isinstance(blob, binary_type):
rectified.append(ScopedBlobReference(blob, net=net))
elif type(blob) is BlobReference:
rectified.append(blob)
else:
raise TypeError(
"I/O blob #{} of unsupported type: {} of type {}"
.format(len(rectified), str(blob), type(blob)))
return rectified
else:
raise TypeError(
"Unknown input/output type: %s of type %s." %
(str(blobs), type(blobs))
)
def CreateOperator(
operator_type,
inputs,
outputs,
name='',
control_input=None,
device_option=None,
arg=None,
engine=None,
**kwargs
):
"""A function wrapper that allows one to create operators based on the
operator type. The type should be a string corresponding to an operator
registered with Caffe2.
"""
operator = caffe2_pb2.OperatorDef()
if (os.environ.get('CAFFE2_DEBUG')):
stack = traceback.format_stack()
operator.debug_info = "".join(stack[:-1])
operator.type = operator_type
operator.name = name
# Add rectified inputs and outputs
inputs = _RectifyInputOutput(inputs)
outputs = _RectifyInputOutput(outputs)
operator.input.extend([text_type(i) for i in inputs])
operator.output.extend([text_type(o) for o in outputs])
if control_input:
control_input = _RectifyInputOutput(control_input)
operator.control_input.extend([text_type(i) for i in control_input])
# Set device option:
# (1) If device_option is explicitly set, use device_option.
# (2) If not, but scope.CurrentDeviceScope() is set,
# then we use scope.CurrentDeviceScope().
# (3) Otherwise, do not set device option.
if device_option is not None:
operator.device_option.CopyFrom(device_option)
elif scope.CurrentDeviceScope() is not None:
operator.device_option.CopyFrom(scope.CurrentDeviceScope())
if engine is not None:
operator.engine = engine
# random seed is defined in the device option, so we need to do special
# care.
if 'random_seed' in kwargs:
operator.device_option.random_seed = kwargs['random_seed']
del kwargs['random_seed']
# Add given arguments that do not need parsing
if arg is not None:
operator.arg.extend(arg)
# Add all other arguments
for key, value in viewitems(kwargs):
operator.arg.add().CopyFrom(utils.MakeArgument(key, value))
if workspace.IsImmediate():
workspace.RunOperatorImmediate(operator)
return operator
def _RegisterPythonImpl(
f, grad_f=None, python_func_type=None, pass_workspace=False
):
if python_func_type:
func = python_func_type(f)
f = func.forward
grad_f = func.backward
else:
if isinstance(f, tuple):
f = f[0](*f[1], **f[2])
if isinstance(grad_f, tuple):
grad_f = grad_f[0](*grad_f[1], **grad_f[2])
token = C.register_python_op(f, pass_workspace, '')
if grad_f:
C.register_python_gradient_op(token, grad_f)
return token
def CreatePythonOperator(
f, inputs,
outputs,
grad_f=None,
pass_workspace=False,
python_func_type=None,
*args,
**kwargs
):
"""
`f` should have a signature (inputs, outputs)
If `pass_workspace` is True, the signature is changed to
(inputs, outputs, workspace) where `workspace` is the workspace the op
is going to run on. This is potentially dangerous (as the op can manipulate
the workspace directly), use on your own risk.
"""
kwargs["token"] = _RegisterPythonImpl(
f, grad_f, python_func_type, pass_workspace=pass_workspace
)
return CreateOperator("Python", inputs, outputs, *args, **kwargs)
def GetIndexFromGradientList(g_list, name):
"""A helper function to get the index from a gradient list, None if not
matching."""
for i, g in enumerate(g_list):
if g == name:
return i
elif type(g) is GradientSlice:
if (g.indices == name or g.values == name):
return i
return None
OpSSA = namedtuple('OpSSA', ['op', 'in_versions', 'out_versions'])
GradGenMeta = namedtuple('GradGenMeta', ['grad_op', 'idx', 'gradient'])
SparseGradGenMeta = namedtuple('SparseGradGenMeta', [
'grad_op_indices', 'idx_indices',
'grad_op_values', 'idx_values',
'gradient',
])
class IR(object):
"""A simple IR class to keep track of all intermediate representations used
in the gradient computation.
"""
def __init__(self, operators):
# The IR class holds multiple metadata from the forward pass:
# a) ssa: a list of [op, in_versions, out_versions] recording the
# input and the output version of each operator, similar
# to a normal SSA form.
# b) input_count: a dictionary specifying for each blob and
# each of its version, how many times it is used as input for another
# op.
# c) frontier: maintaining the current versions of the blobs
# we are having in the workspace, after the execution of all the ops
# added to the IR so far. This is useful because if a gradient is
# trying to access an earlier version of a blob, we can sanity check
# that it is no longer there, and thus throw an error.
# d) gradient_frontier: maps the names of blobs to its version that the
# gradient corresponds to.
# e) gradient_generators: for each blob and each of its version, maps to
# a list of operators that generates its gradient together with the
# gradient name.
self.ssa = []
self.input_usages = defaultdict(lambda: defaultdict(list))
self.frontier = defaultdict(int)
self.gradient_frontier = {}
self.gradient_generators = defaultdict(lambda: defaultdict(list))
self.out_version_history = defaultdict(list)
self.in_version_history = defaultdict(list)
for op in operators:
self.Play(op)
self.SanityCheck(operators)
def SanityCheck(self, operators):
# Validate StopGradient usage by checking that StopGradient's output
# is actually passed forward
for op in operators:
if op.type == 'StopGradient':
if op.output[0] not in self.input_usages:
raise ValueError("""StopGradient's output '{}' is orphan.
You typically want to specify same input and output for
StopGradient. Op:\n\n{}""".format(op.output[0], str(op)))
def Play(self, op):
""""Adds an op to the current IR, and update the internal states to
reflect the blobs and versions after the execution of the op.
"""
# For input, they are the current version in the dict.
in_versions = {}
for s in op.input:
in_versions[s] = self.frontier[s]
self.input_usages[s][self.frontier[s]].append(len(self.ssa))
self.in_version_history[s].append((op, self.frontier[s]))
# For output, they are the current version plus one. If this is a
# newly created blob, its version starts with zero.
out_versions = {}
for s in op.output:
if s in self.frontier:
self.frontier[s] += 1
out_versions[s] = self.frontier[s]
self.out_version_history[s].append((op, self.frontier[s]))
# Add to SSA for bookkeeping.
self.ssa.append(OpSSA(op, in_versions, out_versions))
def CheckGradientOperatorInput(
self, grad_op_input, g_output, fwd_op_idx, locally_generated_blobs):
"""Checks if the gradient operators can be correctly carried out."""
forward_op, in_versions, out_versions = self.ssa[fwd_op_idx]
original_index = GetIndexFromGradientList(g_output, grad_op_input)
# Functions to generate debug help for version-mismatches
def versionMismatchInfoOut(name):
s = "DEBUG HELP:\n"
s += "Maybe you use same output blob twice for different ops?\n"
s += "== Version history of blob [{}]\n".format(name)
for (op, vers) in self.out_version_history[name]:
s += "Version (out) {} <-- {}".format(vers, op)
s += "\n"
return s
def versionMismatchInfoIn(name):
s = "DEBUG HELP:\n"
s += "Maybe the blob was overwritten by another op?\n"
s += "== Version history of blob [{}]\n".format(name)
for (op, vers) in self.in_version_history[name]:
s += "version (in) {} <-- {}".format(vers, op)
s += "\n"
return s
# If it is a dense or sparse gradient name, it should match the
# version of the corresponding output.
if original_index is not None:
original_name = forward_op.output[original_index]
if (out_versions[original_name] !=
self.gradient_frontier[original_name]):
raise RuntimeError(
'Gradient name "%s" is expected to correspond '
'to version %d of "%s", but currently we have '
'version %d.\n\n' % (
grad_op_input, out_versions[original_name],
original_name,
self.gradient_frontier[original_name]) +
versionMismatchInfoOut(original_name))
# If it is an output name, the current version should match the
# version when the operator was run.
elif grad_op_input in out_versions:
if self.frontier[grad_op_input] != out_versions[grad_op_input]:
raise RuntimeError(
'Gradient operator needs output "%s" at version'
' %d, but currently we have version %d.\n\n' % (
grad_op_input, out_versions[grad_op_input],
self.frontier[grad_op_input]
) + versionMismatchInfoOut(grad_op_input)
)
# If it is an input name, the current version should match the
# version when the operator was run.
elif grad_op_input in in_versions:
if (self.frontier[grad_op_input] != in_versions[grad_op_input]):
raise RuntimeError(
'Gradient operator needs input "%s" at version '
'%d, but currently we have version %d.\n\n' % (
grad_op_input, in_versions[grad_op_input],
self.frontier[grad_op_input]
) + versionMismatchInfoIn(grad_op_input)
)
# If it is none of the above, it should be a blob that is
# generated locally by one of the previous gradient operators.
else:
if grad_op_input not in locally_generated_blobs:
raise RuntimeError(
'Blob name "%s" not in the scope of operator: '
'%s\nand is not generated by any of the local '
'gradient operators.' % (grad_op_input, str(forward_op))
)
def AppendSparseGenerators(self, sparse_generators):
# merge indices and values generators for sparse gradients
for name, input_generators in viewitems(sparse_generators):
for version, generators in viewitems(input_generators):
if len(generators) == 1:
# either indices or values are generated (but not both)
generator = generators[0]
else:
# both indices and values are generated
assert(len(generators) == 2)
op1_i, idx1_i, op1_v, idx1_v, g1 = generators[0]
op2_i, idx2_i, op2_v, idx2_v, g2 = generators[1]
assert(g1 == g2)
assert(op1_i is None or op2_i is None)
assert(op1_v is None or op2_v is None)
assert(idx1_i == 0 or idx2_i == 0)
assert(idx1_v == 0 or idx2_v == 0)
generator = SparseGradGenMeta(
op1_i or op2_i, idx1_i + idx2_i,
op1_v or op2_v, idx1_v + idx2_v,
g1)
self.gradient_generators[name][version].append(generator)
def BuildGradientGenerators( # NOQA
self, fwd_op_idx, gradient_ops, g_output, g_input):
"""Updates gradient_generators and gradient_frontier"""
forward_op, in_versions, out_versions = self.ssa[fwd_op_idx]
locally_generated_blobs = []
sparse_generators = defaultdict(lambda: defaultdict(list))
for grad_op in gradient_ops:
# (1) check that inputs are valid
for s in grad_op.input:
self.CheckGradientOperatorInput(
s, g_output, fwd_op_idx, locally_generated_blobs)
# (2) add outputs to the locally generated blobs
# If an output corresponds to the gradient of an input, we also
# record it to gradient_generators
locally_generated_blobs.extend([str(s) for s in grad_op.output])
for i, output in enumerate(grad_op.output):
input_index = GetIndexFromGradientList(g_input, output)
if input_index is not None:
input_name = forward_op.input[input_index]
input_version = in_versions[input_name]
g = g_input[input_index]
if type(g) is GradientSlice:
# the output corresponds either to the indices or the
# values of the sparse gradient. In either case we
# create a (partial) SparseGradGenMeta. If necessary,
# we'll merge indices and values generators
# corresponding to the same gradient in step (3)
if g.indices == output:
m = SparseGradGenMeta(grad_op, i, None, 0, g)
else:
assert(g.values == output)
m = SparseGradGenMeta(None, 0, grad_op, i, g)
sparse_generators[input_name][input_version].append(m)
else:
self.gradient_generators[input_name][input_version] \
.append(GradGenMeta(
grad_op, i, g))
# (3) merge indices and values generators for sparse gradients, and
# add them to gradient_generators
self.AppendSparseGenerators(sparse_generators)
# (4) for ops (e.g., Add, Sum, Sub) which have gradient outputs directly
# passed from inputs (not computed from gradient ops), we create an
# GradGenMeta with None grad_op and idx so that the gradient_generators
# knows where the gradients are coming from. This is needed for creating
# Sum op to accumulate the gradients from multiple parents.
for input_index, g in enumerate(g_input):
input_name = forward_op.input[input_index]
input_version = in_versions[input_name]
if not g:
continue
if type(g) is GradientSlice:
if str(g.indices) not in locally_generated_blobs and \
str(g.values) not in locally_generated_blobs:
self.gradient_generators[input_name][input_version].append(
SparseGradGenMeta(None, 0, None, 0, g))
else:
if str(g) not in locally_generated_blobs:
self.gradient_generators[input_name][input_version].append(
GradGenMeta(None, 0, g))
# Finally, for the gradients specified in g_input, we update the
# gradient frontier to reflect the input versions that the gradients
# correspond to.
for i, g in enumerate(g_input):
if g is not None:
input_name = forward_op.input[i]
input_version = in_versions[input_name]
self.gradient_frontier[input_name] = input_version
def _GetSumOpOutputName(self, generator, input_name):
def remove_suffix(s, suffix):
if s.endswith(suffix):
return s[:-len(suffix)]
return s
for g in generator:
if type(g) is GradGenMeta:
grad_op, idx, _ = g
if grad_op:
return grad_op.output[idx]
else:
assert(type(g) is SparseGradGenMeta)
op_i, idx_i, op_v, idx_v, _ = g
if op_i:
return remove_suffix(op_i.output[idx_i], '_indices')
if op_v:
return remove_suffix(op_v.output[idx_v], '_values')
return input_name + '_grad'
def _SetSumOpsDeviceOption(self, sum_ops, generators):
# we already checked that device options are consistent so we can just
# use the first one we find
for generator in generators:
grad_op = generator.grad_op if type(generator) is GradGenMeta \
else generator.grad_op_values or generator.grad_op_indices
if grad_op:
if grad_op.HasField('device_option'):
for op in sum_ops:
op.device_option.CopyFrom(grad_op.device_option)
break
def _DisambiguateGradOpOutput(self, grad_op, idx, cnt):
grad_op.output[idx] = (
'_' + grad_op.output[idx] + '_autosplit_{}'.format(cnt))
return grad_op.output[idx], cnt + 1
def _CheckSumOpsConflict(self, out_base_name, g):
if str(out_base_name) == str(g):
# TODO not sure what this message really means
raise RuntimeError(
'The gradient output of empty gradient op can not '
'be the same as the normal name of the current '
'input gradient.')
def _MakeDenseSumOps(self, generators, out_base_name):
sum_op_input = []
cnt = 0
assert len(generators) > 1
first_grad_op = True
for generator in generators:
grad_op, idx, g = generator
assert(type(g) is not GradientSlice)
if grad_op:
if first_grad_op:
first_grad_op = False
out = grad_op.output[idx]
else:
out, cnt = self._DisambiguateGradOpOutput(grad_op, idx, cnt)
sum_op_input.append(out)
else:
self._CheckSumOpsConflict(out_base_name, g)
sum_op_input.append(str(g))
if out_base_name in sum_op_input:
# Sum inplace mode works only for the first input
# So we do a swap
idx = sum_op_input.index(out_base_name)
sum_op_input[0], sum_op_input[idx] = (
sum_op_input[idx], sum_op_input[0]
)
sum_ops = [CreateOperator(
"Sum",
[BlobReference(x) for x in sum_op_input],
BlobReference(out_base_name))]
return sum_ops, out_base_name
def _MakeSparseSumOps(self, generators, out_base_name):
indices_concat_input = []
values_concat_input = []
cnt_i = 0
cnt_v = 0
for generator in generators:
assert(type(generator) is SparseGradGenMeta)
op_i, idx_i, op_v, idx_v, g = generator
if op_i:
out, cnt_i = self._DisambiguateGradOpOutput(op_i, idx_i, cnt_i)
indices_concat_input.append(out)
else:
self._CheckSumOpsConflict(out_base_name, g.indices)
indices_concat_input.append(g.indices)
if op_v:
out, cnt_v = self._DisambiguateGradOpOutput(op_v, idx_v, cnt_v)
values_concat_input.append(out)
else:
self._CheckSumOpsConflict(out_base_name, g.values)
values_concat_input.append(g.values)
indices_concat_output = out_base_name + '_indices_concat'
indices_concat_split = out_base_name + '_indices_concat_split'
values_concat_output = out_base_name + '_values_concat'
values_concat_split = out_base_name + '_values_concat_split'
# Sum the given sparse representations by simply concatenating the
# indices (resp. values) tensors together. We don't do any deduplication
# of indices at this point. This will be done as needed before the
# optimizer is called
sum_ops = [
CreateOperator(
"Concat",
[BlobReference(x) for x in indices_concat_input],
[BlobReference(x) for x in
[indices_concat_output, indices_concat_split]],
axis=0
),
CreateOperator(
"Concat",
[BlobReference(x) for x in values_concat_input],
[BlobReference(x) for x in
[values_concat_output, values_concat_split]],
axis=0
),
]
sum_op_output = GradientSlice(
indices=indices_concat_output,
values=values_concat_output,
)
return sum_ops, sum_op_output
def _MakeSumOps(self, input_name, input_version):
generators = self.gradient_generators[input_name][input_version]
out_base_name = self._GetSumOpOutputName(generators, input_name)
types = list(set(type(x) for x in generators))
assert(len(types) == 1)
if types[0] is GradGenMeta:
sum_ops, g = self._MakeDenseSumOps(generators, out_base_name)
else:
assert(types[0] is SparseGradGenMeta)
sum_ops, g = self._MakeSparseSumOps(generators, out_base_name)
self._SetSumOpsDeviceOption(sum_ops, generators)
return sum_ops, g
def _VerifyGradientGenerators(self, generator):
# (1) check if all gradients are of the same type. Aggregating a mix of
# sparse and dense gradients is not supported yet
if len({type(g) for g in generator}) > 1:
raise RuntimeError(
'Automatic aggregation of a mix of sparse and dense gradients '
'is not supported yet')
# If for all the operators that used the operator, none or only one
# produced the gradient, then no additional sum needs to be carried
# out.
if len(generator) < 2:
return False
all_gradient_names = []
all_device_options = []
for g in generator:
if type(g) is GradGenMeta:
if g.grad_op:
all_gradient_names.append(g.gradient)
all_device_options.append(g.grad_op.device_option)
else:
assert(type(g) is SparseGradGenMeta)
if g.grad_op_indices:
all_device_options.append(g.grad_op_indices.device_option)
if g.grad_op_values:
all_device_options.append(g.grad_op_values.device_option)
all_gradient_names.append(g.gradient.values)
# Check if all grad op device options are the same.
if len(all_device_options) >= 2 and not all(
device_option_equal(d, all_device_options[0])
for d in all_device_options[1:]):
raise RuntimeError('Unexpected behavior: not all grad ops '
'have the same device option.')
return True
def DoGradientAccumulation(self, fwd_op_idx):
"""For each input name in the forward op, check if we will need to
add gradient accumulation. If so, do gradient accumulation and return
the list of gradient operators.
The criteria for doing gradient accumulation is:
(1) the specific input version has been used by multiple operators.
(2) the current fwd_op_idx is the first to use that input, i.e. in the
backward pass, is the last to optionally generate the gradient for
the op.
(3) For the operators that used the input, their gradient operators
have generated more than 1 gradient.
When accumulating operators, our current solution is to rename all the
created gradients with an internal intermediate name, and then add a
Sum() operator that adds up all the gradients. This may use more memory
due to intermediate storage, but is usually the fastest approach as one
can do one single sum for multiple intermediate gradients.
"""
forward_op, in_versions, out_versions = self.ssa[fwd_op_idx]
additional_sum_ops = []
grad_map = {}
for _i, input_name in enumerate(set(forward_op.input)):
input_version = in_versions[input_name]
input_usage = self.input_usages[input_name][input_version]
if (len(input_usage) <= 1 or fwd_op_idx != input_usage[0]):
# We do not need to do gradient accumulation yet.
continue
generator = self.gradient_generators[input_name][input_version]
try:
if not self._VerifyGradientGenerators(generator):
continue
except RuntimeError as err:
raise RuntimeError(
"Gradients for param ''{}'' failed to verify: {}".format(
input_name,
err
)
)
# Finally, let's create the sum operator.
sum_ops, g = self._MakeSumOps(input_name, input_version)
additional_sum_ops.extend(sum_ops)
grad_map[input_name] = g
return additional_sum_ops, grad_map
def _AppendAutoGradGenerator(self, y, grad, autograd_op):
# Gradient here is not sparse as it was generated by
# a ConstantFill operator. Autogeneration for sparse gradients is
# not supported
generator = GradGenMeta(
autograd_op, 0 if autograd_op else None, str(grad))
self.gradient_generators[str(y)][self.frontier[str(y)]].append(
generator)
def _GetInitGradients(self, ys):
input_to_grad = {}
gradient_ops = []
for y, g in viewitems(ys):
autograd_op = None
if g is None:
autograd_op = CreateOperator(
"ConstantFill", [y], [str(y) + "_autogen_grad"],
value=1.0)
gradient_ops.append(autograd_op)
g = autograd_op.output[0]
# Since the C++ gradient registry does not have notion of
# NameScopes, we will convert all references to strings.
input_to_grad[str(y)] = (
GradientSlice(str(g[0]), str(g[1]))
if isinstance(g, GradientSlice) else str(g))
# Autogenerated gradients are assumed to be provided for the last
# input version
if autograd_op is not None:
self._AppendAutoGradGenerator(y, g, autograd_op)
return input_to_grad, gradient_ops
def _GenerateGradientsForForwardOp(
self, forward_op_idx, input_to_grad):
new_input_to_grad = {}
gradient_ops = []
forward_op, in_versions, out_versions = self.ssa[forward_op_idx]
g_output = list(
input_to_grad.get(name, None) for name in forward_op.output)
if not all(g is None for g in g_output) or (
forward_op.type == "ZeroGradient"):
gradient_ops, g_input = GradientRegistry.GetGradientForOp(
forward_op, g_output)
# Check if the gradient operators are legal, and update
# gradient_generators and gradient_frontier
self.BuildGradientGenerators(
forward_op_idx, gradient_ops, g_output, g_input)
# Record the gradient map to all_input_to_grad.
for name, grad in zip(forward_op.input, g_input):
# Do not overwrite an existing gradient with a None
# unless the input is also an output of the op, since
# we update the blob version when blob is output of an
# operator.
if grad is not None or \
name not in input_to_grad or \
name in list(forward_op.output):
new_input_to_grad[name] = grad
return new_input_to_grad, gradient_ops
def GetBackwardPass(self, ys):
"""Gets the backward pass that computes the derivatives of given blobs.
Inputs:
ys: a list or a dictionary specifying what blobs we want to compute
derivatives of. If the input is a list, we will automatically
generate their gradients with all-one values; if the input is a
dictionary, for any dictionary entries that are not None, we will
take the corresponding blobs as their gradients; for all those
that are None, we will auto-fill them with 1.
"""
if isinstance(ys, list):
ys = dict((y, None) for y in ys)
elif not isinstance(ys, dict):
raise TypeError("ys should either be a list or a dict.")
# Set the gradient frontier with the initialized external
# gradients.
for y in viewkeys(ys):
self.gradient_frontier[y] = self.frontier[y]
self.input_usages[str(y)][self.frontier[str(y)]].append(
len(self.ssa))
all_input_to_grad, all_gradient_ops = self._GetInitGradients(ys)
# (2) Now, after having the virtual play above, we now play the ops
# backwards, creating the gradients along the path. Note that although
# we are playing it backwards, we cannot refer to variables that are
# at a version older than current_versions because it is already been
# overwritten.
for forward_op_idx in reversed(range(len(self.ssa))):
input_to_grad, gradient_ops = self._GenerateGradientsForForwardOp(
forward_op_idx, all_input_to_grad)
all_input_to_grad.update(input_to_grad)
all_gradient_ops += gradient_ops
# If there are multiple use blobs, do gradient accumulation.
additional_sum_ops, grad_map = self.DoGradientAccumulation(
forward_op_idx)
# This line is so that if in an accumulation some of the operators
# have not produced gradients, they still do not overwrite the
# general all_input_to_grad map.
all_input_to_grad.update(grad_map)
all_gradient_ops += additional_sum_ops
# (3) Post-processing.
# After we have done computation for each op, we now have the gradient
# operators ready. For the output map, we will convert everything to
# BlobReferences for easier handling in python.
all_input_to_grad_out = {}
for key, val in viewitems(all_input_to_grad):
if val is not None:
if (isinstance(val, string_types) or
isinstance(val, binary_type)):
grad_out = BlobReference(val)
else:
grad_out = GradientSlice(BlobReference(val[0]),
BlobReference(val[1]))
all_input_to_grad_out[BlobReference(key)] = grad_out
return all_gradient_ops, all_input_to_grad_out
class GradientRegistry(object):
"""GradientRegistry holds the mapping from operators to their gradients."""
gradient_registry_ = {}
@classmethod
def RegisterGradient(cls, op_type):
"""A decorator for registering gradient mappings."""
def Wrapper(func):
cls.gradient_registry_[op_type] = func
return func
return Wrapper
@classmethod
def _GetGradientForOpCC(cls, op_def, g_output):
# TODO(tulloch) - Propagate GradientWrapper up through the stack.
def from_untyped(grad):
if grad is None:
w = C.GradientWrapper()
assert w.is_empty()
return w
try:
(indices, values) = grad
w = C.GradientWrapper()
w.indices = indices
w.values = values
assert w.is_sparse()
return w
except ValueError:
w = C.GradientWrapper()
w.dense = grad
assert w.is_dense()
return w
g_output = [from_untyped(grad) for grad in g_output]
grad_defs_str, g_input = C.get_gradient_defs(
op_def.SerializeToString(), g_output)
def to_untyped(grad_wrapper):
if grad_wrapper.is_empty():
return None
if grad_wrapper.is_sparse():
return GradientSlice(grad_wrapper.indices, grad_wrapper.values)
assert grad_wrapper.is_dense()
return grad_wrapper.dense
g_input = [to_untyped(grad_wrapper) for grad_wrapper in g_input]
grad_defs = []
for grad_def_str in grad_defs_str:
grad_def = caffe2_pb2.OperatorDef()
grad_def.ParseFromString(grad_def_str)
grad_defs.append(grad_def)
return grad_defs, g_input
@classmethod
def GetGradientForOp(cls, op, g_output):
try:
gradient_ops, g_input = cls._GetGradientForOpCC(op, g_output)
except Exception as e:
# Not supported in C++; will try python registration next.
if op.type in cls.gradient_registry_:
gradient_ops, g_input = cls.gradient_registry_[op.type](
op, g_output
)
else:
raise Exception(
"Exception when creating gradient for [{}]:{}.\nOp: \n{}".
format(op.type, e, str(op))
)
if gradient_ops is None:
return [], g_input
if type(gradient_ops) is not list:
gradient_ops = [gradient_ops]
return gradient_ops, g_input
@classmethod
def GetBackwardPass(cls, operators, ys, ys_generate_gradient=False):
"""Gets the backward pass for the list of operators.
Args:
operators: a list of operators constituting the forward pass.
ys: a list or a dictionary specifying what blobs we want to compute
derivatives of. If the input is a list, we will automatically
generate their gradients with all-one values; if the input is a
dictionary, for any dictionary entries that are not None, we'll
take the corresponding blobs as their gradients; for all those
that are None, we will auto-fill them with 1.
Returns:
gradient_ops: a list of gradient operators to run.
all_input_to_grads: a map from input to their corresponding
gradients.
"""
ir = IR(operators)
return ir.GetBackwardPass(ys)
GradientRegistry.RegisterGradient('Do')(gen_do_gradient)
GradientRegistry.RegisterGradient('If')(gen_if_gradient)
GradientRegistry.RegisterGradient('While')(gen_while_gradient)
def get_ssa(net, blob_versions=None):
"""
Given a net, return a structure containing the version of each input and
output blob used by each operator.
Args:
net: either a Net or a NetDef
blob_versions: (optional) map with current version number for given
blob names. If not provided or blob not found, start
from version 0.
Returns:
Tuple (ssa, blob_versions)
ssa: list of tuples (versioned_inputs, versioned_outputs)
for each op in the net. A versioned input is a tuple
(blob_name, version).
blob_versions: updated map with latest version of each blob found in
the net.
"""
proto = net.Proto() if isinstance(net, Net) else net
assert isinstance(proto, caffe2_pb2.NetDef)
if blob_versions is None:
blob_versions = {}
if isinstance(net, list):
return [get_ssa(n, blob_versions) for n in net], blob_versions
for i in proto.external_input:
if i not in blob_versions:
blob_versions[str(i)] = 0
ssa = []
for op in proto.op:
if not proto.external_input:
for i in op.input:
if i not in blob_versions:
blob_versions[i] = 0
inputs = [(str(i), blob_versions.get(str(i), 0)) for i in op.input]
for o in op.output:
blob_versions[str(o)] = blob_versions.get(str(o), 0) + 1
outputs = [(str(o), blob_versions[str(o)]) for o in op.output]
ssa.append((inputs, outputs))
return ssa, blob_versions
def get_undefined_blobs(ssa):
"""
Given a ssa in the format produced by get_ssa(), return a set of blobs that
are used before they are defined, which corresponds to inputs at version 0.
"""
undef_blobs = set()
for inputs, _outputs in ssa:
undef_blobs |= set(name for (name, ver) in inputs if ver == 0)
return undef_blobs
def get_output_producers(ssa):
"""
Given a ssa in the format produced by get_ssa(), returns a map from
versioned blob into the operator index that produces that version of
the blob. A versioned blob is a tuple (blob_name, version).
"""
producers = {}
for i, (_inputs, outputs) in enumerate(ssa):
for o in outputs:
producers[o] = i
return producers
def get_op_ids_in_path(ssa, blob_versions, inputs, outputs):
"""
Given a ssa and blob_versions as produced by get_ssa(), returns the list
of op indices that are necessary in order to generate the blobs in
`outputs`, given blobs in `inputs`.
Consider that the `inputs` are given in their latest version.
"""
inputs_set = set((str(i), blob_versions[str(i)]) for i in inputs)
producers = get_output_producers(ssa)
queue = [(str(o), blob_versions[str(o)]) for o in outputs]
used_op_ids = set()
while len(queue) > 0:
o = queue.pop()
if (o not in inputs_set) and (o in producers):
op_id = producers[o]
if op_id not in used_op_ids:
used_op_ids |= {op_id}
inputs, _ = ssa[op_id]
queue.extend(inputs)
return sorted(used_op_ids)
def recurrent_network_op_remap(op, prefix, blob_remap):
"""
Parameters
----------
op : Caffe2 operator (RecurrentNetworkOp or RecurrentNetworkGradientOp).
prefix: this argument is not used in this function, just for legacy support.
blob_remap : Dictionary that represents the map from old blob name to new.
Updates blob names in arguments of RecurrentNetworkOp and
RecurrentNetworkGradientOp to conform to cloned input and output of both
operators and also makes sure names of locally generated blobs in arguments
have the same prefix as the input and output of the operators.
"""
def get_remapped_str(blob_str):
if isinstance(blob_str, binary_type):
blob_str = blob_str.decode('utf-8')
return blob_remap.get(blob_str, blob_str).encode('utf-8')
for argument in op.arg:
if len(argument.strings) > 0:
for i in range(len(argument.strings)):
argument.strings[i] = get_remapped_str(argument.strings[i])
elif argument.name == 'timestep':
argument.s = get_remapped_str(argument.s)
elif argument.name.endswith('step_net'):
# argument is a proto
remap_proto(argument, blob_remap)
def control_op_remap(op, prefix, blob_remap):
net_arg_names = []
if op.type == "If":
net_arg_names = ['then_net', 'else_net']
else:
net_arg_names = ['loop_net', 'cond_net']
for argument in op.arg:
if argument.name in net_arg_names:
assert argument.n, \
"Expected non empty net in " + op.type + "'s " + argument.name + " argument"
subnet = Net(argument.n)
remapped_subnet = subnet.Clone(
name=(subnet._net.name if subnet._net.name else '') + '_remapped',
blob_remap=blob_remap)
argument.n.CopyFrom(remapped_subnet.Proto())
DEFAULT_REMAP_FUNCS = {
'RecurrentNetwork': recurrent_network_op_remap,
'RecurrentNetworkGradient': recurrent_network_op_remap,
'If': control_op_remap,
'While': control_op_remap,
}
def remap_proto(argument, blob_remap):
subnet = Net(argument.n)
cloned_sub_net = subnet.Clone(
'cloned_sub_net',
blob_remap,
)
argument.n.CopyFrom(cloned_sub_net.Proto())
def clone_and_bind_net(net, name, prefix, blob_remap=None, inputs=None,
keep_schema=True):
"""
Clone the given Net, binding its input schema to the given `inputs` record.
Blob names defined by the net are prepended with the given `prefix`.
Args:
net: the net to clone
name: the name of the new net
prefix: the prefix to append to local blobs
blob_remap: (optional) dict with additional blob name remapping.
inputs: (optional) input record that will provide actual input
values for the cloned net. Must be compatible with the
net's input schema or be a strict superset of it
keep_schema: by default (True), the original schema will be kept and
remapped accordingly. otherwise, the schema will be set as
inputs or left empty if inputs is not given.
Returns:
Tuple (cloned_net, blob_remap)
clone_net: the cloned Net
blob_remap: a map from original blob names into remapped blob names
"""
from caffe2.python import schema
assert isinstance(net, Net)
if blob_remap is None:
blob_remap = {}
if inputs is not None:
assert isinstance(inputs, schema.Field)
original = net.input_record()
assert original is not None
# TODO(azzolini): improve schema type checking
diff = set(original.field_names()) - set(inputs.field_names())
assert len(diff) == 0, (
"Schemas don't match, extra fields {diff} found in the net {name}. "
"original: {original}; inputs: {inputs}"
.format(
diff=diff, name=net.Name(), original=original.field_names(),
inputs=inputs.field_names()
)
)
original_mapping = dict(zip(original.field_names(),
original.field_blobs()))
for fn, fb in zip(inputs.field_names(), inputs.field_blobs()):
if fn in original_mapping:
blob_remap[str(original_mapping[fn])] = str(fb)
proto = net.Proto()
ssa, blob_versions = get_ssa(proto)
undef_blobs = get_undefined_blobs(ssa)
for blob in viewkeys(blob_versions):
if blob in blob_remap:
continue
elif blob in undef_blobs:
blob_remap[blob] = blob
else:
blob_remap[blob] = prefix + blob
cloned_net = net.Clone(name, blob_remap, keep_schema=keep_schema)
if not keep_schema and inputs:
cloned_net.set_input_record(inputs)
return cloned_net, blob_remap
def _get_blob_ref(blob_name_or_ref):
return (
blob_name_or_ref if isinstance(input, BlobReference)
else BlobReference(blob_name_or_ref)
)
def _recover_record_by_prefix(names, prefix=''):
"""
Tries to recover record by taking a subset of blob names with
a given prefix name and interpreting them as schema column names
"""
from caffe2.python import schema
column_names = [name[len(prefix):] for name in names
if name.startswith(prefix)]
if not column_names:
return None
return schema.from_column_list(
column_names,
col_blobs=[_get_blob_ref(prefix + name) for name in column_names])
class Net(object):
_net_names_used = set()
operator_registry_ = {}
@staticmethod
def current_prefix():
from caffe2.python.net_builder import NetBuilder
builder = NetBuilder.current(required=False)
return builder.name if builder else ''
@staticmethod
def _get_next_net_name(basename):
name = basename = '/'.join(
x for x in [Net.current_prefix(), basename] if x
)
next_idx = 1
while name in Net._net_names_used:
name = basename + '_' + str(next_idx)
next_idx += 1
Net._net_names_used |= set([name])
return name
def __init__(self, name_or_proto):
"""
Create a Net.
Args:
name_or_proto: If a NetDef is provided, clone it. Otherwise,
create an empty net with the given name.
"""
self._input_record = None
self._output_record = None
# Register blobs so that it's guaranteed that different calls to
# NextBlob/NextScopedBlob always return blobs with different names
self._registered_blob_names = set()
self._recreate_lookup_tables = False
self._op_outputs = set()
self._external_input_map = set()
self._attr_dict = defaultdict(list)
if type(name_or_proto) is caffe2_pb2.NetDef:
proto = name_or_proto
# We rae initializing a network by a NetDef. In this case, we will
# initialize our network with the given netdef.
self._net = caffe2_pb2.NetDef()
self._net.CopyFrom(proto)
existing_outputs = [list(op.output) for op in self._net.op]
self._external_input_map.update(list(self._net.external_input))
# Set the next name index properly.
existing_names = set(
sum(
[list(op.input) for op in self._net.op], []
) + sum(
existing_outputs, []
)
)
for outs in existing_outputs:
self._op_outputs.update(outs)
prefix_len = len(self._net.name + '_blob_')
autogen_indices = []
for s in existing_names:
if s.startswith(self._net.name + '_blob_'):
try:
autogen_indices.append(int(s[prefix_len]))
except ValueError:
pass
if len(autogen_indices):
self._next_name_index = max(autogen_indices) + 1
else:
self._next_name_index = 0
name = self._net.name
else:
name = name_or_proto
self._net = caffe2_pb2.NetDef()
self._next_name_index = 0
# make sure that this net name hasn't been used before
self._net.name = Net._get_next_net_name(name)
def AppendNet(self, net):
assert isinstance(net, Net)
for i in net.Proto().external_input:
if (
i not in self.Proto().external_input and
i not in self._op_outputs
):
self.Proto().external_input.append(i)
self.Proto().external_output.extend(
[
o for o in net.Proto().external_output
if o not in self.Proto().external_output
]
)
self._ExtendOps(net.Proto().op)
return self
def LogInfo(self, *msg_or_blobs):
for msg_or_blob in msg_or_blobs:
if not isinstance(msg_or_blob, BlobReference):
blob = self.GivenTensorStringFill(
[], self.NextName('log'),
shape=[], values=[msg_or_blob])
else:
blob = msg_or_blob
self.Print(blob, [])
def add_attribute(self, name, obj):
"""
Add `obj` to the list of attributes in this net under the given `name`.
Attributes are user-defined objects and have no pre-defined semantics.
"""
self._attr_dict[name].append(obj)
def get_attributes(self, name):
"""
Returns the list of attributes in this net for a given `name`.
Attributes are user-defined objects added with `add_attribute'.
"""
return self._attr_dict.get(name, [])
def set_rand_seed(self, seed=100, sequence_seed=True, seed_on_op_def=False):
"""
Adds a random seed to each op in the net.
If sequence_seed is set, the i-th op has rand_seed=`seed + i`
If seed_on_op_def is set, the op rand_seed=hash(str(op))
sequence_seed and seed_on_op_def cannot be both set to True.
"""
assert not (sequence_seed and seed_on_op_def), (
'sequence_seed and seed_on_op_def cannot be both set to True.')
for i, op in enumerate(self.Proto().op):
if sequence_seed:
curr_seed = seed + i
elif seed_on_op_def:
curr_seed = hash(str(op) + str(seed)) % np.iinfo(np.uint32).max
else:
curr_seed = seed
op.device_option.random_seed = curr_seed
def Name(self):
return self._net.name
def __str__(self):
return self.Name()
def Const(self, array, blob_out=None, dtype=None):
if isinstance(array, bool):
return self.ConstantFill(
[],
blob_out or 1,
dtype=DataType.BOOL,
value=array)
if dtype is None:
array = np.array(array)
else:
array = np.array(array, dtype=dtype)
def do_set(operator):
return operator(
[],
blob_out or 1,
shape=array.shape,
values=array.flatten().tolist())
if array.dtype == np.int32:
return do_set(self.GivenTensorIntFill)
elif array.dtype == np.int64:
return do_set(self.GivenTensorInt64Fill)
elif array.dtype == np.str:
return do_set(self.GivenTensorStringFill)
elif array.dtype == np.bool:
return do_set(self.GivenTensorBoolFill)
else:
return do_set(self.GivenTensorFill)
def BlobIsDefined(self, blob):
"""
Returns true if the given BlobReference is produced as output of
an operator in this net, or if it is provided as an external input.
"""
if self._recreate_lookup_tables:
self._RecreateLookupTables()
name = str(blob)
return (name in self._op_outputs) or (name in self._external_input_map)
def UsesBlob(self, blob):
"""
Returns true iff the given BlobReference is used by any operator
or this net, or if it is one of the external inputs of the net.
"""
blob_name = str(blob)
for op in self._net.op:
for input in op.input:
if input == blob_name:
return True
return blob_name in self._external_input_map
def UsedBlobNames(self):
"""
Returns a set of blob names used in the net
"""
blob_names = set()
for op in self._net.op:
blob_names |= set(op.input)
blob_names |= set(op.output)
if self._net.external_input:
blob_names |= set(self._net.external_input)
if self._net.external_output:
blob_names |= set(self._net.external_output)
return blob_names
def GetBlobRef(self, blob_name):
"""
Given the name of a blob produced by this net, return a BlobReference
to it. If the blob is not produced by any op in this net,
raises KeyError.
"""
blob_name = str(blob_name)
if not self.BlobIsDefined(blob_name):
raise KeyError('Net does not define blob %s' % blob_name)
return BlobReference(blob_name, self)
def Clone(
self,
name,
blob_remap=None,
op_id_mask=None,
remap_funcs=None,
keep_schema=True
):
"""
Clone this net.
Args:
name: name of the cloned net
blob_remap: optional map with list of blob names to replace
op_id_mask: optional list of operator indices to include in
the cloned net. If not provided, all ops are included.
"""
orig_remap_funcs = {} if remap_funcs is None else remap_funcs
# by default we want to put RecurrentNetworkOp and
# RecurrentNetworkGradientOp into remap_funcs, as these two operators
# also take blobs and proto into the arguments.
remap_funcs = DEFAULT_REMAP_FUNCS.copy()
remap_funcs.update(orig_remap_funcs)
proto = self._net
new_proto = caffe2_pb2.NetDef()
new_proto.CopyFrom(proto)
new_proto.name = name
if blob_remap is None:
blob_remap = {}
if op_id_mask is None:
op_id_mask = list(range(0, len(proto.op)))
def get_remapped_str(blob):
blob_str = str(blob)
return str(blob_remap.get(blob_str, blob_str))
def remap_list(proto_list):
new_list = [get_remapped_str(b) for b in proto_list]
del proto_list[:]
proto_list.extend(new_list)
def remap_op(op):
new_op = caffe2_pb2.OperatorDef()
new_op.CopyFrom(op)
remap_list(new_op.input)
remap_list(new_op.output)
if new_op.type in remap_funcs:
remap_funcs[new_op.type](
new_op,
(name + '/') if name else '',
blob_remap,
)
return new_op
del new_proto.op[:]
new_proto.op.extend([remap_op(proto.op[op_id]) for op_id in op_id_mask])
remap_list(new_proto.external_input)
remap_list(new_proto.external_output)
new_net = Net(new_proto)
if keep_schema:
from caffe2.python import schema
if self._input_record:
new_net._input_record = schema.from_blob_list(
self._input_record,
[
BlobReference(get_remapped_str(blob), net=new_net)
for blob in self._input_record.field_blobs()
],
)
if self._output_record:
new_net._output_record = schema.from_blob_list(
self._output_record,
[
BlobReference(get_remapped_str(blob), net=new_net)
for blob in self._output_record.field_blobs()
],
)
new_net._attr_dict.update(self._attr_dict)
return new_net
def ClonePartial(self, name, inputs, outputs, remap_funcs=None):
"""
Clone this net, including only ops that are necessary in order to
compute `outputs` given `inputs`. Return references to the cloned
outputs. Internal blobs (blobs that are produced and consumed inside
the net but not used as outputs) will be remapped to avoid name
conflict.
Args:
name: the name of the cloned net
inputs: map where the keys correspond to BlobReferences in the
original net, and the values correspond to external inputs
in the partially cloned net. If `inputs` is a list, don't
remap input names.
outputs: outputs to be produced by the cloned net.
Returns:
Tuple (new_net, new_outputs)
new_net: a new Net object.
new_outputs: list of BlobReferences corresponding to the
outputs produced by new_net.
"""
input_is_pair_list = isinstance(inputs, list) and all(
isinstance(i, tuple) and len(i) == 2 for i in inputs)
inputs = (
inputs if isinstance(inputs, (dict, OrderedDict)) else
OrderedDict(inputs) if input_is_pair_list else
OrderedDict(zip(inputs, inputs)))
for output in outputs:
assert self.BlobIsDefined(output)
input_names = {str(k): str(v) for k, v in viewitems(inputs)}
output_names = [str(o) for o in outputs]
proto = self._net
blob_versions = {str(i): 0 for i in inputs}
ssa, blob_versions = get_ssa(proto, blob_versions)
used_op_ids = get_op_ids_in_path(ssa, blob_versions, inputs, outputs)
disallowed_op_ids = get_op_ids_in_path(ssa, blob_versions, [], inputs)
assert len(set(used_op_ids) & set(disallowed_op_ids)) == 0, (
'Cannot partially clone net: some of the ops required would ' +
'generate the given input.')
sub_ssa = [op for i, op in enumerate(ssa) if i in used_op_ids]
undef_blobs = get_undefined_blobs(sub_ssa) - set(viewkeys(input_names))
prefix = (name + '/') if name else ''
def remap(blob_name):
if blob_name in input_names:
return input_names[blob_name]
elif blob_name in undef_blobs:
return blob_name
else:
return prefix + blob_name
blob_mapping = {b: remap(b) for b in viewkeys(blob_versions)}
new_net = self.Clone(name, blob_mapping, used_op_ids, remap_funcs)
new_in = [
blob_mapping[i] for i in viewkeys(input_names)] + list(undef_blobs)
new_out = [blob_mapping[o] for o in output_names]
del new_net.Proto().external_input[:]
new_net.Proto().external_input.extend(new_in)
new_net._external_input_map = set(list(new_in))
del new_net.Proto().external_output[:]
new_net.Proto().external_output.extend(new_out)
return new_net, [new_net.GetBlobRef(o) for o in new_out]
def Proto(self):
self._InvalidateLookupTables()
return self._net
def PopulateProtoWithFileName(self):
net_tb = workspace.operator_tracebacks.get(self.Name(), None)
if net_tb is not None:
for idx, op in enumerate(self.Proto().op):
if idx in net_tb:
op.name = ':'.join(map(str, net_tb[idx][0]))
def NextScopedBlob(self, prefix='unnamed'):
"""Return the blob that has not been defined or registered in the
current net. It returns `ScopedBlobReference(prefix)`, if it's valid,
otherwise `ScopedBlobReference(prefix) + '_auto_' + ?`. Different calls
is guaranteed to return blob with different names.
"""
output_blob_base = ScopedName(prefix)
return self.NextBlob(output_blob_base)
def NextBlob(self, prefix='unnamed'):
"""Return the blob that has not been defined or registered in the
current net. It returns `BlobReference(prefix)`, if it's valid,
otherwise `BlobReference(prefix) + '_auto_' + ?`. Different calls
is guaranteed to return blob with different names."""
output_blob_base = BlobReference(prefix)
output_blob = output_blob_base
index = 0
while str(output_blob) in self._registered_blob_names or (
self.BlobIsDefined(output_blob)):
output_blob = output_blob_base + '_auto_' + str(index)
index += 1
self._registered_blob_names.add(str(output_blob))
return output_blob
def NextName(self, prefix=None, output_id=None):
"""Returns the next name to be used, if you do not want to explicitly
name your blob. [Deprecated, use NextBlob, NextScopedBlob instead]"""
if prefix:
output_name_base = self._net.name + '/' + prefix
output_name = output_name_base
if output_id is not None:
output_name += ':' + str(output_id)
index = 2
while self.BlobIsDefined(str(ScopedBlobReference(output_name))):
output_name = output_name_base + '_' + str(index)
if output_id is not None:
output_name += ':' + str(output_id)
index += 1
else:
output_name = self._net.name + '_blob_' + str(self._next_name_index)
self._next_name_index += 1
return str(output_name)
def _ExtendOps(self, new_ops):
self._net.op.extend(new_ops)
for op in new_ops:
self._op_outputs.update([text_type(o) for o in op.output])
def _CheckLookupTables(self):
'''
Called from unit tests to validate the internal lookup tables
match the protobuf contents.
'''
test_op_outputs = set()
for op in self._net.op:
for o in op.output:
test_op_outputs.add(o)
test_external_inp = set()
for inp in self._net.external_input:
test_external_inp.add(inp)
assert test_op_outputs.difference(self._op_outputs) == set()
assert test_external_inp.difference(self._external_input_map) == set()
def _InvalidateLookupTables(self):
self._recreate_lookup_tables = True
def _RecreateLookupTables(self):
self._op_outputs = set()
for op in self._net.op:
for o in op.output:
self._op_outputs.add(o)
self._external_input_map = set()
for inp in self._net.external_input:
self._external_input_map.add(inp)
self._recreate_lookup_tables = False
def AddGradientOperators(self, ys, skip=0):
"""Add the gradient for operators in the net.
Inputs:
ys: a list or a dictionary specifying what blobs we want to compute
derivatives of. If the input is a list, we will automatically
generate their gradients with all-one values; if the input is a
dictionary, for any dictionary entries that are not None, we will
take the corresponding blobs as their gradients; for all those
that are None, we will auto-fill them with 1.
skip: skips the first n operators. This is provided mainly because a
lot of nets may use the first few operators for data generation
like stuff which really do not need to have gradients.
Outputs:
returns a map from the blob name in the input network to a blob
containing gradient or a GradientSlice in case of sparse gradient
Currently, this is hard-coded for float operators if there are branches
(i.e. a blob is used as input to multiple operators). This is because
the gradient accumulation (Sum) is float only right now.
"""
grad_ops, input_to_grad = GradientRegistry.GetBackwardPass(
self._net.op[skip:], ys)
# Check if in immediate mode: the grad_ops are actually being produced
# by C++ and bypasses the CreateOperator() call, so in immediate mode
# we will have to explicitly run them.
if workspace.IsImmediate():
for op in grad_ops:
workspace.RunOperatorImmediate(op)
self._ExtendOps(grad_ops)
return input_to_grad
def AddExternalInput(self, *inputs):
assert len(inputs) > 0
refs = []
for input in inputs:
input_name = str(input)
assert str(input) not in self._external_input_map, (
'Net already contains an input named %s' % input_name)
for input in inputs:
input_name = str(input)
self._net.external_input.extend([input_name])
self._external_input_map.update([input_name])
refs.append(_get_blob_ref(input_name))
return refs[0] if len(refs) == 1 else refs
def AddExternalOutput(self, *outputs):
for output in outputs:
assert isinstance(output, BlobReference)
assert self.BlobIsDefined(output)
for output in outputs:
self.Proto().external_output.extend([str(output)])
def AddScopedExternalInputs(self, *inputs):
res = self.AddExternalInput(
* [ScopedBlobReference(b) for b in inputs]
)
if not isinstance(res, list):
res = [res]
return res
def AddScopedExternalOutputs(self, *outputs):
return self.AddExternalOutput(
* [ScopedBlobReference(b) for b in outputs]
)
# This returns a reference to the observer
def AddObserver(self, observer_type):
return C.add_observer_to_net(self._net.name, observer_type)
def RemoveObserver(self, observer):
C.remove_observer_from_net(self._net.name, observer)
def NumObservers(self):
return C.num_observers_on_net(self._net.name)
@property
def external_inputs(self):
return [_get_blob_ref(x) for x in self._net.external_input]
@property
def external_outputs(self):
return [_get_blob_ref(x) for x in self._net.external_output]
def set_input_record(self, input_record):
from caffe2.python import schema
assert self._input_record is None or (input_record.has_blobs() and
set(input_record.field_blobs()) ==
set(self._input_record.field_blobs())), (
'Input schema cannot be reset')
if not input_record.has_blobs():
with NameScope(self.Name()):
self._input_record = schema.NewRecord(self, input_record)
else:
self._input_record = input_record
for blob in input_record.field_blobs():
if blob not in self.external_inputs:
self.AddExternalInput(blob)
return self._input_record
def recover_input_record_by_prefix(self, prefix):
"""
Tries to recover input record by taking a subset of external_inputs with
a given prefix name and interpreting them as schema column names
"""
record = _recover_record_by_prefix(self._net.external_input, prefix)
if record:
self.set_input_record(record)
def set_output_record(self, record):
assert self._output_record is None or (record.has_blobs() and
set(record.field_blobs()) ==
set(self._output_record.field_blobs())), (
'Output schema cannot be reset')
for blob in record.field_blobs():
assert self.BlobIsDefined(blob), "{} is not defined".format(blob)
for blob in record.field_blobs():
self.AddExternalOutput(blob)
self._output_record = record
def recover_output_record_by_prefix(self, prefix):
"""
Tries to recover out record by taking a subset of external_outputs with
a given prefix name and interpreting them as schema column names
"""
record = _recover_record_by_prefix(self._net.external_output, prefix)
if record:
self.set_output_record(record)
def AppendOutputRecordField(self, field_name, record):
from caffe2.python import schema
assert self._output_record is not None, (
'Tried to append to missing output record'
)
for blob in record.field_blobs():
assert self.BlobIsDefined(blob)
for blob in record.field_blobs():
self.AddExternalOutput(blob)
self._output_record = self._output_record + schema.Struct(
(field_name, record)
)
def input_record(self):
return self._input_record
def output_record(self):
return self._output_record
def AddExternalInputs(self, *inputs):
return self.AddExternalInput(*inputs)
def AddExternalOutputs(self, *outputs):
self.AddExternalOutput(*outputs)
def DeduplicateGradientSlices(self, g, aggregator='sum'):
assert isinstance(g, GradientSlice)
unique, remapping = self.Unique([g.indices], 2, engine='SparseHash')
if aggregator.lower() == 'sum':
new_g = self.UnsortedSegmentSum([g.values, remapping], 1)
elif aggregator.lower() == 'mean':
new_g = self.UnsortedSegmentMean([g.values, remapping], 1)
else:
raise ValueError('{} is not supported'.format(aggregator))
return GradientSlice(indices=unique, values=new_g)
def RunAllOnGPU(self, gpu_id=0, use_cudnn=False):
"""A convenient function to run everything on the GPU."""
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = gpu_id
self._net.device_option.CopyFrom(device_option)
if use_cudnn:
for op in self._net.op:
op.engine = "CUDNN"
def RunAllOnMKL(self):
"""A convenient function to run everything using MKLDNN."""
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.MKLDNN
self._net.device_option.CopyFrom(device_option)
def _CreateAndAddToSelf(self, op_type, inputs, outputs=None, **kwargs):
"""A helper function to create an operator and add it to self.
"""
inputs = _RectifyInputOutput(inputs)
for input in inputs:
if not self.BlobIsDefined(input):
assert input.Net() != self
self.AddExternalInput(input)
if outputs is None:
# If we do not specify an output, we will assume that this op
# produces one output in this case.
outputs = self.NextName(prefix=op_type)
elif type(outputs) is int:
# In this case, we will auto-fill the given number of outputs
# with auto-generated names.
outputs = [
self.NextName(prefix=op_type, output_id=i)
for i in range(outputs)]
outputs = _RectifyInputOutput(outputs, net=self)
op = CreateOperator(op_type, inputs, outputs, **kwargs)
self._ExtendOps([op])
workspace.operator_tracebacks[self.Name()][
len(self._net.op) - 1] = _extract_stacktrace()
if len(op.output) == 0:
return
elif len(op.output) == 1:
return BlobReference(op.output[0], self)
else:
return tuple(BlobReference(o, self) for o in op.output)
def __getattr__(self, op_type):
if op_type.startswith('__'):
raise AttributeError('Attribute {} not found.'.format(op_type))
if not IsOperator(op_type) and not IsOperatorWithEngine(op_type, "CUDNN"):
raise AttributeError(
'Method ' + op_type + ' is not a registered operator.' +
' Did you mean: [' +
",".join(workspace.C.nearby_opnames(op_type)) + ']'
)
return lambda *args, **kwargs: self._CreateAndAddToSelf(
op_type, *args, **kwargs)
def __dir__(self):
additional_methods = [
op
for op in _REGISTERED_OPERATORS
if '_ENGINE_' not in op]
return sorted(set(chain(
dir(type(self)),
viewkeys(self.__dict__),
additional_methods
)))
def Python(
self,
f,
grad_f=None,
python_func_type=None,
pass_workspace=False,
grad_output_indices=None,
grad_input_indices=None
):
"""
Registers and returns a python operator.
`f` and `grad_f` can be one of the following:
- a function with signature (inputs, outputs), where inputs and
outputs are a list of CPUTensor objects. This function will be
called from C++ everytime the operator is executed.
- a tuple (func, args, kwargs), here `func` is a callable, args is
an argument list, and kwargs is a dict list. The call:
f = func(*args, kwargs)
will be performed locally at node initialization time, on all of
the nodes of the job, returning `f`, a callable that will be used
as the python operator function to be called during Net execution.
This is to be used when using python operator in a distributed
context, and allows to create and keep local python state across
calls to the operator.
`python_func_type` is a type of an object that constructed as
python_func_type(f) and provides an implementation to forward and
backward functions. Its useful in such a case where users needs
a statefull PythonOp (ex: use autograd for computing grad_f).
If `pass_workspace` is True, the signature is changed to
(inputs, outputs, workspace) where `workspace` is the workspace the op
is going to run on. This is potentially dangerous (as the op can
manipulate the workspace directly), use on your own risk.
If a gradient function is specified (`grad_f`), by default its inputs
will be: (1) all inputs to `f`, (2) followed by all outputs of `f`, (3)
and then all gradient outputs of `f`. The outputs of `grad_f` will be
(by default) all gradient inputs to `f`. If a subset of the gradient
outputs or gradient inputs is desired instead, then the subsets can be
specified by providing `grad_output_indices` and/or `grad_input_indices`
which identify the indices of `f`'s inputs and outputs which have
gradients.
"""
assert(IsOperator('Python'))
def make_builder(t):
if not isinstance(t, tuple):
return ''
assert len(t) == 3, 'Expected builder tuple (func, args, kwargs)'
func, args, kwargs = t
normalized = (func, tuple(args), dict(kwargs))
return pickle.dumps(normalized)
f_builder = make_builder(f)
grad_f_builder = make_builder(grad_f)
assert (not grad_f) or ((not f_builder) == (not grad_f_builder)), (
'A tuple has to be passed to both f and grad_f or neither.')
core_kwargs = {}
if f_builder:
core_kwargs['pickled_builder'] = f_builder
core_kwargs['pickled_grad_builder'] = grad_f_builder
core_kwargs['pass_workspace'] = pass_workspace
else:
core_kwargs['token'] = _RegisterPythonImpl(
f, grad_f, python_func_type, pass_workspace=pass_workspace)
grad_output_indices = grad_output_indices or []
grad_input_indices = grad_input_indices or []
return lambda *args, **kwargs: self._CreateAndAddToSelf(
'Python',
grad_output_indices=grad_output_indices,
grad_input_indices=grad_input_indices,
*args,
**dict(chain(viewitems(kwargs), viewitems(core_kwargs)))
)
def is_external_input(self, blob):
name = str(blob)
return name in self._external_input_map
def extend_ops(self, new_ops):
return self._ExtendOps(new_ops)
def copy_func_between_devices(src, dst):
CPU = caffe2_pb2.CPU
CUDA = caffe2_pb2.CUDA
if src.device_type == CPU and dst.device_type == CPU:
return None
if src.device_type == CUDA and dst.device_type == CUDA:
if src.cuda_gpu_id == dst.cuda_gpu_id:
return None
else:
def fun(net, *args, **kw):
with DeviceScope(dst):
return net.Copy(*args, **kw)
return fun
if src.device_type == CUDA and dst.device_type == CPU:
def fun(net, *args, **kw):
with DeviceScope(src):
return net.CopyGPUToCPU(*args, **kw)
return fun
if src.device_type == CPU and dst.device_type == CUDA:
def fun(net, *args, **kw):
with DeviceScope(dst):
return net.CopyCPUToGPU(*args, **kw)
return fun
raise ValueError('Non-supported devices: %s and %s' % (src, dst))
def device_equal(src, dst):
'''
We are using this fucntion instead of == operator because optional-value
comparison between empty device_options and {device_type:0, cuda_gpu_id:0}
returns not equal in some cases.
'''
return src.device_type == dst.device_type and src.cuda_gpu_id == dst.cuda_gpu_id
def update_placeholder_op_output(op, blob_to_device):
'''
Placeholder ops (for e.g. Recv) always runs on CPU. So ensure their
output blobs reside on CPU.
'''
outputs = []
for output in op.output:
blob_dev = blob_to_device[output]
if blob_dev.device_type != caffe2_pb2.CPU:
output += '_cpu'
outputs.append(output)
del op.output[:]
op.output.extend(outputs)
class RemapEntry:
def __init__(self, blob, device):
self.blob = blob
self.device = device
def __eq__(self, other):
return self.blob == other.blob and self.device == other.device
def __hash__(self):
return hash(self.blob + str(self.device))
def InjectCrossDeviceCopies(net, blob_to_device=None, blob_remap=None,
placeHolderOps=None):
'''
Injecting Copy functions between device within a net. Users can provide
a net with part of operators using different device_options. This method
will automatically create a new net with Copy ops inserted in it.
Inputs:
blob_to_device: If not None, it is a map of blobs and their device locations.
blob_remap: If not None, it is a map from a pair (blob, device) to
the name of the blob in the given device. Blobs found in this
map are assumed to be cached and don't need to be copied.
Outputs:
new_net: A new net with CopyCPUToGPU inserted with correct device option
required_external_to_device:
A mapping between unresolved external inputs and their
required device options.
Assumptions:
1. every external inputs of this net is already in blob_to_device!
2. if not, this function will use net device option
'''
new_net = net.Clone(net._net.name + '_cross_device', keep_schema=True)
del new_net._net.op[:]
if blob_to_device is None:
blob_to_device = {}
# remapping of input blobs for each op.
if blob_remap is None:
blob_remap = {}
temp_remap = {}
net_option = net._net.device_option or caffe2_pb2.DeviceOption()
# if external_inputs have device remappings generated by previous nets,
# then add those remappings as external inputs as well.
all_remaps = defaultdict(list)
for entry, mapped_blob in blob_remap.items():
all_remaps[entry.blob].append(mapped_blob)
mapped_external_inputs = []
for input in new_net._net.external_input:
mapped_external_inputs.extend(all_remaps.get(input) or [])
new_net._net.external_input.extend(mapped_external_inputs)
for op in net._net.op:
temp_remap.clear()
# Get where inputs and outputs should be. If it is a Placeholder
# (i.e. fake) op, then set op's device as blob's devices.
input_dev = None
output_dev = None
if placeHolderOps is not None and op.type in placeHolderOps:
input_dev, output_dev = InferOpDeviceAsBlobDevices(op)
else:
input_dev, output_dev = InferOpBlobDevices(op)
for dev, input in zip(input_dev, op.input):
assert net.BlobIsDefined(input), \
"input {} should be defined in the net.".format(input)
if input not in blob_to_device:
if net.is_external_input(input):
blob_to_device[input] = net_option
else:
raise AttributeError(
"No device information found for blob {}.".
format(input)
)
if not device_equal(blob_to_device[input], dev):
# reuse already moved input
if (RemapEntry(input, dev) in blob_remap and
blob_to_device[blob_remap[RemapEntry(input, dev)]] == dev):
temp_remap[input] = blob_remap[RemapEntry(input, dev)]
else:
# need to make input on correct device.
copy_func = copy_func_between_devices(
blob_to_device[input], dev
)
def _gen_new_name(blob, device_option):
CPU = caffe2_pb2.CPU
CUDA = caffe2_pb2.CUDA
if device_option.device_type == CPU:
suffix = '_cpu'
elif device_option.device_type == CUDA:
suffix = '_cuda_' + str(device_option.cuda_gpu_id)
else:
raise RuntimeError(
"Unknown device type: {}".
format(device_option.device_type)
)
return blob + suffix
new_name = _gen_new_name(input, dev)
copy_func(new_net, input, new_name)
blob_remap[RemapEntry(input, dev)] = new_name
temp_remap[input] = new_name
blob_to_device[new_name] = dev
if placeHolderOps is not None and op.type in placeHolderOps:
update_placeholder_op_output(op, blob_to_device)
# Enforcing no reuse blob between operators. In-place blob usage in an
# op is allowed. This is based on the assumption that in-place op has
# same device info
for dev, output in zip(output_dev, op.output):
if output in blob_to_device and (
output not in op.input and
not device_equal(blob_to_device[output], dev)
):
raise RuntimeError(
"In-place blob: {} is not supported between operators "
"with different device option previous:{} now: {}. "
"Failed op:\n {}".format(
output, blob_to_device[output], dev, op
)
)
new_op = caffe2_pb2.OperatorDef()
new_op.CopyFrom(op)
new_list = [temp_remap.get(b, b) for b in new_op.input]
del new_op.input[:]
new_op.input.extend(new_list)
# keep inplace blobs inplace
original_inputs = list(op.input)
for i, out in enumerate(new_op.output):
try:
input_idx = original_inputs.index(out)
new_op.output[i] = new_op.input[input_idx]
except ValueError:
pass
blob_to_device.update(
{o: d for d, o in zip(output_dev, new_op.output)})
new_net.extend_ops([new_op])
return new_net, blob_to_device
def InjectDeviceCopiesAmongNets(nets, blob_to_device_init=None):
"""
Takes in a list of nets. They usually represent your whole execution graph.
This function will insert cross device copy functions to all nets, and resolve
inter-net external inputs dependencies. This method will insert Copy funcitons if
external inputs of a net is produced on different device than it is required.
Inputs:
nets: a list of nets
Outputs:
new_nets: a list of new nets with device difference solved.
Some notes from wyiming:
1. You MUST pass nets in execution order. e.g. [train_init, train]
"""
assert isinstance(nets, list), \
"nets {} should be a list of nets.".format(str(nets))
assert all(isinstance(net, Net) for net in nets), \
"nets {} should be a list of nets.".format(str(nets))
# A holistic blob to device mapping.
blob_to_device = blob_to_device_init or {}
blob_remap = {}
new_nets = []
for net in nets:
new_net, blob_to_device = InjectCrossDeviceCopies(
net,
blob_to_device=blob_to_device,
blob_remap=blob_remap,
)
new_nets.append(new_net)
return new_nets, blob_to_device
def InjectDeviceCopiesAmongNetsWithoutB2D(nets, blob_to_device_init=None):
new_nets, _ = InjectDeviceCopiesAmongNets(nets, blob_to_device_init)
return new_nets
def get_net_name(netlike):
if isinstance(netlike, Net):
return netlike.Proto().name
elif isinstance(netlike, caffe2_pb2.NetDef):
return netlike.name
else:
return netlike
def output_to_list(op_output):
"""
Ensures that the output of an operator is a list.
Use when an operator has a variable number of outputs, but a list of
outputs is desired even when number of outputs is 1.
Args:
op_output: Either a BlobReferenece or an iterable of BlobReferences.
Returns:
A list of BlobReferences.
"""
assert type(op_output) in (list, tuple, BlobReference)
return (
[op_output]
if isinstance(op_output, BlobReference) else list(op_output))
def _add_net_to_dict(net_dict, net):
name = get_net_name(net)
if name in net_dict:
assert net_dict[name] is None or net == net_dict[name], (
'Different nets with same name: ' + name)
return False
else:
net_dict[name] = net if isinstance(net, Net) else None
return True
class ExecutionStep(object):
_step_names_used = set()
@staticmethod
def _get_next_step_name(basename):
name = basename
next_idx = 1
while name in ExecutionStep._step_names_used:
name = basename + '_' + str(next_idx)
next_idx += 1
ExecutionStep._step_names_used |= set([name])
return name
def __init__(self, name, nets=None, num_iter=None):
self._step = caffe2_pb2.ExecutionStep()
self._step.name = name or ExecutionStep._get_next_step_name('step')
self._net_dict = OrderedDict()
self._is_used = False
self._substeps = []
if nets is not None:
if type(nets) is Net:
nets = [nets]
for net in nets:
if _add_net_to_dict(self._net_dict, net):
self._step.network.extend([get_net_name(net)])
if num_iter is not None:
self._step.num_iter = num_iter
def get_net(self, name):
return self._net_dict[name]
def Name(self):
return self._step.name
def __str__(self):
return self._step.name
def _assert_can_mutate(self):
assert not self._is_used, (
'Cannot mutate a step that has already been added to a plan/step.')
def _notify_is_used(self):
self._is_used = True
def Proto(self):
return self._step
def HasNets(self):
return self._step.network is not None and (
len(self._step.network) > 0)
def HasSubsteps(self):
return self._step.substep is not None and (
len(self._step.substep) > 0)
def Nets(self):
return list(viewvalues(self._net_dict))
def Substeps(self):
return self._substeps
def SetIter(self, num_iter):
self._assert_can_mutate()
self._step.num_iter = num_iter
def SetCreateWorkspace(self, create_workspace):
self._assert_can_mutate()
self._step.create_workspace = create_workspace
def SetNumConcurrentInstances(self, num_concurrent_instances):
self._assert_can_mutate()
self._step.num_concurrent_instances = num_concurrent_instances
def SetOnlyOnce(self, only_once):
self._assert_can_mutate()
self._step.only_once = only_once
def SetShouldStopBlob(self, should_stop_blob):
assert isinstance(should_stop_blob, BlobReference), (
"expects BlobReference here, got {}".format(type(should_stop_blob)))
self._assert_can_mutate()
self._step.should_stop_blob = str(should_stop_blob)
def RunEveryMillis(self, interval):
"""
Run this step every interval millisecods, as long as its
siblings are still running. It is guaranteed that, after all
siblings finish, this step will run at least one.
This property is ignored for top-level ExecutionSteps.
"""
self._step.run_every_ms = interval
def SetReportNet(self, report_net, report_interval):
""" DEPRECATED. Use RunEveryMillis instead. """
self._assert_can_mutate()
_add_net_to_dict(self._net_dict, report_net)
self._step.report_net = get_net_name(report_net)
self._step.report_interval = report_interval
def AddSubstep(self, substep):
self._assert_can_mutate()
assert not self.HasNets(), 'Cannot have both network and substeps.'
if isinstance(substep, ExecutionStep):
substep._notify_is_used()
if not substep.HasNets() and not substep.HasSubsteps():
return self
for net in substep.Nets():
_add_net_to_dict(self._net_dict, net)
self._substeps.append(substep)
proto = substep.Proto()
else:
proto = substep
self._step.substep.add().CopyFrom(proto)
return self
def SetConcurrentSubsteps(self, concurrent_substeps):
self._assert_can_mutate()
assert not self.HasNets(), 'Cannot have both network and substeps.'
self._step.concurrent_substeps = concurrent_substeps
def AddNet(self, net):
self._assert_can_mutate()
assert not self.HasSubsteps(), 'Cannot have both network and substeps.'
assert isinstance(net, Net)
_add_net_to_dict(self._net_dict, net)
self._step.network.extend([get_net_name(net)])
return self
def get_all_attributes(self, name):
"""
Return the list of all attributes under the given `name`, present in
all of the nets used in this execution step and its children.
"""
return [
attr
for net in viewvalues(self._net_dict)
for attr in net.get_attributes(name)
]
@classmethod
def create_from_proto(cls, step_proto, net_obj_dict, net_proto_dict):
"""
Create ExecutionStep from ExecutionStep protobuf recursively
"""
assert isinstance(step_proto, caffe2_pb2.ExecutionStep)
assert (len(step_proto.network) > 0 and len(step_proto.substep) == 0) or \
(len(step_proto.network) == 0 and len(step_proto.substep) > 0)
steps_or_nets = []
if len(step_proto.substep) > 0:
for substep_proto in step_proto.substep:
steps_or_nets.append(ExecutionStep.create_from_proto(
substep_proto, net_obj_dict, net_proto_dict))
else:
for net_name in step_proto.network:
if net_name not in net_obj_dict:
assert net_name in net_proto_dict
net = Net(net_proto_dict[net_name])
net_obj_dict[net_name] = net
net = net_obj_dict[net_name]
assert isinstance(net, Net)
steps_or_nets.append(net)
num_iter = step_proto.num_iter if step_proto.HasField('num_iter') else None
concurrent_substeps = step_proto.concurrent_substeps if\
step_proto.HasField('concurrent_substeps') else None
should_stop_blob = BlobReference(step_proto.should_stop_blob) if\
step_proto.HasField('should_stop_blob') else None
only_once = step_proto.only_once if\
step_proto.HasField('only_once') else None
num_concurrent_instances = step_proto.num_concurrent_instances if\
step_proto.HasField('num_concurrent_instances') else None
create_workspace = step_proto.create_workspace if\
step_proto.HasField('create_workspace') else None
run_every_ms = step_proto.run_every_ms if\
step_proto.HasField('run_every_ms') else None
return execution_step(
step_proto.name,
steps_or_nets,
num_iter=num_iter,
report_net=None, # DEPRECATED
report_interval=None, # DEPRECATED
concurrent_substeps=concurrent_substeps,
should_stop_blob=should_stop_blob,
only_once=only_once,
num_concurrent_instances=num_concurrent_instances,
create_workspace=create_workspace,
run_every_ms=run_every_ms)
def add_nets_in_order(step, net_list):
proto = step.Proto()
for substep in step.Substeps():
add_nets_in_order(substep, net_list)
for net in proto.network:
if net not in net_list:
net_list.append(net)
# FIXME(azzolini): This is actually wrong. Report nets should be
# instantiated first since they may run before any substep is run.
# However, curerntly, Reporter depends on this behavior.
if proto.report_net and proto.report_net not in net_list:
net_list.append(proto.report_net)
class Plan(object):
def __init__(self, name_or_step):
self._plan = caffe2_pb2.PlanDef()
self._net_dict = OrderedDict()
self._steps = [] # A list of ExecutionStep
if isinstance(name_or_step, ExecutionStep):
self._plan.name = name_or_step.Name()
self.AddStep(name_or_step)
elif isinstance(name_or_step, basestring):
self._plan.name = name_or_step
else:
raise ValueError('name_or_step must be a string or ExecutionStep')
def __str__(self):
return self._plan.name
def Proto(self):
return self._plan
def AddNets(self, nets):
for net in nets:
if _add_net_to_dict(self._net_dict, net):
assert isinstance(net, Net)
self._plan.network.add().CopyFrom(net.Proto())
def Nets(self):
return list(viewvalues(self._net_dict))
def AddStep(self, step):
assert isinstance(step, ExecutionStep)
step._notify_is_used()
if not step.HasNets() and not step.HasSubsteps():
return
self._plan.execution_step.add().CopyFrom(step.Proto())
self._steps.append(step)
# nets need to be added to the plan in order of usage
net_list = []
add_nets_in_order(step, net_list)
self.AddNets([step.get_net(n) for n in net_list])
def Steps(self):
return self._steps
def get_all_attributes(self, name):
"""
Return the list of all attributes under the given `name`, present in
all of the nets used in this plan.
"""
return [
attr
for net in viewvalues(self._net_dict)
for attr in net.get_attributes(name)
]
@classmethod
def create_from_proto(cls, plan_proto):
assert isinstance(plan_proto, caffe2_pb2.PlanDef)
plan = Plan(plan_proto.name)
plan._plan.CopyFrom(plan_proto)
net_obj_dict = {}
net_proto_dict = {}
for net_proto in plan_proto.network:
assert net_proto.name not in net_proto_dict
net_proto_dict[net_proto.name] = net_proto
for step_proto in plan_proto.execution_step:
step = ExecutionStep.create_from_proto(
step_proto, net_obj_dict, net_proto_dict)
plan.AddStep(step)
return plan
def to_execution_step(step_or_nets, default_name=None):
from caffe2.python.net_builder import NetBuilder
if isinstance(step_or_nets, ExecutionStep):
return step_or_nets
stop_blob = None
if not default_name and hasattr(step_or_nets, 'name'):
default_name = step_or_nets.name
if isinstance(step_or_nets, NetBuilder):
stop_blob = step_or_nets._stop_blob
step_or_nets = step_or_nets.get()
return execution_step(
default_name, step_or_nets, should_stop_blob=stop_blob)
def execution_step(default_name,
steps_or_nets,
num_iter=None,
report_net=None,
report_interval=None,
concurrent_substeps=None,
should_stop_blob=None,
only_once=None,
num_concurrent_instances=None,
create_workspace=False,
run_every_ms=None):
"""
Helper for creating an ExecutionStep.
- steps_or_nets can be:
- None
- Net
- ExecutionStep
- list<Net>
- list<ExecutionStep>
- should_stop_blob is either None or a scalar boolean blob.
- This blob is checked AFTER every substeps/subnets.
- If specified and true, then this step will return immediately.
- Be sure to handle race conditions if setting from concurrent threads.
- if no should_stop_blob or num_iter is provided, defaults to num_iter=1
"""
assert should_stop_blob is None or num_iter is None, (
'Cannot set both should_stop_blob and num_iter.')
if should_stop_blob is None and num_iter is None:
num_iter = 1
step = ExecutionStep(default_name)
if should_stop_blob is not None:
step.SetShouldStopBlob(should_stop_blob)
if num_iter is not None:
step.SetIter(num_iter)
if only_once is not None:
step.SetOnlyOnce(only_once)
if concurrent_substeps is not None:
step.SetConcurrentSubsteps(concurrent_substeps)
if report_net is not None:
assert report_interval is not None
step.SetReportNet(report_net, report_interval)
if num_concurrent_instances is not None:
step.SetNumConcurrentInstances(num_concurrent_instances)
if create_workspace:
step.SetCreateWorkspace(True)
if run_every_ms:
step.RunEveryMillis(run_every_ms)
if isinstance(steps_or_nets, ExecutionStep):
step.AddSubstep(steps_or_nets)
elif isinstance(steps_or_nets, Net):
step.AddNet(steps_or_nets)
elif isinstance(steps_or_nets, list):
if all(isinstance(x, Net) for x in steps_or_nets):
for x in steps_or_nets:
step.AddNet(x)
else:
for x in steps_or_nets:
step.AddSubstep(to_execution_step(x))
elif steps_or_nets:
raise ValueError(
'steps_or_nets must be a step, a net, or a list of nets or steps.')
return step
def scoped_execution_step(name, *args, **kwargs):
"""Same as execution_step() except that the step name is scoped."""
default_name = ScopedName(name) if name else name
return execution_step(default_name, *args, **kwargs)
def _extract_stacktrace():
'''
This function extracts stacktrace without file system access
by purely using sys._getframe() and removes part that belongs to
this file (core.py). We are not using inspect module because
its just a wrapper on top of sys._getframe() whos
logis is based on accessing source files on disk - exactly what
we are trying to avoid here. Same stands for traceback module
The reason for file system access avoidance is that
if code is located on an NFS, file access might be slow
Function returns a list of tuples (file_name, line_number, function)
'''
result = []
# Ignore top 3 layers of stack: this function, _CreateAndAddToSelf, and
# whatever calls _CreateAndAddToSelf (either __getattr__ or Python)
frame = sys._getframe(3)
# We just go down the frame stack in a loop
while frame:
# Its important to extract information from the frame here
# as frame's current line most probably will change later.
result.append((frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name))
frame = frame.f_back
return result
SetPerOpEnginePref = C.set_per_op_engine_pref
SetGlobalEnginePref = C.set_global_engine_pref
SetEnginePref = C.set_engine_pref
SetOpEnginePref = C.set_op_engine_pref
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import numpy as np
import struct
from hypothesis import given
# Eigen/Python round 0.5 away from 0, Numpy rounds to even
round_to_nearest = np.vectorize(round)
def bytes_to_floats(byte_matrix):
floats = np.empty([np.shape(byte_matrix)[0], 1], dtype=np.float32)
for i, byte_values in enumerate(byte_matrix):
floats[i], = struct.unpack('f', bytearray(byte_values))
return floats
def floats_to_bytes(floats):
byte_matrix = np.empty([np.shape(floats)[0], 4], dtype=np.uint8)
for i, value in enumerate(floats):
assert isinstance(value, np.float32), (value, floats)
as_bytes = struct.pack('f', value)
# In Python3 bytes will be a list of int, in Python2 a list of string
if isinstance(as_bytes[0], int):
byte_matrix[i] = list(as_bytes)
else:
byte_matrix[i] = list(map(ord, as_bytes))
return byte_matrix
def fused_rowwise_8bit_quantize_reference(data):
minimum = np.min(data, axis=1, keepdims=True)
maximum = np.max(data, axis=1, keepdims=True)
span = maximum - minimum
bias = minimum
scale = span / 255.0
inverse_scale = 255.0 / (span + 1e-8)
quantized_data = round_to_nearest((data - bias) * inverse_scale)
scale_bytes = floats_to_bytes(scale.reshape(-1))
bias_bytes = floats_to_bytes(bias.reshape(-1))
return np.concatenate([quantized_data, scale_bytes, bias_bytes], axis=1)
def fused_rowwise_8bit_quantize_dequantize_reference(data):
fused_quantized = fused_rowwise_8bit_quantize_reference(data)
scale = bytes_to_floats(fused_quantized[:, -8:-4].astype(np.uint8))
bias = bytes_to_floats(fused_quantized[:, -4:].astype(np.uint8))
quantized_data = fused_quantized[:, :-8]
return quantized_data * scale + bias
class TestFused8BitRowwiseQuantizationConversion(hu.HypothesisTestCase):
@given(input_data=hu.tensor(min_dim=2, max_dim=2))
def test_quantize_op(self, input_data):
quantize = core.CreateOperator(
'FloatToFused8BitRowwiseQuantized',
['input_data'],
['quantized_data'],
)
workspace.FeedBlob('input_data', input_data)
workspace.RunOperatorOnce(quantize)
quantized_data = workspace.FetchBlob('quantized_data')
reference = fused_rowwise_8bit_quantize_reference(
input_data.astype(np.float32)
)
np.testing.assert_array_almost_equal(quantized_data, reference)
@given(input_data=hu.tensor(min_dim=2, max_dim=2))
def test_quantize_and_dequantize_op(self, input_data):
quantize = core.CreateOperator(
'FloatToFused8BitRowwiseQuantized',
['input_data'],
['quantized_data'],
)
workspace.FeedBlob('input_data', input_data)
workspace.RunOperatorOnce(quantize)
quantized_data = workspace.FetchBlob('quantized_data')
dequantize = core.CreateOperator(
'Fused8BitRowwiseQuantizedToFloat',
['quantized_data'],
['dequantized_data'],
)
workspace.FeedBlob('quantized_data', quantized_data)
workspace.RunOperatorOnce(dequantize)
dequantized_data = workspace.FetchBlob('dequantized_data')
reference = fused_rowwise_8bit_quantize_dequantize_reference(input_data)
np.testing.assert_array_almost_equal(dequantized_data, reference)
|
## @package queue_util
# Module caffe2.python.queue_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, dataio
from caffe2.python.task import TaskGroup
import logging
logger = logging.getLogger(__name__)
class _QueueReader(dataio.Reader):
def __init__(self, wrapper, num_dequeue_records=1):
assert wrapper.schema is not None, (
'Queue needs a schema in order to be read from.')
dataio.Reader.__init__(self, wrapper.schema())
self._wrapper = wrapper
self._num_dequeue_records = num_dequeue_records
def setup_ex(self, init_net, exit_net):
exit_net.CloseBlobsQueue([self._wrapper.queue()], 0)
def read_ex(self, local_init_net, local_finish_net):
self._wrapper._new_reader(local_init_net)
dequeue_net = core.Net('dequeue')
fields, status_blob = dequeue(
dequeue_net,
self._wrapper.queue(),
len(self.schema().field_names()),
field_names=self.schema().field_names(),
num_records=self._num_dequeue_records)
return [dequeue_net], status_blob, fields
def read(self, net):
net, _, fields = self.read_ex(net, None)
return net, fields
class _QueueWriter(dataio.Writer):
def __init__(self, wrapper):
self._wrapper = wrapper
def setup_ex(self, init_net, exit_net):
exit_net.CloseBlobsQueue([self._wrapper.queue()], 0)
def write_ex(self, fields, local_init_net, local_finish_net, status):
self._wrapper._new_writer(self.schema(), local_init_net)
enqueue_net = core.Net('enqueue')
enqueue(enqueue_net, self._wrapper.queue(), fields, status)
return [enqueue_net]
class QueueWrapper(dataio.Pipe):
def __init__(self, handler, schema=None, num_dequeue_records=1):
dataio.Pipe.__init__(self, schema, TaskGroup.LOCAL_SETUP)
self._queue = handler
self._num_dequeue_records = num_dequeue_records
def reader(self):
return _QueueReader(
self, num_dequeue_records=self._num_dequeue_records)
def writer(self):
return _QueueWriter(self)
def queue(self):
return self._queue
class Queue(QueueWrapper):
def __init__(self, capacity, schema=None, name='queue',
num_dequeue_records=1):
# find a unique blob name for the queue
net = core.Net(name)
queue_blob = net.AddExternalInput(net.NextName('handler'))
QueueWrapper.__init__(
self, queue_blob, schema, num_dequeue_records=num_dequeue_records)
self.capacity = capacity
self._setup_done = False
def setup(self, global_init_net):
assert self._schema, 'This queue does not have a schema.'
self._setup_done = True
global_init_net.CreateBlobsQueue(
[],
[self._queue],
capacity=self.capacity,
num_blobs=len(self._schema.field_names()),
field_names=self._schema.field_names())
def enqueue(net, queue, data_blobs, status=None):
if status is None:
status = net.NextName('status')
# Enqueueing moved the data into the queue;
# duplication will result in data corruption
queue_blobs = []
for blob in data_blobs:
if blob not in queue_blobs:
queue_blobs.append(blob)
else:
logger.warning("Need to copy blob {} to enqueue".format(blob))
queue_blobs.append(net.Copy(blob))
results = net.SafeEnqueueBlobs([queue] + queue_blobs, queue_blobs + [status])
return results[-1]
def dequeue(net, queue, num_blobs, status=None, field_names=None,
num_records=1):
if field_names is not None:
assert len(field_names) == num_blobs
data_names = [net.NextName(name) for name in field_names]
else:
data_names = [net.NextName('data', i) for i in range(num_blobs)]
if status is None:
status = net.NextName('status')
results = net.SafeDequeueBlobs(
queue, data_names + [status], num_records=num_records)
results = list(results)
status_blob = results.pop(-1)
return results, status_blob
def close_queue(step, *queues):
close_net = core.Net("close_queue_net")
for queue in queues:
close_net.CloseBlobsQueue([queue], 0)
close_step = core.execution_step("%s_step" % str(close_net), close_net)
return core.execution_step(
"%s_wraper_step" % str(close_net),
[step, close_step])
|
## @package predictor_constants
# Module caffe2.python.predictor_constants
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import caffe2.proto.predictor_consts_pb2 as predictor_consts
predictor_constants = predictor_consts.PredictorConsts()
|
## @package convnet_benchmarks
# Module caffe2.python.convnet_benchmarks
"""
Benchmark for common convnets.
Speed on Titan X, with 10 warmup steps and 10 main steps and with different
versions of cudnn, are as follows (time reported below is per-batch time,
forward / forward+backward):
CuDNN V3 CuDNN v4
AlexNet 32.5 / 108.0 27.4 / 90.1
OverFeat 113.0 / 342.3 91.7 / 276.5
Inception 134.5 / 485.8 125.7 / 450.6
VGG (batch 64) 200.8 / 650.0 164.1 / 551.7
Speed on Inception with varied batch sizes and CuDNN v4 is as follows:
Batch Size Speed per batch Speed per image
16 22.8 / 72.7 1.43 / 4.54
32 38.0 / 127.5 1.19 / 3.98
64 67.2 / 233.6 1.05 / 3.65
128 125.7 / 450.6 0.98 / 3.52
Speed on Tesla M40, which 10 warmup steps and 10 main steps and with cudnn
v4, is as follows:
AlexNet 68.4 / 218.1
OverFeat 210.5 / 630.3
Inception 300.2 / 1122.2
VGG (batch 64) 405.8 / 1327.7
(Note that these numbers involve a "full" backprop, i.e. the gradient
with respect to the input image is also computed.)
To get the numbers, simply run:
for MODEL in AlexNet OverFeat Inception; do
PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \
--batch_size 128 --model $MODEL --forward_only True
done
for MODEL in AlexNet OverFeat Inception; do
PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \
--batch_size 128 --model $MODEL
done
PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \
--batch_size 64 --model VGGA --forward_only True
PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \
--batch_size 64 --model VGGA
for BS in 16 32 64 128; do
PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \
--batch_size $BS --model Inception --forward_only True
PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \
--batch_size $BS --model Inception
done
Note that VGG needs to be run at batch 64 due to memory limit on the backward
pass.
"""
import argparse
from caffe2.python import workspace, brew, model_helper
def MLP(order, cudnn_ws):
model = model_helper.ModelHelper(name="MLP")
d = 256
depth = 20
width = 3
for i in range(depth):
for j in range(width):
current = "fc_{}_{}".format(i, j) if i > 0 else "data"
next_ = "fc_{}_{}".format(i + 1, j)
brew.fc(
model,
current,
next_,
dim_in=d,
dim_out=d,
weight_init=('XavierFill', {}),
bias_init=('XavierFill', {}),
)
brew.sum(
model, ["fc_{}_{}".format(depth, j) for j in range(width)], ["sum"]
)
brew.fc(
model,
"sum",
"last",
dim_in=d,
dim_out=1000,
weight_init=('XavierFill', {}),
bias_init=('XavierFill', {}),
)
xent = model.net.LabelCrossEntropy(["last", "label"], "xent")
model.net.AveragedLoss(xent, "loss")
return model, d
def AlexNet(order, cudnn_ws):
my_arg_scope = {
'order': order,
'use_cudnn': True,
'cudnn_exhaustive_search': True,
}
if cudnn_ws:
my_arg_scope['ws_nbytes_limit'] = cudnn_ws
model = model_helper.ModelHelper(
name="alexnet",
arg_scope=my_arg_scope,
)
conv1 = brew.conv(
model,
"data",
"conv1",
3,
64,
11, ('XavierFill', {}), ('ConstantFill', {}),
stride=4,
pad=2
)
relu1 = brew.relu(model, conv1, "conv1")
pool1 = brew.max_pool(model, relu1, "pool1", kernel=3, stride=2)
conv2 = brew.conv(
model,
pool1,
"conv2",
64,
192,
5,
('XavierFill', {}),
('ConstantFill', {}),
pad=2
)
relu2 = brew.relu(model, conv2, "conv2")
pool2 = brew.max_pool(model, relu2, "pool2", kernel=3, stride=2)
conv3 = brew.conv(
model,
pool2,
"conv3",
192,
384,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1
)
relu3 = brew.relu(model, conv3, "conv3")
conv4 = brew.conv(
model,
relu3,
"conv4",
384,
256,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1
)
relu4 = brew.relu(model, conv4, "conv4")
conv5 = brew.conv(
model,
relu4,
"conv5",
256,
256,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1
)
relu5 = brew.relu(model, conv5, "conv5")
pool5 = brew.max_pool(model, relu5, "pool5", kernel=3, stride=2)
fc6 = brew.fc(
model,
pool5, "fc6", 256 * 6 * 6, 4096, ('XavierFill', {}),
('ConstantFill', {})
)
relu6 = brew.relu(model, fc6, "fc6")
fc7 = brew.fc(
model, relu6, "fc7", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {})
)
relu7 = brew.relu(model, fc7, "fc7")
fc8 = brew.fc(
model, relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {})
)
pred = brew.softmax(model, fc8, "pred")
xent = model.net.LabelCrossEntropy([pred, "label"], "xent")
model.net.AveragedLoss(xent, "loss")
return model, 224
def OverFeat(order, cudnn_ws):
my_arg_scope = {
'order': order,
'use_cudnn': True,
'cudnn_exhaustive_search': True,
}
if cudnn_ws:
my_arg_scope['ws_nbytes_limit'] = cudnn_ws
model = model_helper.ModelHelper(
name="overfeat",
arg_scope=my_arg_scope,
)
conv1 = brew.conv(
model,
"data",
"conv1",
3,
96,
11,
('XavierFill', {}),
('ConstantFill', {}),
stride=4,
)
relu1 = brew.relu(model, conv1, "conv1")
pool1 = brew.max_pool(model, relu1, "pool1", kernel=2, stride=2)
conv2 = brew.conv(
model, pool1, "conv2", 96, 256, 5, ('XavierFill', {}),
('ConstantFill', {})
)
relu2 = brew.relu(model, conv2, "conv2")
pool2 = brew.max_pool(model, relu2, "pool2", kernel=2, stride=2)
conv3 = brew.conv(
model,
pool2,
"conv3",
256,
512,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu3 = brew.relu(model, conv3, "conv3")
conv4 = brew.conv(
model,
relu3,
"conv4",
512,
1024,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu4 = brew.relu(model, conv4, "conv4")
conv5 = brew.conv(
model,
relu4,
"conv5",
1024,
1024,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu5 = brew.relu(model, conv5, "conv5")
pool5 = brew.max_pool(model, relu5, "pool5", kernel=2, stride=2)
fc6 = brew.fc(
model, pool5, "fc6", 1024 * 6 * 6, 3072, ('XavierFill', {}),
('ConstantFill', {})
)
relu6 = brew.relu(model, fc6, "fc6")
fc7 = brew.fc(
model, relu6, "fc7", 3072, 4096, ('XavierFill', {}), ('ConstantFill', {})
)
relu7 = brew.relu(model, fc7, "fc7")
fc8 = brew.fc(
model, relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {})
)
pred = brew.softmax(model, fc8, "pred")
xent = model.net.LabelCrossEntropy([pred, "label"], "xent")
model.net.AveragedLoss(xent, "loss")
return model, 231
def VGGA(order, cudnn_ws):
my_arg_scope = {
'order': order,
'use_cudnn': True,
'cudnn_exhaustive_search': True,
}
if cudnn_ws:
my_arg_scope['ws_nbytes_limit'] = cudnn_ws
model = model_helper.ModelHelper(
name="vgga",
arg_scope=my_arg_scope,
)
conv1 = brew.conv(
model,
"data",
"conv1",
3,
64,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu1 = brew.relu(model, conv1, "conv1")
pool1 = brew.max_pool(model, relu1, "pool1", kernel=2, stride=2)
conv2 = brew.conv(
model,
pool1,
"conv2",
64,
128,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu2 = brew.relu(model, conv2, "conv2")
pool2 = brew.max_pool(model, relu2, "pool2", kernel=2, stride=2)
conv3 = brew.conv(
model,
pool2,
"conv3",
128,
256,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu3 = brew.relu(model, conv3, "conv3")
conv4 = brew.conv(
model,
relu3,
"conv4",
256,
256,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu4 = brew.relu(model, conv4, "conv4")
pool4 = brew.max_pool(model, relu4, "pool4", kernel=2, stride=2)
conv5 = brew.conv(
model,
pool4,
"conv5",
256,
512,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu5 = brew.relu(model, conv5, "conv5")
conv6 = brew.conv(
model,
relu5,
"conv6",
512,
512,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu6 = brew.relu(model, conv6, "conv6")
pool6 = brew.max_pool(model, relu6, "pool6", kernel=2, stride=2)
conv7 = brew.conv(
model,
pool6,
"conv7",
512,
512,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu7 = brew.relu(model, conv7, "conv7")
conv8 = brew.conv(
model,
relu7,
"conv8",
512,
512,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu8 = brew.relu(model, conv8, "conv8")
pool8 = brew.max_pool(model, relu8, "pool8", kernel=2, stride=2)
fcix = brew.fc(
model, pool8, "fcix", 512 * 7 * 7, 4096, ('XavierFill', {}),
('ConstantFill', {})
)
reluix = brew.relu(model, fcix, "fcix")
fcx = brew.fc(
model, reluix, "fcx", 4096, 4096, ('XavierFill', {}),
('ConstantFill', {})
)
relux = brew.relu(model, fcx, "fcx")
fcxi = brew.fc(
model, relux, "fcxi", 4096, 1000, ('XavierFill', {}),
('ConstantFill', {})
)
pred = brew.softmax(model, fcxi, "pred")
xent = model.net.LabelCrossEntropy([pred, "label"], "xent")
model.net.AveragedLoss(xent, "loss")
return model, 231
def _InceptionModule(
model, input_blob, input_depth, output_name, conv1_depth, conv3_depths,
conv5_depths, pool_depth
):
# path 1: 1x1 conv
conv1 = brew.conv(
model, input_blob, output_name + ":conv1", input_depth, conv1_depth, 1,
('XavierFill', {}), ('ConstantFill', {})
)
conv1 = brew.relu(model, conv1, conv1)
# path 2: 1x1 conv + 3x3 conv
conv3_reduce = brew.conv(
model, input_blob, output_name + ":conv3_reduce", input_depth,
conv3_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {})
)
conv3_reduce = brew.relu(model, conv3_reduce, conv3_reduce)
conv3 = brew.conv(
model,
conv3_reduce,
output_name + ":conv3",
conv3_depths[0],
conv3_depths[1],
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
conv3 = brew.relu(model, conv3, conv3)
# path 3: 1x1 conv + 5x5 conv
conv5_reduce = brew.conv(
model, input_blob, output_name + ":conv5_reduce", input_depth,
conv5_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {})
)
conv5_reduce = brew.relu(model, conv5_reduce, conv5_reduce)
conv5 = brew.conv(
model,
conv5_reduce,
output_name + ":conv5",
conv5_depths[0],
conv5_depths[1],
5,
('XavierFill', {}),
('ConstantFill', {}),
pad=2,
)
conv5 = brew.relu(model, conv5, conv5)
# path 4: pool + 1x1 conv
pool = brew.max_pool(
model,
input_blob,
output_name + ":pool",
kernel=3,
stride=1,
pad=1,
)
pool_proj = brew.conv(
model, pool, output_name + ":pool_proj", input_depth, pool_depth, 1,
('XavierFill', {}), ('ConstantFill', {})
)
pool_proj = brew.relu(model, pool_proj, pool_proj)
output = brew.concat(model, [conv1, conv3, conv5, pool_proj], output_name)
return output
def Inception(order, cudnn_ws):
my_arg_scope = {
'order': order,
'use_cudnn': True,
'cudnn_exhaustive_search': True,
}
if cudnn_ws:
my_arg_scope['ws_nbytes_limit'] = cudnn_ws
model = model_helper.ModelHelper(
name="inception",
arg_scope=my_arg_scope,
)
conv1 = brew.conv(
model,
"data",
"conv1",
3,
64,
7,
('XavierFill', {}),
('ConstantFill', {}),
stride=2,
pad=3,
)
relu1 = brew.relu(model, conv1, "conv1")
pool1 = brew.max_pool(model, relu1, "pool1", kernel=3, stride=2, pad=1)
conv2a = brew.conv(
model, pool1, "conv2a", 64, 64, 1, ('XavierFill', {}),
('ConstantFill', {})
)
conv2a = brew.relu(model, conv2a, conv2a)
conv2 = brew.conv(
model,
conv2a,
"conv2",
64,
192,
3,
('XavierFill', {}),
('ConstantFill', {}),
pad=1,
)
relu2 = brew.relu(model, conv2, "conv2")
pool2 = brew.max_pool(model, relu2, "pool2", kernel=3, stride=2, pad=1)
# Inception modules
inc3 = _InceptionModule(
model, pool2, 192, "inc3", 64, [96, 128], [16, 32], 32
)
inc4 = _InceptionModule(
model, inc3, 256, "inc4", 128, [128, 192], [32, 96], 64
)
pool5 = brew.max_pool(model, inc4, "pool5", kernel=3, stride=2, pad=1)
inc5 = _InceptionModule(
model, pool5, 480, "inc5", 192, [96, 208], [16, 48], 64
)
inc6 = _InceptionModule(
model, inc5, 512, "inc6", 160, [112, 224], [24, 64], 64
)
inc7 = _InceptionModule(
model, inc6, 512, "inc7", 128, [128, 256], [24, 64], 64
)
inc8 = _InceptionModule(
model, inc7, 512, "inc8", 112, [144, 288], [32, 64], 64
)
inc9 = _InceptionModule(
model, inc8, 528, "inc9", 256, [160, 320], [32, 128], 128
)
pool9 = brew.max_pool(model, inc9, "pool9", kernel=3, stride=2, pad=1)
inc10 = _InceptionModule(
model, pool9, 832, "inc10", 256, [160, 320], [32, 128], 128
)
inc11 = _InceptionModule(
model, inc10, 832, "inc11", 384, [192, 384], [48, 128], 128
)
pool11 = brew.average_pool(model, inc11, "pool11", kernel=7, stride=1)
fc = brew.fc(
model, pool11, "fc", 1024, 1000, ('XavierFill', {}),
('ConstantFill', {})
)
# It seems that Soumith's benchmark does not have softmax on top
# for Inception. We will add it anyway so we can have a proper
# backward pass.
pred = brew.softmax(model, fc, "pred")
xent = model.net.LabelCrossEntropy([pred, "label"], "xent")
model.net.AveragedLoss(xent, "loss")
return model, 224
def AddParameterUpdate(model):
""" Simple plain SGD update -- not tuned to actually train the models """
ITER = brew.iter(model, "iter")
LR = model.net.LearningRate(
ITER, "LR", base_lr=-1e-8, policy="step", stepsize=10000, gamma=0.999)
ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0)
for param in model.params:
param_grad = model.param_to_grad[param]
model.net.WeightedSum([param, ONE, param_grad, LR], param)
def Benchmark(model_gen, arg):
model, input_size = model_gen(arg.order, arg.cudnn_ws)
model.Proto().type = arg.net_type
model.Proto().num_workers = arg.num_workers
# In order to be able to run everything without feeding more stuff, let's
# add the data and label blobs to the parameter initialization net as well.
if arg.order == "NCHW":
input_shape = [arg.batch_size, 3, input_size, input_size]
else:
input_shape = [arg.batch_size, input_size, input_size, 3]
if arg.model == "MLP":
input_shape = [arg.batch_size, input_size]
model.param_init_net.GaussianFill(
[],
"data",
shape=input_shape,
mean=0.0,
std=1.0
)
model.param_init_net.UniformIntFill(
[],
"label",
shape=[arg.batch_size, ],
min=0,
max=999
)
if arg.forward_only:
print('{}: running forward only.'.format(arg.model))
else:
print('{}: running forward-backward.'.format(arg.model))
model.AddGradientOperators(["loss"])
AddParameterUpdate(model)
if arg.order == 'NHWC':
print(
'==WARNING==\n'
'NHWC order with CuDNN may not be supported yet, so I might\n'
'exit suddenly.'
)
if not arg.cpu:
model.param_init_net.RunAllOnGPU()
model.net.RunAllOnGPU()
if arg.engine:
for op in model.net.Proto().op:
op.engine = arg.engine
if arg.dump_model:
# Writes out the pbtxt for benchmarks on e.g. Android
with open(
"{0}_init_batch_{1}.pbtxt".format(arg.model, arg.batch_size), "w"
) as fid:
fid.write(str(model.param_init_net.Proto()))
with open("{0}.pbtxt".format(arg.model, arg.batch_size), "w") as fid:
fid.write(str(model.net.Proto()))
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
workspace.BenchmarkNet(
model.net.Proto().name, arg.warmup_iterations, arg.iterations,
arg.layer_wise_benchmark)
def GetArgumentParser():
parser = argparse.ArgumentParser(description="Caffe2 benchmark.")
parser.add_argument(
"--batch_size",
type=int,
default=128,
help="The batch size."
)
parser.add_argument("--model", type=str, help="The model to benchmark.")
parser.add_argument(
"--order",
type=str,
default="NCHW",
help="The order to evaluate."
)
parser.add_argument(
"--cudnn_ws",
type=int,
help="The cudnn workspace size."
)
parser.add_argument(
"--iterations",
type=int,
default=10,
help="Number of iterations to run the network."
)
parser.add_argument(
"--warmup_iterations",
type=int,
default=10,
help="Number of warm-up iterations before benchmarking."
)
parser.add_argument(
"--forward_only",
action='store_true',
help="If set, only run the forward pass."
)
parser.add_argument(
"--layer_wise_benchmark",
action='store_true',
help="If True, run the layer-wise benchmark as well."
)
parser.add_argument(
"--cpu",
action='store_true',
help="If True, run testing on CPU instead of GPU."
)
parser.add_argument(
"--engine",
type=str,
default="",
help="If set, blindly prefer the given engine(s) for every op.")
parser.add_argument(
"--dump_model",
action='store_true',
help="If True, dump the model prototxts to disk."
)
parser.add_argument("--net_type", type=str, default="dag")
parser.add_argument("--num_workers", type=int, default=2)
parser.add_argument("--use-nvtx", default=False, action='store_true')
parser.add_argument("--htrace_span_log_path", type=str)
return parser
if __name__ == '__main__':
args, extra_args = GetArgumentParser().parse_known_args()
if (
not args.batch_size or not args.model or not args.order
):
GetArgumentParser().print_help()
else:
workspace.GlobalInit(
['caffe2', '--caffe2_log_level=0'] + extra_args +
(['--caffe2_use_nvtx'] if args.use_nvtx else []) +
(['--caffe2_htrace_span_log_path=' + args.htrace_span_log_path]
if args.htrace_span_log_path else []))
model_map = {
'AlexNet': AlexNet,
'OverFeat': OverFeat,
'VGGA': VGGA,
'Inception': Inception,
'MLP': MLP,
}
Benchmark(model_map[args.model], args)
|
## @package gradient_checker
# Module caffe2.python.gradient_checker
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace, net_drawer
from caffe2.proto import caffe2_pb2
def _get_grad_blob(grad_map, input_to_check):
grad_blob = grad_map[input_to_check]
if isinstance(grad_blob, core.BlobReference):
return workspace.blobs[grad_blob]
# If grad_blob is not a single blob, it should be a gradient slice.
# To make it comparable with the estimiated gradient which is dense,
# we need to first convert grad_blob to dense gradient.
assert isinstance(grad_blob, core.GradientSlice)
dense_grad = 'tmp_dense_grad'
sparse_to_dense_op = core.CreateOperator(
'SparseToDense',
[grad_blob.indices, grad_blob.values, input_to_check],
dense_grad,
)
workspace.RunOperatorOnce(sparse_to_dense_op)
return workspace.blobs[dense_grad]
def _get_grad(net, outputs, outputs_with_grad, input_values, inputs_with_grads):
grad_net = net.Clone(net.Name() + "_copy")
grad_map = grad_net.AddGradientOperators(outputs_with_grad)
for name, value in (input_values or {}).items():
workspace.blobs[name] = value
for input_to_check in inputs_with_grads:
assert input_to_check in grad_map, (
'{} has no gradient, cannot check net gradient.'.format(
input_to_check))
assert str(input_to_check) in workspace.blobs
workspace.RunNetOnce(grad_net)
forward_results = [(output, workspace.blobs[output]) for output in outputs]
grads = {input_to_check: _get_grad_blob(grad_map, input_to_check)
for input_to_check in inputs_with_grads}
return forward_results, grads, grad_net
def _assert_close(value1, value2, threshold, err_msg=''):
np.testing.assert_allclose(
value1, value2,
atol=threshold, rtol=threshold,
err_msg=err_msg,
)
delta = np.abs(value1 - value2).flatten()
return np.mean(delta), max(delta)
class NetGradientChecker(object):
@staticmethod
def CompareNets(nets, outputs, outputs_with_grad_ids,
inputs_with_grads, input_values=None,
threshold=0.0000001, print_net_images=False):
def _get_output_with_grad_names(net_outputs):
return [net_outputs[i] for i in outputs_with_grad_ids]
if print_net_images:
for i, net in enumerate(nets):
png = net_drawer.GetPydotGraph(net).create_png()
with open("caffe2_net_forward_" + str(i) + net.Name() + ".png",
'wb') \
as f:
f.write(png)
results = [
_get_grad(net, net_outputs,
_get_output_with_grad_names(net_outputs),
input_values, inputs_with_grads)
for net, net_outputs in zip(nets, outputs)
]
if print_net_images:
_, _, backward_nets = zip(*results)
for i, net in enumerate(backward_nets):
png = net_drawer.GetPydotGraph(net).create_png()
with open("caffe2_net_" + str(i) + net.Name() + ".png", 'wb') \
as f:
f.write(png)
first_net_results, first_net_grads, _ = results[0]
for net_results, net_grads, _ in results[1:]:
assert len(net_results) == len(first_net_results)
for idx, ((blob1, blob_value1), (blob2, blob_value2)) in enumerate(
zip(first_net_results, net_results)):
_assert_close(
blob_value1, blob_value2, threshold,
err_msg="Different forward pass results for output id {}. "
"Corresponding output blobs: {} and {}".format(
idx, blob1, blob2))
assert net_grads.keys() == first_net_grads.keys()
for blob, blob_grad_value in net_grads.items():
_assert_close(
first_net_grads[blob], blob_grad_value, threshold,
err_msg="Different gradients for input {}".format(blob))
@staticmethod
def Check(net, outputs_with_grad, input_values,
input_to_check, step_size=0.0001,
threshold=0.05, print_net=True):
net_results, net_grads, full_net = _get_grad(
net, [], outputs_with_grad, input_values, [input_to_check])
analytic_grad = net_grads[input_to_check]
def GetLoss(new_value):
workspace.blobs[input_to_check] = new_value
workspace.RunNetOnce(full_net)
return sum([
workspace.blobs[output]
for output in outputs_with_grad
]).sum()
def GetValue(dim, delta):
input_value = input_values[input_to_check].copy()
input_value.flat[dim] += delta
return input_value
grad_estimate = np.zeros_like(input_values[input_to_check])
for dim in range(input_values[input_to_check].size):
pos_loss = GetLoss(GetValue(dim, step_size))
neg_loss = GetLoss(GetValue(dim, -step_size))
grad_estimate.flat[dim] = (pos_loss - neg_loss) / step_size / 2
err_msg = "Error in gradient check for net_copy {}".format(
net.Name())
if print_net:
err_msg += ": {}".format(net.Proto())
return _assert_close(analytic_grad, grad_estimate, threshold, err_msg)
class GradientChecker:
"""A gradient checker in Python.
This is not the most efficient way to check gradients, as the Python
interface will involve a lot of copies back and forth operations. Use at your
own risk.
"""
def __init__(
self,
stepsize,
threshold,
device_option=caffe2_pb2.DeviceOption(),
workspace_name="gradient_check"
):
self._stepsize = stepsize
self._threshold = threshold
self._device_option = device_option
self._workspace_name = workspace_name
def GetLossAndGrad(
self, op, grad_ops, x, input_name, grad_name, outputs_with_grads
):
# First, feed in the current input. Note that we are not changing
# anything else, so we don't need to feed in others.
workspace.FeedBlob(input_name, x, self._device_option)
# Run.
workspace.RunOperatorOnce(op)
loss = 0.
# Get Loss and feed in the gradients, run gradient ops.
for idx in outputs_with_grads:
name = op.output[idx]
arr = workspace.FetchBlob(name)
loss += (arr**2).sum()
workspace.FeedBlob(name + '_grad', arr, self._device_option)
loss /= 2.
# Run gradient ops
workspace.RunOperatorsOnce(grad_ops)
# Get gradients
if isinstance(grad_name, core.GradientSlice):
workspace.FeedBlob('zeros', np.zeros_like(x, dtype=np.float32))
workspace.FeedBlob('ones', np.ones(1, dtype=np.float32))
gv_cpu_op = core.CreateOperator(
'EnsureCPUOutput', grad_name.values, grad_name.values + '_cpu',
device_option=self._device_option
)
gi_cpu_op = core.CreateOperator(
'EnsureCPUOutput', grad_name.indices, grad_name.indices + '_cpu',
device_option=self._device_option
)
sparse_to_dense_op = core.CreateOperator(
'ScatterWeightedSum',
[
'zeros', 'ones', grad_name.indices + '_cpu',
grad_name.values + '_cpu', 'ones'
],
'zeros',
)
workspace.RunOperatorOnce(gv_cpu_op)
workspace.RunOperatorOnce(gi_cpu_op)
workspace.RunOperatorOnce(sparse_to_dense_op)
grad = workspace.FetchBlob('zeros')
else:
grad = workspace.FetchBlob(grad_name)
return loss, grad
def CheckSimple(
self,
op,
inputs,
input_to_check,
outputs_with_grads,
grad_ops=None,
input_device_options=None
):
"""Checks the operator in a very simple fashion by stacking a sum of
squares on the top.
Inputs:
op: the operator to be checked.
inputs: the input data in numpy arrays.
input_to_check: an index specifying which input blob we should
check.
outputs_with_grads: indices specifying which output blobs will we
need to check gradients with. For these outputs, we will collect a
squared sum and also feed in their gradients.
grad_operator: the gradient operator. If not given, we will get the
gradient operator from the gradient registry.
input_device_options: an optional mapping from input names to
DeviceOptions (to override the default DeviceOption)
Outputs:
boolean: True if it passes, False if it does not pass.
"""
if input_device_options is None:
input_device_options = {}
# Entering the checker workspace
old_ws_name = workspace.CurrentWorkspace()
if self._workspace_name != old_ws_name:
workspace.SwitchWorkspace(self._workspace_name, True)
op.device_option.CopyFrom(self._device_option)
if grad_ops is None:
# TODO(jiayq): use the gradient registration instead of the old
# hack.
grad_ops, g_input = core.GradientRegistry.GetGradientForOp(
op, [s + '_grad' for s in op.output])
dims_to_check = inputs[input_to_check].size
# First, feed in the input.
for i, arr in enumerate(inputs):
workspace.FeedBlob(
op.input[i], arr,
input_device_options.get(
op.input[i], self._device_option))
# Get the loss and gradient for the original.
input_name = op.input[input_to_check]
grad_name = g_input[input_to_check]
loss, grad = self.GetLossAndGrad(
op, grad_ops, inputs[input_to_check], input_name, grad_name,
outputs_with_grads
)
grad_estimate = np.zeros_like(inputs[input_to_check])
if grad_estimate.shape != grad.shape:
raise Exception(
"Mismatched gradient shapes: estimated ({}), grad ({})".format(
grad_estimate.shape, grad.shape))
for current_dim in range(dims_to_check):
# Positive gradient
inputs[input_to_check].flat[current_dim] += self._stepsize
pos_loss, _ = self.GetLossAndGrad(
op, grad_ops, inputs[input_to_check], input_name,
grad_name, outputs_with_grads
)
# Negative gradient
inputs[input_to_check].flat[current_dim] -= self._stepsize * 2
neg_loss, _ = self.GetLossAndGrad(
op, grad_ops, inputs[input_to_check], input_name,
grad_name, outputs_with_grads
)
# Recover the value
inputs[input_to_check].flat[current_dim] += self._stepsize
grad_estimate.flat[current_dim] = (
pos_loss - neg_loss) / self._stepsize / 2
# Now, check correctness
fail_mat = ~np.isclose(
grad, grad_estimate, atol=self._threshold, rtol=self._threshold)
if np.any(fail_mat):
idx = np.flatnonzero(fail_mat)
print('Failed. [idx, grad, grad_estimate] are:')
print(np.vstack([idx, grad.flat[idx], grad_estimate.flat[idx]]).T)
ret = False
else:
ret = True
# After finishing, cleaning up things.
if self._workspace_name != old_ws_name:
# We reset the workspace to make sure everything intermediate is
# cleaned up. Note that there is no need to delete a workspace -
# when empty it takes a very limited amount of memory.
workspace.ResetWorkspace()
workspace.SwitchWorkspace(old_ws_name)
return ret, grad, grad_estimate
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
import time
from functools import partial, reduce
from future.utils import viewitems, viewkeys
from hypothesis import assume, given, settings, HealthCheck
import hypothesis.strategies as st
import unittest
from caffe2.python import core, workspace, tt_core, dyndep
import caffe2.python.hypothesis_test_util as hu
from caffe2.proto.caffe2_pb2 import TensorProto
dyndep.InitOpsLibrary('@/caffe2/caffe2/fb/optimizers:sgd_simd_ops')
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
@st.composite
def _tensor_and_prefix(draw, dtype, elements, min_dim=1, max_dim=4, **kwargs):
dims_ = draw(
st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim))
extra_ = draw(
st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim))
assume(len(dims_) + len(extra_) < max_dim)
return (draw(hu.arrays(dims_ + extra_, dtype, elements)),
draw(hu.arrays(extra_, dtype, elements)))
def _tensor_and_indices(min_dim=1, max_dim=4, dtype=np.float32,
elements=None, **kwargs):
""" generates a tensor and a list of indices of larger tensor of same dim"""
data_dims_ = st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim)
original_dim = st.integers(min_value=2, max_value=10)
return st.tuples(data_dims_, original_dim).flatmap(lambda pair: st.tuples(
st.just(pair[1]), # original dimension
hu.arrays(pair[0], dtype, elements), # data tensor
hu.arrays(pair[0][0], dtype=np.int64, elements=st.integers(
min_value=0, max_value=pair[1] - 1)),
))
_NUMPY_TYPE_TO_ENUM = {
np.float32: core.DataType.FLOAT,
np.int32: core.DataType.INT32,
np.bool: core.DataType.BOOL,
np.uint8: core.DataType.UINT8,
np.int8: core.DataType.INT8,
np.uint16: core.DataType.UINT16,
np.int16: core.DataType.INT16,
np.int64: core.DataType.INT64,
np.float64: core.DataType.DOUBLE,
}
def _dtypes(dtypes=None):
dtypes = dtypes if dtypes else [np.int32, np.int64, np.float32]
return st.sampled_from(dtypes)
def _test_binary(name, ref, filter_=None, gcs=hu.gcs,
test_gradient=False, allow_inplace=False, dtypes=_dtypes):
@given(
inputs=dtypes().flatmap(
lambda dtype: hu.tensors(
n=2, dtype=dtype,
elements=hu.elements_of_type(dtype, filter_=filter_))),
out=st.sampled_from(('Y', 'X1', 'X2') if allow_inplace else ('Y',)),
**gcs)
@settings(max_examples=3, timeout=100)
def test_binary(self, inputs, out, gc, dc):
op = core.CreateOperator(name, ["X1", "X2"], [out])
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
# We only do gradient check with float32 types.
if test_gradient and X1.dtype == np.float32:
self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
self.assertReferenceChecks(gc, op, [X1, X2], ref)
return test_binary
def _test_binary_broadcast(name, ref, filter_=None,
gcs=hu.gcs, allow_inplace=False, dtypes=_dtypes):
@given(
inputs=dtypes().flatmap(lambda dtype: _tensor_and_prefix(
dtype=dtype,
elements=hu.elements_of_type(dtype, filter_=filter_))),
in_place=(st.booleans() if allow_inplace else st.just(False)),
**gcs)
@settings(max_examples=3, timeout=100)
def test_binary_broadcast(self, inputs, in_place, gc, dc):
op = core.CreateOperator(
name, ["X1", "X2"], ["X1" if in_place else "Y"], broadcast=1)
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
def cast_ref(x, y):
return (np.array(ref(x, y)[0], dtype=x.dtype), )
# gradient not implemented yet
# self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
self.assertReferenceChecks(gc, op, [X1, X2], cast_ref)
return test_binary_broadcast
class TestOperators(hu.HypothesisTestCase):
def test_comparison_ops(self):
ops = {"LT": lambda x1, x2: [x1 < x2],
"LE": lambda x1, x2: [x1 <= x2],
"GT": lambda x1, x2: [x1 > x2],
"GE": lambda x1, x2: [x1 >= x2]}
for name, ref in viewitems(ops):
_test_binary(name, ref, gcs=hu.gcs_cpu_only)(self)
_test_binary_broadcast(name, ref, gcs=hu.gcs_cpu_only)(self)
@given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs)
def test_sum(self, inputs, in_place, gc, dc):
op = core.CreateOperator("Sum", ["X1", "X2"],
["Y" if not in_place else "X1"])
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
@given(inputs=hu.tensors(n=2, min_dim=2, max_dim=2), **hu.gcs_cpu_only)
def test_row_mul(self, inputs, gc, dc):
op = core.CreateOperator("RowMul", ["X1", "X2"], ["Y"])
X1, Xtmp = inputs
X2 = Xtmp[:, 0]
def ref(x, y):
ret = np.zeros(shape=x.shape, dtype=x.dtype)
for i in range(y.size):
ret[i, ] = x[i, ] * y[i]
return [ret]
self.assertDeviceChecks(dc, op, [X1, X2], [0])
for i in range(2):
self.assertGradientChecks(gc, op, [X1, X2], i, [0])
self.assertReferenceChecks(gc, op, [X1, X2], ref)
@given(inputs=hu.tensors(n=2), **hu.gcs_cpu_only)
def test_max(self, inputs, gc, dc):
op = core.CreateOperator("Max", ["X1", "X2"], ["Y"])
X1, X2 = inputs
# Make X1 and X2 far from each other, since X1=X2 is not differentiable
# and the step size of gradient checker is 0.05
X1[np.logical_and(X1 >= X2 - 0.05, X1 <= X2)] -= 0.05
X1[np.logical_and(X1 <= X2 + 0.05, X1 >= X2)] += 0.05
self.assertDeviceChecks(dc, op, [X1, X2], [0])
for i in range(2):
self.assertGradientChecks(gc, op, [X1, X2], i, [0])
def elementwise_max(X, Y):
return [np.maximum(X, Y)]
self.assertReferenceChecks(gc, op, [X1, X2], elementwise_max)
def test_add(self):
def not_overflow(x):
if not isinstance(x, float):
return abs(x) < (1 << 30) - 1
return True
def ref(x, y):
return (x + y, )
_test_binary("Add", ref, filter_=not_overflow, test_gradient=True)(self)
_test_binary_broadcast("Add", ref, filter_=not_overflow)(self)
def test_sub(self):
def ref(x, y):
return (x - y, )
# TODO(jiayq): enable gradient test when implemented.
_test_binary("Sub", ref, test_gradient=True)(self)
_test_binary_broadcast("Sub", ref)(self)
def test_mul(self):
def not_overflow(x):
if not isinstance(x, float):
return abs(x) < (1 << 15) - 1
return True
def ref(x, y):
return (x * y, )
_test_binary("Mul", ref, filter_=not_overflow, test_gradient=True)(self)
_test_binary_broadcast("Mul", ref, filter_=not_overflow)(self)
def test_div(self):
def ref(x, y):
return (x / y, )
def non_zero(x):
return abs(x) > 1e-2
def div_dtypes():
return st.sampled_from([np.float32, np.float64])
_test_binary(
"Div", ref, filter_=non_zero, test_gradient=True,
dtypes=div_dtypes, gcs=hu.gcs_cpu_only
)(self)
_test_binary(
"Div", ref, filter_=non_zero, test_gradient=False,
dtypes=div_dtypes
)(self)
_test_binary_broadcast(
"Div", ref, filter_=non_zero, dtypes=div_dtypes)(self)
@given(X=hu.tensor(), in_place=st.booleans(), **hu.gcs)
def test_negative(self, X, in_place, gc, dc):
op = core.CreateOperator("Negative", ["X"],
["Y" if not in_place else "X"])
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(), **hu.gcs)
def test_tanh(self, X, gc, dc):
op = core.CreateOperator("Tanh", "X", "Y")
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(), **hu.gcs)
def test_averaged_loss(self, X, gc, dc):
op = core.CreateOperator("AveragedLoss", ["X"], ["loss"])
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs)
def test_softsign(self, X, inplace, gc, dc):
op = core.CreateOperator("Softsign", ["X"], ["X" if inplace else "Y"])
def softsign(X):
return (X / (1 + np.abs(X)),)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertReferenceChecks(gc, op, [X], softsign)
if inplace:
with self.assertRaises(Exception):
self.assertGradientChecks(gc, op, [X], 0, [0])
else:
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(
device_options=st.lists(
min_size=2,
max_size=4,
elements=st.sampled_from(hu.expanded_device_options)),
set_seed=st.booleans())
def test_random_seed_behaviour(self, device_options, set_seed):
# Assume we are always operating on CUDA or CPU, since RNG is
# inconsistent between CPU and GPU.
device_options = copy.deepcopy(device_options)
assume(len({do.device_type for do in device_options}) == 1)
if set_seed:
for do in device_options:
do.random_seed = 1000
def run(do):
# Reset each time because 'Y' may already exist in the workspace
# on a different device
workspace.ResetWorkspace()
ws = workspace.C.Workspace()
op = core.CreateOperator(
"XavierFill", [], ["Y"],
device_option=do,
shape=[2])
ws.run(op)
return ws.blobs["Y"].fetch()
ys = [run(do) for do in device_options]
for y in ys[1:]:
if set_seed:
np.testing.assert_array_equal(ys[0], y)
else:
with self.assertRaises(AssertionError):
np.testing.assert_array_equal(ys[0], y)
@given(axis=st.integers(min_value=1, max_value=4),
num_output=st.integers(min_value=4, max_value=8),
engine=st.sampled_from(["", "PACKED"]),
**hu.gcs)
def test_fully_connected_axis(self, axis, num_output, engine, gc, dc):
np.random.seed(1)
X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32)
def prod(xs):
p = 1
for x in xs:
p *= x
return p
K = prod(list(X.shape)[axis:])
N = num_output
W = np.random.randn(N, K).astype(np.float32)
b = np.random.randn(N).astype(np.float32)
op = core.CreateOperator(
"FC",
["X", "W", "b"],
["Y"],
engine=engine,
axis=axis)
for name, param in [("X", X), ("W", W), ("b", b)]:
self.ws.create_blob(name).feed(param)
self.ws.run(op)
Y = self.ws.blobs["Y"].fetch()
self.assertEqual(list(Y.shape), list(X.shape)[:axis] + [N])
inputs = [X, W, b]
self.assertDeviceChecks(dc, op, inputs, [0])
for param, _ in enumerate(inputs):
self.assertGradientChecks(gc, op, inputs, param, [0])
@unittest.skipIf(not workspace.has_gpu_support,
"Skipping test due to no gpu present.")
@given(hidden_size=st.integers(min_value=1, max_value=3),
num_layers=st.integers(min_value=1, max_value=3),
bidirectional=st.just(False), # TODO
rnn_mode=st.sampled_from(["lstm"]), # TODO: "gru"
input_mode=st.sampled_from(["linear"]),
dropout=st.floats(min_value=1.0, max_value=1.0),
T=st.integers(min_value=2, max_value=6),
N=st.integers(min_value=1, max_value=4),
D=st.integers(min_value=1, max_value=4))
def test_recurrent(self, hidden_size, num_layers, bidirectional, rnn_mode,
input_mode, dropout, T, N, D):
# Random seed, this one happens to pass
seed = 1234
np.random.seed(seed)
input_weight_size = hidden_size * D
upper_layer_input_weight_size = hidden_size * hidden_size
recurrent_weight_size = hidden_size * hidden_size
input_bias_size = hidden_size
recurrent_bias_size = hidden_size
num_directions = 2 if bidirectional else 1
first_layer_sz = input_weight_size + recurrent_weight_size + \
input_bias_size + recurrent_bias_size
upper_layer_sz = upper_layer_input_weight_size + \
recurrent_weight_size + input_bias_size + \
recurrent_bias_size
total_sz = 4 * (first_layer_sz + (num_layers - 1) * upper_layer_sz)
total_sz *= num_directions
W = np.random.rand(total_sz).astype(np.float32)
self.ws.create_blob("WEIGHT").feed(W, device_option=hu.gpu_do)
op = core.CreateOperator(
"Recurrent",
["INPUT", "HIDDEN_INPUT", "CELL_INPUT", "WEIGHT"],
["OUTPUT", "HIDDEN_OUTPUT", "CELL_OUTPUT",
"RNN_SCRATCH", "DROPOUT_STATES"],
hidden_size=hidden_size,
bidirectional=bidirectional,
rnn_mode=rnn_mode,
dropout=dropout,
input_mode=input_mode,
num_layers=num_layers,
seed=seed,
engine="CUDNN")
X = np.random.randn(T, N, D).astype(np.float32)
self.ws.create_blob("INPUT").feed(X, device_option=hu.gpu_do)
W = self.ws.blobs["WEIGHT"].fetch()
H = np.random.randn(
num_layers, N, hidden_size * num_directions).astype(
np.float32)
C = np.random.randn(
num_layers, N, hidden_size * num_directions).astype(
np.float32) if rnn_mode == "lstm" else \
np.empty((1,)).astype(np.float32) # unused in GRU
inputs = [X, H, C, W]
input_idxs = [i for (i, _) in enumerate(inputs)] \
if rnn_mode == "lstm" else [0, 1, 3] # ignore C
for input_idx in input_idxs:
self.assertGradientChecks(
hu.gpu_do, op, inputs, input_idx, [0],
stepsize=0.01, threshold=0.01)
@given(ndim=st.integers(1, 4),
axis=st.integers(0, 3),
add_axis=st.integers(0, 1),
num_inputs=st.integers(2, 4), **hu.gcs)
def test_depth_concat(self, ndim, axis, add_axis, num_inputs, gc, dc):
assume(axis < ndim)
input_names = ['X0', 'X1', 'X2', 'X3'][:num_inputs]
shape = [2, 3, 5, 7][:ndim]
individual_dims = [1, 2, 3, 4, 5][:num_inputs]
inputs = []
for i in range(num_inputs):
if add_axis == 0:
# Sets a unique dim and create the input.
shape[axis] = individual_dims[i]
inputs.append(np.random.randn(*shape).astype(np.float32))
op = core.CreateOperator("Concat", input_names, ["Y", "Y_dims"],
axis=axis, add_axis=add_axis)
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(num_inputs):
self.assertGradientChecks(gc, op, inputs, i, [0])
# Reference
def depth_concat(*inputs):
inputs = list(inputs)
if add_axis:
for i in range(len(inputs)):
inputs[i] = np.expand_dims(inputs[i], axis)
input_dims = np.array([np.shape(x)[axis] for x in inputs])
return [np.concatenate(inputs, axis=axis), input_dims]
self.assertReferenceChecks(gc, op, inputs, depth_concat)
@given(num_inputs=st.integers(2, 4),
order=st.sampled_from([("NCHW", 1), ("NHWC", 3)]),
**hu.gcs)
def test_depth_concat_with_order(self, num_inputs, order, gc, dc):
input_names = ['X0', 'X1', 'X2', 'X3'][:num_inputs]
shape = [2, 3, 5, 7]
individual_dims = [1, 2, 3, 4][:num_inputs]
inputs = []
for i in range(num_inputs):
# Sets a unique dim and create the input.
shape[order[1]] = individual_dims[i]
inputs.append(np.random.rand(*shape).astype(np.float32))
op = core.CreateOperator("Concat", input_names, ["Y", "Y_dims"],
order=order[0])
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(num_inputs):
self.assertGradientChecks(gc, op, inputs, i, [0])
# Reference
def depth_concat_with_order(*inputs):
inputs = list(inputs)
axis = order[1]
input_dims = np.array([np.shape(x)[axis] for x in inputs])
return [np.concatenate(inputs, axis=axis), input_dims]
self.assertReferenceChecks(gc, op, inputs, depth_concat_with_order)
@given(X=hu.arrays(dims=[5, 2],
elements=st.floats(min_value=1.0, max_value=10.0)),
**hu.gcs_cpu_only)
def test_last_n_windows(self, X, gc, dc):
workspace.FeedBlob('input', X)
workspace.FeedBlob('next', np.array(0, dtype=np.int32))
workspace.CreateBlob('output')
collect_net = core.Net('collect_net')
collect_net.LastNWindowCollector(
['output', 'next', 'input'],
['output', 'next'],
num_to_collect=7,
)
plan = core.Plan('collect_data')
plan.AddStep(core.execution_step('collect_data',
[collect_net], num_iter=2))
workspace.RunPlan(plan)
output = workspace.FetchBlob('output')
inputs = workspace.FetchBlob('input')
new_output = np.zeros([7, inputs.shape[1]])
for i in range(inputs.shape[0] * 2):
new_output[i % 7] = inputs[i % inputs.shape[0]]
import numpy.testing as npt
npt.assert_almost_equal(output, new_output, decimal=5)
@given(dtype=st.sampled_from([np.float32, np.float64, np.int32, np.bool]))
def test_print(self, dtype):
data = np.random.permutation(6).astype(dtype)
self.ws.create_blob("data").feed(data)
op = core.CreateOperator("Print", "data", [])
self.ws.run(op)
@given(inputs=hu.tensors(n=2),
in_place=st.booleans(),
momentum=st.floats(min_value=0.1, max_value=0.9),
nesterov=st.booleans(),
lr=st.floats(min_value=0.1, max_value=0.9),
**hu.gcs)
def test_momentum_sgd(
self, inputs, in_place, momentum, nesterov, lr, gc, dc):
grad, m = inputs
lr = np.asarray([lr], dtype=np.float32)
op = core.CreateOperator(
"MomentumSGD",
["grad", "m", "lr"],
["grad" if in_place else "grad_o",
"m" if in_place else "m_o"],
momentum=momentum,
nesterov=int(nesterov),
device_option=gc)
self.assertDeviceChecks(
dc, op, [grad, m, lr], [0])
# Reference
def momentum_sgd(grad, m, lr):
lr = lr[0]
if not nesterov:
adjusted_gradient = lr * grad + momentum * m
return (adjusted_gradient, adjusted_gradient)
else:
m_new = momentum * m + lr * grad
return ((1 + momentum) * m_new - momentum * m, m_new)
self.assertReferenceChecks(gc, op, [grad, m, lr], momentum_sgd)
@given(inputs=hu.tensors(n=3),
in_place=st.booleans(),
decay=st.floats(min_value=0.1, max_value=0.9),
momentum=st.floats(min_value=0.1, max_value=0.9),
lr=st.floats(min_value=0.1, max_value=0.9),
epsilon=st.floats(min_value=1e-5, max_value=1e-2),
**hu.gcs)
def test_rmsprop_sgd(self, inputs, in_place, decay, momentum, lr, epsilon,
gc, dc):
grad, ms, mom = inputs
ms = np.abs(ms) + 0.01
lr = np.asarray([lr], dtype=np.float32)
op = core.CreateOperator(
"RmsProp",
["grad", "ms", "mom", "lr"],
["grad" if in_place else "grad_o",
"ms" if in_place else "ms_o",
"mom" if in_place else "mom_o"],
momentum=momentum, decay=decay, epsilon=epsilon, device_option=gc)
self.assertDeviceChecks(dc, op, [grad, ms, mom, lr], [0])
def rmsprop(grad, ms, mom, lr):
lr = lr[0]
ms_o = ms + (1. - decay) * (np.square(grad) - ms)
mom_o = momentum * mom + lr * grad / np.sqrt(epsilon + ms_o)
grad_o = mom_o
return (grad_o, ms_o, mom_o)
self.assertReferenceChecks(gc, op, [grad, ms, mom, lr], rmsprop)
# Reference
@staticmethod
def _dense_ftrl(alpha, beta, lambda1, lambda2, w, nz, g):
if isinstance(alpha, np.ndarray):
alpha = np.asscalar(alpha)
n = np.take(nz, 0, axis=-1)
z = np.take(nz, 1, axis=-1)
# python port of Sigrid's implementation
g2 = g * g
sigma = (np.sqrt(n + g2) - np.sqrt(n)) / alpha
z += g - sigma * w
n += g2
w = (np.sign(z) * lambda1 - z) / (
(beta + np.sqrt(n)) / alpha + lambda2)
w[np.abs(z) <= lambda1] = 0
return (w, np.stack([n, z], axis=-1))
@given(inputs=hu.tensors(n=4),
in_place=st.booleans(),
alpha=st.floats(min_value=0.01, max_value=0.1),
beta=st.floats(min_value=0.1, max_value=0.9),
lambda1=st.floats(min_value=0.001, max_value=0.1),
lambda2=st.floats(min_value=0.001, max_value=0.1),
engine=st.sampled_from([None, "SIMD"]),
**hu.gcs_cpu_only)
def test_ftrl_sgd(self, inputs, in_place, alpha, beta, lambda1, lambda2,
engine, gc, dc):
var, n, z, grad = inputs
n = np.abs(n)
nz = np.stack([n, z], axis=-1)
op = core.CreateOperator(
"Ftrl",
["var", "nz", "grad"],
["var" if in_place else "var_o",
"nz" if in_place else "nz_o"],
alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2,
engine=engine,
device_option=gc)
self.assertDeviceChecks(
dc, op, [var, nz, grad], [0])
self.assertReferenceChecks(
gc, op, [var, nz, grad],
partial(self._dense_ftrl, alpha, beta, lambda1, lambda2))
@given(inputs=hu.tensors(n=4),
alpha=st.floats(min_value=0.01, max_value=0.1),
beta=st.floats(min_value=0.1, max_value=0.9),
lambda1=st.floats(min_value=0.001, max_value=0.1),
lambda2=st.floats(min_value=0.001, max_value=0.1),
engine=st.sampled_from([None, "SIMD"]),
**hu.gcs_cpu_only)
def test_sparse_ftrl_sgd(self, inputs, alpha, beta, lambda1, lambda2,
engine, gc, dc):
var, n, z, grad = inputs
# generate fake subset manually because hypothesis is too complicated :)
indices = np.arange(var.shape[0])
indices = indices[indices % 2 == 0]
grad = grad[indices]
n = np.abs(n)
nz = np.stack([n, z], axis=-1)
op = core.CreateOperator(
"SparseFtrl",
["var", "nz", "indices", "grad"],
["var", "nz"],
alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2,
engine=engine,
device_option=gc)
self.assertDeviceChecks(
dc, op, [var, nz, indices, grad], [0])
# Reference
def ftrl(w, nz, i, g):
sw, snz = self._dense_ftrl(alpha, beta, lambda1, lambda2,
w[i], nz[i], g)
w[i] = sw
nz[i] = snz
return (w, nz)
self.assertReferenceChecks(gc, op, [var, nz, indices, grad], ftrl)
# Reference
@staticmethod
def _dense_ftrl_send_alpha_by_input(beta, lambda1, lambda2, w, nz, g, alpha):
return TestOperators._dense_ftrl(alpha, beta, lambda1, lambda2, w, nz,
g)
@given(inputs=hu.tensors(n=4),
in_place=st.booleans(),
alpha=st.floats(min_value=0.01, max_value=0.1),
beta=st.floats(min_value=0.1, max_value=0.9),
lambda1=st.floats(min_value=0.001, max_value=0.1),
lambda2=st.floats(min_value=0.001, max_value=0.1),
engine=st.sampled_from([None, "SIMD"]),
**hu.gcs_cpu_only)
def test_ftrl_sgd_send_alpha_by_input(self, inputs, in_place, alpha, beta,
lambda1, lambda2, engine, gc, dc):
var, n, z, grad = inputs
n = np.abs(n)
nz = np.stack([n, z], axis=-1)
alpha = np.array(alpha).astype(np.float32)
op = core.CreateOperator(
"Ftrl",
["var", "nz", "grad", "alpha"],
["var" if in_place else "var_o",
"nz" if in_place else "nz_o"],
beta=beta, lambda1=lambda1, lambda2=lambda2,
engine=engine,
device_option=gc)
self.assertDeviceChecks(
dc, op, [var, nz, grad, alpha], [0])
self.assertReferenceChecks(
gc, op, [var, nz, grad, alpha],
partial(self._dense_ftrl_send_alpha_by_input, beta, lambda1, lambda2))
@given(inputs=hu.tensors(n=4),
alpha=st.floats(min_value=0.01, max_value=0.1),
beta=st.floats(min_value=0.1, max_value=0.9),
lambda1=st.floats(min_value=0.001, max_value=0.1),
lambda2=st.floats(min_value=0.001, max_value=0.1),
engine=st.sampled_from([None, "SIMD"]),
**hu.gcs_cpu_only)
def test_sparse_ftrl_sgd_send_alpha_by_input(self, inputs, alpha, beta,
lambda1, lambda2, engine, gc,
dc):
var, n, z, grad = inputs
# generate fake subset manually because hypothesis is too complicated :)
indices = np.arange(var.shape[0])
indices = indices[indices % 2 == 0]
grad = grad[indices]
n = np.abs(n)
nz = np.stack([n, z], axis=-1)
alpha = np.array(alpha).astype(np.float32)
op = core.CreateOperator(
"SparseFtrl",
["var", "nz", "indices", "grad", "alpha"],
["var", "nz"],
beta=beta, lambda1=lambda1, lambda2=lambda2,
engine=engine,
device_option=gc)
self.assertDeviceChecks(
dc, op, [var, nz, indices, grad, alpha], [0])
# Reference
def ftrl(w, nz, i, g, alpha):
sw, snz = self._dense_ftrl_send_alpha_by_input(beta, lambda1,
lambda2, w[i], nz[i],
g, alpha)
w[i] = sw
nz[i] = snz
return (w, nz)
self.assertReferenceChecks(gc, op, [var, nz, indices, grad, alpha],
ftrl)
@given(input=hu.tensor(max_value=20,
max_dim=1,
dtype=np.int32,
elements=st.integers(min_value=0, max_value=10)),
with_remapping=st.booleans(),
**hu.gcs)
def test_unique(self, input, with_remapping, gc, dc):
op = core.CreateOperator(
"Unique",
["input"],
["unique"] + (["remapping"] if with_remapping else []),
device_option=gc)
self.assertDeviceChecks(dc, op, [input], [0])
# Validator
def unique_valid(input, unique, remapping=None):
self.assertEqual(unique.size, len(set(input)))
self.assertEqual(sorted(unique), sorted(set(input)))
if with_remapping:
self.assertEqual(remapping.shape, input.shape)
remapped = [unique[remapping[i]] for i in range(len(input))]
np.testing.assert_array_equal(remapped, input)
self.assertValidationChecks(gc, op, [input], unique_valid)
@given(prediction=hu.arrays(dims=[10, 3],
elements=st.floats(allow_nan=False,
allow_infinity=False,
min_value=0,
max_value=1)),
labels=hu.arrays(dims=[10],
dtype=np.int32,
elements=st.integers(min_value=0,
max_value=3 - 1)),
top_k=st.integers(min_value=1, max_value=3),
**hu.gcs)
def test_accuracy(self, prediction, labels, top_k, gc, dc):
if(top_k > 1):
gc = hu.cpu_do
op = core.CreateOperator(
"Accuracy",
["prediction", "labels"],
["accuracy"],
top_k=top_k,
device_option=gc
)
def op_ref(prediction, labels, top_k):
N = prediction.shape[0]
correct = 0
for i in range(0, len(prediction)):
pred_sorted = sorted(
([item, j] for j, item in enumerate(prediction[i])),
key=lambda x: x[0],
reverse=True
)
max_ids = [x[1] for x in pred_sorted[0:top_k]]
for m in max_ids:
if m == labels[i]:
correct += 1
accuracy = correct / N
return (accuracy,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[prediction, labels, top_k],
reference=op_ref)
@given(target_probabilities=hu.arrays(
dims=[10], elements=st.floats(allow_nan=False,
allow_infinity=False,
min_value=0.01,
max_value=1)),
**hu.gcs)
def test_perplexity(self, target_probabilities, gc, dc):
op = core.CreateOperator(
"Perplexity",
["target_probabilities"],
["perplexity"]
)
def op_ref(target_probabilities):
N = target_probabilities.shape[0]
perplexities = np.power(target_probabilities, -1.0 / N)
perplexity = reduce(lambda x, y: x * y, perplexities)
return (perplexity,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[target_probabilities],
reference=op_ref)
@given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
def test_lengths_to_segment_ids(self, lengths, gc, dc):
op = core.CreateOperator(
"LengthsToSegmentIds",
["lengths"],
["segment_ids"])
def op_ref(lengths):
sids = []
for i, l in enumerate(lengths):
sids.extend(l * [i])
return (np.array(sids, dtype=np.int32), )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(lengths, dtype=np.int32)],
reference=op_ref)
@given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
def test_lengths_range_fill(self, lengths, gc, dc):
op = core.CreateOperator(
"LengthsRangeFill",
["lengths"],
["increasing_seq"])
def op_ref(lengths):
sids = []
for _, l in enumerate(lengths):
sids.extend(list(range(l)))
return (np.array(sids, dtype=np.int32), )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(lengths, dtype=np.int32)],
reference=op_ref)
@given(**hu.gcs_cpu_only)
def test_segment_ids_to_ranges(self, gc, dc):
lengths = [4, 6, 3, 2, 0, 4]
op = core.CreateOperator(
"SegmentIdsToRanges",
["segment_ids"],
["ranges"])
def op_ref(segment_ids):
ranges = [np.array([0, 0], dtype=np.int32)]
prev = 0
for i, sid in enumerate(segment_ids):
while sid != prev:
prev += 1
ranges.append(np.array([i, 0], dtype=np.int32))
ranges[-1][1] += 1
return (np.array(ranges, dtype=np.int32), )
def lengths_to_segment_ids(lengths):
sids = []
for i, l in enumerate(lengths):
sids.extend(l * [i])
return (np.array(sids, dtype=np.int32), )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=np.array(lengths_to_segment_ids(lengths), dtype=np.int32),
reference=op_ref)
@given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
def test_lengths_to_ranges(self, lengths, gc, dc):
op = core.CreateOperator(
"LengthsToRanges",
["lengths"],
["ranges"])
def op_ref(x):
if not x.size:
return (x.reshape((0, 2)), )
return (np.column_stack((np.concatenate(([0], np.cumsum(x)[:-1])),
x)), )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(lengths, dtype=np.int32)],
reference=op_ref)
@given(prediction=hu.arrays(dims=[10, 3],
elements=st.floats(allow_nan=False,
allow_infinity=False,
min_value=0,
max_value=1)),
labels=hu.arrays(dims=[10],
dtype=np.int32,
elements=st.integers(min_value=0,
max_value=3 - 1)),
**hu.gcs)
def test_multi_class_accuracy(self, prediction, labels, gc, dc):
op = core.CreateOperator(
"MultiClassAccuracy",
["prediction", "labels"],
["accuracies", "amounts"]
)
def op_ref(prediction, labels):
N = prediction.shape[0]
D = prediction.shape[1]
accuracies = np.empty(D, dtype=float)
accuracies.fill(0)
amounts = np.empty(D, dtype=int)
amounts.fill(0)
max_ids = np.argmax(prediction, axis=1)
for i in range(0, N):
max_id = max_ids[i]
label_id = labels[i]
if max_id == label_id:
accuracies[label_id] += 1
amounts[label_id] += 1
for i in range(0, D):
amount = amounts[i]
if amount:
accuracies[i] /= amount
return (accuracies, amounts,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[prediction, labels],
reference=op_ref)
@given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
def test_segment_ids_to_lengths(self, lengths, gc, dc):
op = core.CreateOperator(
"SegmentIdsToLengths",
["segment_ids"],
["lengths"])
def lengths_to_ids(lengths):
sids = []
for i, l in enumerate(lengths):
sids.extend(l * [i])
return sids
segment_ids = lengths_to_ids(lengths)
def ids_to_lengths(ids):
ids_length = len(ids)
if ids_length == 0:
return (np.array([], dtype=np.int32),)
lengths = []
# segment id starts with 0
prev_id = -1
tmp_length = 0
for idx in range(ids_length):
cur_id = ids[idx]
if cur_id != prev_id:
if idx != 0:
lengths.append(tmp_length)
while prev_id + 1 != cur_id:
lengths.append(0)
prev_id += 1
prev_id = cur_id
tmp_length = 0
tmp_length += 1
lengths.append(tmp_length)
return (np.array(lengths, dtype=np.int32),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(segment_ids, dtype=np.int32)],
reference=ids_to_lengths)
@given(lengths=st.lists(st.integers(min_value=1, max_value=10),
min_size=0,
max_size=10),
power=st.sampled_from([0.5, 1.0, 1.5, 2.0]),
**hu.gcs_cpu_only)
def test_lengths_to_weights(self, lengths, power, gc, dc):
op = core.CreateOperator(
"LengthsToWeights",
["lengths"],
["weights"],
power=power)
def lengths_to_weights(lengths):
weighted_length = []
for l in lengths:
weighted_length.extend(l * [1 / pow(l, power)])
return (np.array(weighted_length, dtype=float),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(lengths, dtype=np.int32)],
reference=lengths_to_weights)
@given(input_tensor=hu.arrays(
dims=[10], elements=st.floats(allow_nan=False,
allow_infinity=False)),
**hu.gcs)
def test_abs(self, input_tensor, gc, dc):
op = core.CreateOperator(
"Abs",
["input"],
["output"]
)
def abs_ref(input_tensor):
return (np.abs(input_tensor),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_tensor],
reference=abs_ref)
@given(input_tensor=hu.arrays(
dims=[10], elements=st.floats(min_value=-10,
max_value=10)),
**hu.gcs)
def test_cos(self, input_tensor, gc, dc):
op = core.CreateOperator(
"Cos",
["input"],
["output"]
)
def cos_ref(input_tensor):
return (np.cos(input_tensor),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_tensor],
reference=cos_ref)
@given(input_tensor=hu.arrays(
dims=[10], elements=st.floats(min_value=-10,
max_value=10)),
**hu.gcs)
def test_sin(self, input_tensor, gc, dc):
op = core.CreateOperator(
"Sin",
["input"],
["output"]
)
def sin_ref(input_tensor):
return (np.sin(input_tensor),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_tensor],
reference=sin_ref)
@given(input_tensor=hu.arrays(
dims=[10], elements=st.floats(allow_nan=False,
allow_infinity=False)),
**hu.gcs)
def test_exp(self, input_tensor, gc, dc):
op = core.CreateOperator(
"Exp",
["input"],
["output"]
)
def exp_ref(input_tensor):
return (np.exp(input_tensor),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_tensor],
reference=exp_ref)
@given(input_tensor=hu.arrays(
dims=[10], elements=st.floats(min_value=1,
max_value=10000)),
**hu.gcs_cpu_only)
def test_log(self, input_tensor, gc, dc):
op = core.CreateOperator(
"Log",
["input"],
["output"]
)
def log_ref(input_tensor):
return (np.log(input_tensor),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_tensor],
reference=log_ref)
self.assertGradientChecks(gc, op, [input_tensor], 0, [0])
def test_blobs_dequeue_timeout(self):
op = core.CreateOperator(
"CreateBlobsQueue",
[],
["queue"],
capacity=5,
num_blobs=1)
self.ws.run(op)
t = time.time()
op = core.CreateOperator(
"DequeueBlobs",
["queue"],
["out"],
timeout_secs=0.2)
self.assertRaises(RuntimeError, lambda: self.ws.run(op))
t = time.time() - t
self.assertGreater(t, 0.19)
@given(num_threads=st.integers(1, 10), # noqa
num_elements=st.integers(1, 100),
capacity=st.integers(1, 5),
num_blobs=st.integers(1, 3),
do=st.sampled_from(hu.device_options))
def test_blobs_queue_threading(self, num_threads, num_elements,
capacity, num_blobs, do):
"""
- Construct matrices of size N x D
- Start K threads
- Push all N rows into the queue of capacity C
- Pull all N rows out of the queue.
- Verify that the output matrices are permutation of the rows of the
original matrices.
"""
import threading
try:
import queue
except ImportError:
# Py3
import Queue as queue
op = core.CreateOperator(
"CreateBlobsQueue",
[],
["queue"],
capacity=capacity,
num_blobs=num_blobs,
device_option=do)
self.ws.run(op)
xs = [np.random.randn(num_elements, 5).astype(np.float32)
for _ in range(num_blobs)]
q = queue.Queue()
for i in range(num_elements):
q.put([x[i] for x in xs])
def enqueue(t):
while True:
feed_blobs = ["x_{}_{}".format(i, t) for i in range(num_blobs)]
op = core.CreateOperator(
"EnqueueBlobs",
["queue"] + feed_blobs,
feed_blobs,
device_option=do)
try:
elems = q.get_nowait()
for elem, feed_blob in zip(elems, feed_blobs):
self.ws.create_blob(feed_blob).feed(
elem, device_option=do)
self.ws.run(op)
except queue.Empty:
return
# Create all blobs before racing on multiple threads
# (blob creation is not threadsafe)
for t in range(num_threads):
for i in range(num_blobs):
self.ws.create_blob("x_{}_{}".format(i, t))
threads = [threading.Thread(target=enqueue, args=(t,))
for t in range(num_threads)]
for thread in threads:
thread.start()
for n in range(num_elements):
dequeue_blobs = ["y_{}_{}".format(i, n) for i in range(num_blobs)]
op = core.CreateOperator(
"DequeueBlobs",
["queue"],
dequeue_blobs,
device_option=do)
self.ws.run(op)
for thread in threads:
thread.join()
op = core.CreateOperator("CloseBlobsQueue", ["queue"], [])
self.ws.run(op)
ys = [np.vstack([self.ws.blobs["y_{}_{}".format(i, n)].fetch()
for n in range(num_elements)])
for i in range(num_blobs)]
for i in range(num_blobs):
self.assertEqual(ys[i].shape, xs[i].shape)
for j in range(num_elements):
# Verify that the rows of the returned blob are a
# permutation. The order may be different due to
# different threads racing.
self.assertTrue(
any(np.array_equal(xs[i][j], ys[i][k])
for k in range(num_elements)))
@given(num_producers=st.integers(1, 10),
num_consumers=st.integers(1, 10),
capacity=st.integers(1, 5),
num_blobs=st.integers(1, 3),
do=st.sampled_from(hu.device_options))
def test_safe_blobs_queue(self, num_producers, num_consumers,
capacity, num_blobs, do):
init_net = core.Net('init_net')
queue = init_net.CreateBlobsQueue(
[], 1, capacity=capacity, num_blobs=num_blobs)
producer_steps = []
truth = 0
for i in range(num_producers):
name = 'producer_%d' % i
net = core.Net(name)
blobs = [net.ConstantFill([], 1, value=1.0, run_once=False)
for times in range(num_blobs)]
status = net.NextName()
net.SafeEnqueueBlobs([queue] + blobs, blobs + [status])
count = (i + 1) * 10
step = core.execution_step(name, net, num_iter=count)
truth += count
producer_steps.append(step)
producer_exit_net = core.Net('producer_exit_net')
producer_exit_net.CloseBlobsQueue([queue], 0)
producer_step = core.execution_step('producer', [
core.execution_step(
'producers', producer_steps, concurrent_substeps=True),
core.execution_step('producer_exit', producer_exit_net)]
)
consumer_steps = []
counters = []
const_1 = init_net.ConstantFill([], 1, value=1.0)
for i in range(num_consumers):
name = 'consumer_%d' % i
net1 = core.Net(name)
blobs = net1.SafeDequeueBlobs([queue], num_blobs + 1)
status = blobs[-1]
net2 = core.Net(name + '_counter')
counter = init_net.ConstantFill([], 1, value=0.0)
counters.append(counter)
net2.Add([counter, const_1], counter)
consumer_steps.append(core.execution_step(
name, [net1, net2], should_stop_blob=status))
consumer_step = core.execution_step(
'consumer', consumer_steps, concurrent_substeps=True)
init_step = core.execution_step('init', init_net)
worker_step = core.execution_step(
'worker', [consumer_step, producer_step], concurrent_substeps=True)
plan = core.Plan('test')
plan.AddStep(init_step)
plan.AddStep(worker_step)
self.ws.run(plan)
v = 0
for counter in counters:
v += self.ws.blobs[str(counter)].fetch().tolist()
self.assertEqual(v, truth)
@given(num_queues=st.integers(1, 5),
num_iter=st.integers(5, 10),
capacity=st.integers(1, 5),
num_blobs=st.integers(1, 3))
def test_weighted_sample_blobs_queue(
self, num_queues, num_iter, capacity, num_blobs
):
# Create BlobsQueue for each input queue
print("num_queues", num_queues)
init_net = core.Net('init_net')
queues = [
init_net.CreateBlobsQueue(
[], 1, capacity=capacity, num_blobs=num_blobs
) for _ in range(num_queues)
]
# Create multiple producer nets and one producer exist net
producer_steps = []
producer_exit_nets = []
for i in range(num_queues):
name = 'producer_%d' % i
net = core.Net(name)
blobs = [net.ConstantFill([], 1, value=1.0, run_once=False)
for _ in range(num_blobs)]
status = net.NextName()
net.SafeEnqueueBlobs([queues[i]] + blobs, blobs + [status])
exit_net = core.Net('producer_exit_%d' % i)
exit_net.CloseBlobsQueue(queues[i], 0)
producer_exit_nets.append(exit_net)
step = core.execution_step(
name, [
core.execution_step(
'producer_%d' % i, [net], num_iter=num_iter
),
core.execution_step('producer_exit_%d' % i, [exit_net]),
]
)
producer_steps.append(step)
producer_step = core.execution_step(
'producer', [
core.execution_step(
'producers',
producer_steps,
concurrent_substeps=True,
),
]
)
status_lst = []
def append(ins, outs):
status_lst.append(ins)
# Create one consumer dequeue net and one consumer exist net
consumer_net = core.Net('weight_sample_dequeue_net')
table_idx_blob = np.random.randint(low=-1, high=num_blobs, size=1)
blobs = consumer_net.WeightedSampleDequeueBlobs(
queues,
num_blobs + 1,
weights=np.random.uniform(low=0.0, high=1.0, size=(num_queues,)),
table_idx_blob=table_idx_blob[0],
)
status = blobs[-1]
consumer_net.Python(append)(status)
consumer_step = core.execution_step(
'consumer',
[
core.execution_step(
'consumer', [consumer_net], should_stop_blob=status
),
core.execution_step('producer_exit', producer_exit_nets)
]
)
init_step = core.execution_step('init', init_net)
worker_step = core.execution_step(
'worker', [producer_step, consumer_step], concurrent_substeps=True)
plan = core.Plan('test')
plan.AddStep(init_step)
plan.AddStep(worker_step)
self.ws.run(plan)
assert len(status_lst) >= num_iter + 1
assert len(status_lst) <= num_iter * num_queues + 1
@given(
data=hu.tensor(),
**hu.gcs_cpu_only)
def test_squeeze_expand_dims(self, data, gc, dc):
dims = [0, 0]
if len(data.shape) > 2:
dims.append(2)
op = core.CreateOperator(
"ExpandDims",
["data"],
["expanded"],
dims=dims)
def expand_dims_ref(data, *args, **kw):
inc_dims = list(set(dims))
inc_dims.sort()
r = data
for dim in inc_dims:
r = np.expand_dims(r, axis=dim)
return (r, )
def squeeze_ref(data, *args, **kw):
dec_dims = list(set(dims))
dec_dims.sort(reverse=True)
r = data
for dim in dec_dims:
r = np.squeeze(r, axis=dim)
return (r, )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data],
reference=expand_dims_ref,
output_to_grad='expanded',
grad_reference=squeeze_ref)
@given(**hu.gcs_cpu_only)
def test_tt_layer(self, gc, dc):
seed = 1234
np.random.seed(seed)
inp_sizes = [2, 2, 2, 2]
out_sizes = [2, 2, 2, 2]
tt_ranks = [1, 3, 3, 3, 1]
op = core.CreateOperator(
"TT",
["X", "b", "cores"],
["Y"],
inp_sizes=inp_sizes,
out_sizes=out_sizes,
tt_ranks=tt_ranks,
)
X = np.expand_dims(
np.random.rand(16).astype(np.float32), axis=0)
b = np.array([0] * 16).astype(np.float32)
cores = tt_core.init_tt_cores(inp_sizes, out_sizes, tt_ranks)
self.ws.create_blob("X").feed(X)
self.ws.create_blob("b").feed(b)
self.ws.create_blob("cores").feed(cores)
self.ws.run(op)
Y = self.ws.blobs[("Y")].fetch()
Y = Y.reshape([16])
golden = np.array([-9.51763490e-07, -1.28442286e-06,
-2.86281141e-07, 2.28865644e-07,
-1.96180017e-06, -1.78920531e-06,
9.31094666e-07, -2.04273989e-07,
1.70017107e-06, 1.64845711e-06,
-1.06099132e-06, -4.69111137e-07,
6.57552358e-08, -1.28942040e-08,
-2.29114004e-07, -1.04262714e-06])
# This golden array is dependent on the specified inp_sizes, out_sizes,
# tt_ranks, and seed. Changing these will cause the test to fail.
self.assertAlmostEqual(np.linalg.norm(golden - Y), 0, delta=1e-10)
@given(num_workers=st.integers(1, 10),
net_type=st.sampled_from(
["simple", "dag"] +
(["async_dag"] if workspace.has_gpu_support else [])),
do=st.sampled_from(hu.device_options))
def test_dag_net_forking(self, net_type, num_workers, do):
from caffe2.python.model_helper import ModelHelper
from caffe2.python import brew
m = ModelHelper(name="test_model")
n = 10
d = 2
depth = 2
iters = 5
np.random.seed(1701)
# Build a binary tree of FC layers, summing at each node.
for i in reversed(range(depth)):
for j in range(2 ** i):
bottom_1 = "{}_{}".format(i + 1, 2 * j)
bottom_2 = "{}_{}".format(i + 1, 2 * j + 1)
mid_1 = "{}_{}_m".format(i + 1, 2 * j)
mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1)
top = "{}_{}".format(i, j)
brew.fc(
m,
bottom_1, mid_1,
dim_in=d, dim_out=d,
weight_init=('ConstantFill', dict(value=np.random.randn())),
bias_init=('ConstantFill', dict(value=np.random.randn())))
brew.fc(
m,
bottom_2, mid_2,
dim_in=d, dim_out=d,
weight_init=('ConstantFill', dict(value=np.random.randn())),
bias_init=('ConstantFill', dict(value=np.random.randn())))
m.net.Sum([mid_1, mid_2], top)
m.net.SquaredL2Distance(["0_0", "label"], "xent")
m.net.AveragedLoss("xent", "loss")
input_to_grad = m.AddGradientOperators(["loss"])
m.Proto().device_option.CopyFrom(do)
m.param_init_net.Proto().device_option.CopyFrom(do)
m.Proto().type = net_type
m.Proto().num_workers = num_workers
self.ws.run(m.param_init_net)
print(str(m.Proto()))
def run():
import numpy as np
np.random.seed(1701)
input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)]
for input_blob in input_blobs:
self.ws.create_blob(input_blob).feed(
np.random.randn(n, d).astype(np.float32),
device_option=do)
self.ws.create_blob("label").feed(
np.random.randn(n, d).astype(np.float32),
device_option=do)
self.ws.run(m.net)
gradients = [
self.ws.blobs[str(input_to_grad[input_blob])].fetch()
for input_blob in input_blobs]
return gradients
outputs = [run() for _ in range(iters)]
for output in outputs[1:]:
np.testing.assert_array_equal(outputs[0], output)
self.assertAlmostEqual(np.sum(np.square(output)), 91.81752,
delta=1e-2)
@given(input=hu.tensor(min_dim=2, max_dim=6, dtype=np.int32,
elements=st.integers(min_value=0,
max_value=2**32 - 1)),
slice_dim=st.integers(),
a=st.integers(),
b=st.integers(),
is_empty=st.booleans(),
**hu.gcs_cpu_only)
def test_slice(self, input, slice_dim, a, b, is_empty, gc, dc):
slice_dim = slice_dim % len(input.shape)
if (is_empty):
input = np.random.rand(*([0] + list(input.shape))).astype(np.int32)
slice_dim += 1
a = a % input.shape[slice_dim]
b = b % input.shape[slice_dim] + 1
start_vec = np.zeros(len(input.shape), dtype=np.int32)
end_vec = np.ones(len(input.shape), dtype=np.int32) * -1
start_vec[slice_dim] = min(a, b)
end_vec[slice_dim] = max(a, b)
op = core.CreateOperator(
"Slice",
["input", "start", "end"],
["output"])
def slice_ref(x, s, e):
if len(s.shape) == 0:
return x
slc = [slice(si, None if ei == -1 else ei) for si, ei in zip(s, e)]
return (x[slc], )
self.assertReferenceChecks(gc, op, [input, start_vec, end_vec],
slice_ref)
@given(data=hu.tensor(), **hu.gcs_cpu_only)
def test_shape(self, data, gc, dc):
op = core.CreateOperator("Shape", ["data"], ["shape"])
self.assertReferenceChecks(gc, op, [data], lambda x: (x.shape, ))
@given(data=hu.tensor(), **hu.gcs_cpu_only)
def test_has_elements(self, data, gc, dc):
op = core.CreateOperator("HasElements", ["data"], ["has_elements"])
self.assertReferenceChecks(gc, op, [data], lambda x: (len(x) > 0, ))
op = core.CreateOperator("IsEmpty", ["data"], ["is_empty"])
self.assertReferenceChecks(gc, op, [data], lambda x: (len(x) == 0, ))
@given(initial_iters=st.integers(0, 100),
max_iters=st.integers(0, 100))
def test_should_stop_as_criteria_net_execution_step(
self, initial_iters, max_iters):
net = core.Net("net")
net.Iter(["iter"], ["iter"])
self.ws.create_blob("iter").feed(
np.asarray([initial_iters]).astype(np.int64))
self.ws.create_blob("num_iters").feed(
np.asarray([max_iters]).astype(np.int64))
criteria_net = core.Net("criteria")
criteria_net.GE(["iter", "num_iters"], ["stop"])
criteria_net.Proto().external_output.extend(["stop"])
plan = core.Plan('plan')
plan.AddStep(core.execution_step(
'step', [criteria_net, net],
should_stop_blob=core.BlobReference("stop")))
self.ws.run(plan)
iters = self.ws.blobs[("iter")].fetch()
self.assertEqual(iters.dtype, np.int64)
self.assertEqual(iters[0], max(initial_iters, max_iters))
def test_disabled_execution_step(self):
def createNets(i, disabled):
should_stop = 'should_stop_{}'.format(i)
output = 'output_{}'.format(i)
# init content and stop signal
init = core.Net("init_{}".format(i))
init.ConstantFill(
[],
[output],
shape=[1],
value=0.0
)
init.Cast([output], [should_stop], to='bool')
# decide if disabled or not
criterion = core.Net("criterion_{}".format(i))
tmp = criterion.ConstantFill(
[],
shape=[1],
value=1.0 if disabled else 0.0
)
criterion.Cast([tmp], [should_stop], to='bool')
criterion.Proto().external_output.extend([should_stop])
# the body net is just to turn a 0 blob to 1
net = core.Net("net_{}".format(i))
net.ConstantFill(
[],
[output],
shape=[1],
value=1.0
)
# always end the loop
ender = core.Net("ender_{}".format(i))
tmp = ender.ConstantFill(
[],
shape=[1],
value=1.0
)
ender.Cast([tmp], [should_stop], to='bool')
ender.Proto().external_output.extend([should_stop])
return [init, criterion, net, ender]
nets = [createNets(1, False),
createNets(2, True),
createNets(3, False)]
steps = [
core.execution_step(
'step_1', nets[0],
should_stop_blob=core.BlobReference('should_stop_1')),
core.execution_step(
'step_2', nets[1],
should_stop_blob=core.BlobReference('should_stop_2')),
core.execution_step('step_3', nets[2])
]
expected = [1.0, 0.0, 1.0]
plan = core.Plan('plan')
plan.AddStep(core.execution_step('all_steps', steps, num_iter=3))
self.ws.run(plan)
for i, _ in enumerate(nets):
self.assertEqual(
self.ws.blobs['output_{}'.format(i + 1)].fetch()[0],
expected[i])
@given(initial_iters=st.integers(0, 100),
num_iters=st.integers(0, 100))
def test_iter_count_with_execution_step(self, initial_iters, num_iters):
net = core.Net("net")
net.Iter(["iter"], ["iter"])
self.ws.create_blob("iter").feed(
np.asarray([initial_iters]).astype(np.int64))
step = core.ExecutionStep("step", [net])
step.SetIter(num_iters)
plan = core.Plan("plan")
plan.AddStep(step)
self.ws.run(plan)
iters = self.ws.blobs[("iter")].fetch()
self.assertEqual(iters.dtype, np.int64)
self.assertEqual(iters[0], initial_iters + num_iters)
@given(initial_iters=st.integers(0, 100),
num_iters=st.integers(0, 100),
num_nets=st.integers(0, 5))
def test_atomic_iter_with_concurrent_steps(self, initial_iters, num_iters,
num_nets):
init_net = core.Net("init_net")
iter_mutex = init_net.CreateMutex([], ["iter_mutex"])
self.ws.create_blob("iter").feed(
np.asarray([initial_iters]).astype(np.int64))
concurrent_steps = core.ExecutionStep("concurrent_steps",
num_iter=num_iters)
for i in range(num_nets):
net = core.Net("net_{}".format(i))
net.AtomicIter([iter_mutex, "iter"], ["iter"])
step = core.ExecutionStep("step", [net])
concurrent_steps.AddSubstep(step)
concurrent_steps.SetConcurrentSubsteps(True)
plan = core.Plan("plan")
plan.AddStep(concurrent_steps)
stats_net = core.Net("stats_net")
stats_net.StatRegistryExport([], ["stats_key", "stats_val", "stats_ts"])
self.ws.run(init_net)
self.ws.run(plan)
self.ws.run(stats_net)
iters = self.ws.blobs[("iter")].fetch()
self.assertEqual(iters.dtype, np.int64)
self.assertEqual(iters[0], initial_iters + num_iters * num_nets)
if num_iters * num_nets > 0:
stats_key = self.ws.blobs[("stats_key")].fetch()
self.assertEqual(b'atomic_iter/stats/iter/num_iter', stats_key[0])
stat_val = self.ws.blobs[("stats_val")].fetch()
self.assertEqual(num_iters * num_nets, stat_val[0])
@given(a=hu.tensor(),
src=st.sampled_from(list(viewkeys(_NUMPY_TYPE_TO_ENUM))),
dst=st.sampled_from(list(viewkeys(_NUMPY_TYPE_TO_ENUM))),
use_name=st.booleans(),
**hu.gcs)
def test_cast(self, a, src, dst, use_name, gc, dc):
a = a.astype(src)
# Casting from a float type outside the range of the integral
# type is UB.
ftypes = [np.float32, np.float64]
if src in ftypes and dst not in ftypes and dst is not np.bool:
info = np.iinfo(dst)
a = np.clip(a, info.min, info.max)
def ref(data):
return [data.astype(dst)]
to = _NUMPY_TYPE_TO_ENUM[dst]
if use_name:
to = TensorProto.DataType.Name(to).lower()
op = core.CreateOperator('Cast', ["X"], ["Y"], to=to)
self.assertDeviceChecks(dc, op, [a], [0])
out, = self.assertReferenceChecks(gc, op, [a], ref)
self.assertEqual(dst, out.dtype)
@given(a=hu.tensor(),
eps=st.floats(min_value=1e-4, max_value=1e-2),
a_grad=hu.tensor(elements=st.floats(min_value=0.01, max_value=0.99)),
eps_grad=st.floats(min_value=1e-4, max_value=1e-3),
**hu.gcs)
def test_logit(self, a, eps, a_grad, eps_grad, gc, dc):
def ref(data):
data = np.clip(data, eps, 1.0 - eps)
return (np.log(data / (1 - data)), )
# forward testing carried out in the full range of input
# to ensure original test coverage.
# gradient test carried out with reduced input range
# because the sharp increase of the logit curve at 0 and 1
# error increases dramtically when input is close to 0 or 1
# and it will fail the test.
# So we only run gradient test in the range of (0.01, 0.99)
# very occationally, test may fail due to random accumulated error
# reduce test range to (0.02, 0.98) will improve test stability
op = core.CreateOperator('Logit', ["X"], ["Y"], eps=eps)
self.assertDeviceChecks(dc, op, [a], [0])
self.assertReferenceChecks(gc, op, [a], ref)
op_grad = core.CreateOperator('Logit', ["X"], ["Y"], eps=eps_grad)
self.assertGradientChecks(gc, op_grad, [a_grad], 0, [0],
threshold=0.04, stepsize=2e-3)
@given(a=hu.tensor(elements=st.floats(allow_nan=True)),
value=st.floats(min_value=-10, max_value=10),
**hu.gcs)
def test_replace_nan(self, a, value, gc, dc):
def ref(data):
out = np.copy(data)
out[np.isnan(data)] = value
return (out, )
op = core.CreateOperator('ReplaceNaN', ["X"], ["Y"], value=value)
self.assertDeviceChecks(dc, op, [a], [0])
self.assertReferenceChecks(gc, op, [a], ref)
@given(data=_dtypes(dtypes=[np.int32, np.int64, np.float32, np.bool]).
flatmap(lambda dtype: hu.tensor(
min_dim=1, dtype=dtype, elements=hu.elements_of_type(dtype))),
has_input=st.booleans(),
has_extra_shape=st.booleans(),
extra_shape=st.lists(
min_size=1, max_size=5, elements=st.integers(1, 5)),
**hu.gcs)
def test_constant_fill(self, data, has_input, has_extra_shape, extra_shape,
gc, dc):
dtype = data.dtype.type
# in opt mode, np.bool is converted into np.bool_
if data.dtype == np.dtype(np.bool):
dtype = np.bool
value = data.item(0)
gt_shape = data.shape
inputs = [data]
enum_type = _NUMPY_TYPE_TO_ENUM[dtype]
if has_input:
if has_extra_shape:
op = core.CreateOperator('ConstantFill', ["X"], ["Y"],
dtype=enum_type,
extra_shape=extra_shape,
value=value)
gt_shape += tuple(extra_shape)
else:
op = core.CreateOperator('ConstantFill', ["X"], ["Y"],
dtype=enum_type,
value=value)
else:
op = core.CreateOperator('ConstantFill', [], ["Y"],
dtype=enum_type,
value=value,
shape=list(gt_shape))
inputs = []
def ref(inputs=None):
outputs = np.full(shape=gt_shape, fill_value=value, dtype=dtype)
return [outputs]
self.assertDeviceChecks(dc, op, inputs, [0])
out, = self.assertReferenceChecks(gc, op, inputs, ref)
self.assertEqual(dtype, out.dtype)
@given(t=st.integers(1, 5),
n=st.integers(1, 5),
d=st.integers(1, 5))
def test_elman_recurrent_network(self, t, n, d):
from caffe2.python import model_helper, brew
np.random.seed(1701)
step_net = model_helper.ModelHelper(name="Elman")
# TODO: name scope external inputs and outputs
step_net.Proto().external_input.extend(
["input_t", "seq_lengths", "timestep",
"hidden_t_prev", "gates_t_w", "gates_t_b"])
step_net.Proto().type = "simple"
step_net.Proto().external_output.extend(["hidden_t", "gates_t"])
brew.fc(step_net,
"hidden_t_prev", "gates_t", dim_in=d, dim_out=d, axis=2)
step_net.net.Sum(["gates_t", "input_t"], ["gates_t"])
step_net.net.Sigmoid(["gates_t"], ["hidden_t"])
# Initialize params for step net in the parent net
for op in step_net.param_init_net.Proto().op:
workspace.RunOperatorOnce(op)
backward_ops, backward_mapping = core.GradientRegistry.GetBackwardPass(
step_net.Proto().op, {"hidden_t": "hidden_t_grad"})
backward_mapping = {
str(k): str(v) for k, v in viewitems(backward_mapping)
}
backward_step_net = core.Net("ElmanBackward")
del backward_step_net.Proto().op[:]
backward_step_net.Proto().op.extend(backward_ops)
assert backward_mapping["input_t"] == "gates_t_grad"
links = [
("hidden_t_prev", "hidden", 0),
("hidden_t", "hidden", 1),
("input_t", "input", 0),
]
link_internal, link_external, link_offset = zip(*links)
backward_links = [
("hidden_t_prev_grad", "hidden_grad", 0),
("hidden_t_grad", "hidden_grad", 1),
("gates_t_grad", "input_grad", 0),
]
backward_link_internal, backward_link_external, backward_link_offset = \
zip(*backward_links)
backward_step_net.Proto().external_input.extend(["hidden_t_grad"])
backward_step_net.Proto().external_input.extend(
step_net.Proto().external_input)
backward_step_net.Proto().external_input.extend(
step_net.Proto().external_output)
inputs = ["input", "seq_lengths", "gates_t_w", "gates_t_b", "hidden_input"]
recurrent_inputs = ["hidden_input"]
op = core.CreateOperator(
"RecurrentNetwork",
inputs,
["output", "hidden", "hidden_output", "step_workspaces"],
alias_src=["hidden", "hidden"],
alias_dst=["output", "hidden_output"],
alias_offset=[1, -1],
recurrent_states=["hidden"],
initial_recurrent_state_ids=[
inputs.index(i) for i in recurrent_inputs
],
link_internal=link_internal,
link_external=link_external,
link_offset=link_offset,
backward_link_internal=backward_link_internal,
backward_link_external=backward_link_external,
backward_link_offset=backward_link_offset,
param=[inputs.index(p) for p in step_net.params],
step_net=step_net.Proto(),
backward_step_net=backward_step_net.Proto(),
outputs_with_grads=[0],
)
workspace.FeedBlob(
"input", np.random.randn(t, n, d).astype(np.float32))
workspace.FeedBlob(
"hidden_input", np.random.randn(1, n, d).astype(np.float32))
workspace.FeedBlob(
"seq_lengths", np.random.randint(0, t, size=(n,)).astype(np.int32))
def reference(input, seq_lengths, gates_w, gates_b, hidden_input):
T = input.shape[0]
N = input.shape[1]
D = input.shape[2]
hidden = np.zeros(shape=(T + 1, N, D))
assert hidden.shape[0] == T + 1
assert hidden.shape[1] == N
assert hidden.shape[2] == D
hidden[0, :, :] = hidden_input
for t in range(T):
input_t = input[t].reshape(1, N, D)
hidden_t_prev = hidden[t].reshape(1, N, D)
gates = np.dot(hidden_t_prev, gates_w.T)
gates = gates.reshape(1, N, D) + input_t.reshape(1, N, D)
hidden[t + 1] = sigmoid(gates)
return hidden[1:], hidden, hidden[-1].reshape(1, N, D)
self.assertReferenceChecks(
hu.cpu_do,
op,
[workspace.FetchBlob(name)
for name in ["input", "seq_lengths", "gates_t_w", "gates_t_b",
"hidden_input"]],
reference,
outputs_to_check=[0, 1, 2])
for param in [0, 2, 3]:
self.assertGradientChecks(
hu.cpu_do,
op,
[workspace.FetchBlob(name)
for name in ["input", "seq_lengths", "gates_t_w", "gates_t_b",
"hidden_input"]],
param,
[0])
@settings(suppress_health_check=[HealthCheck.filter_too_much])
@given(n=st.integers(1, 5),
c=st.integers(1, 5),
h=st.integers(1, 5),
w=st.integers(1, 5),
pad=st.integers(0, 2),
block_size=st.integers(2, 3),
**hu.gcs)
def test_space_to_batch(self, n, c, h, w, pad, block_size, gc, dc):
assume((h + 2 * pad) % block_size == 0)
assume((w + 2 * pad) % block_size == 0)
X = np.random.randn(n, c, h, w).astype(np.float32)
op = core.CreateOperator("SpaceToBatch", ["X"], ["Y"],
pad=pad, block_size=block_size)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@settings(suppress_health_check=[HealthCheck.filter_too_much])
@given(n=st.integers(1, 5),
c=st.integers(1, 5),
h=st.integers(1, 5),
w=st.integers(1, 5),
pad=st.integers(0, 2),
block_size=st.integers(2, 3),
**hu.gcs)
def test_batch_to_space(self, n, c, h, w, pad, block_size, gc, dc):
assume((h + 2 * pad) % block_size == 0)
assume((w + 2 * pad) % block_size == 0)
X = np.random.randn(
n * block_size * block_size,
c,
(h + 2 * pad) // block_size,
(w + 2 * pad) // block_size).astype(np.float32)
op = core.CreateOperator("BatchToSpace", ["X"], ["Y"],
pad=pad, block_size=block_size)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(),
in_place=st.booleans(),
scale=st.floats(min_value=-2.0, max_value=2.0),
**hu.gcs)
def test_scale(self, X, in_place, scale, gc, dc):
op = core.CreateOperator(
"Scale", ["X"], ["Y" if not in_place else "X"],
scale=scale)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(s=st.text())
def test_string_serde(self, s):
s = s.encode('ascii', 'ignore')
self.ws.create_blob("a").feed(s)
serialized = self.ws.blobs["a"].serialize("a")
self.ws.create_blob("b").deserialize(serialized)
self.assertEqual(s, self.ws.blobs[("a")].fetch())
self.assertEqual(s, self.ws.blobs[("b")].fetch())
@given(pad=st.integers(0, 3),
size=st.integers(1, 10),
input_channels=st.integers(1, 5),
batch_size=st.integers(1, 5),
order=st.sampled_from(["NCHW", "NHWC"]),
mode=st.sampled_from(["constant", "reflect", "edge"]),
**hu.gcs)
def test_same_pad_image(self, pad, size, input_channels, batch_size, order,
mode, gc, dc):
assume(size > pad)
op = core.CreateOperator(
"PadImage",
["X"],
["Y"],
pad=pad,
mode=mode,
order=order,
)
if order == "NHWC":
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
def numpy_pad_ref(x):
return (np.pad(
x, ((0, 0), (pad, pad), (pad, pad), (0, 0)), mode),)
else:
X = np.random.rand(
batch_size, input_channels, size, size).astype(np.float32) - 0.5
def numpy_pad_ref(x):
return (np.pad(
x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), mode),)
self.assertReferenceChecks(gc, op, [X], numpy_pad_ref)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
size=st.integers(1, 10),
input_channels=st.integers(1, 5),
batch_size=st.integers(1, 5),
order=st.sampled_from(["NCHW", "NHWC"]),
mode=st.sampled_from(["constant", "reflect", "edge"]),
**hu.gcs)
def test_pad_image(self, pad_t, pad_l, pad_b, pad_r, size, input_channels,
batch_size, order, mode, gc, dc):
assume(size > max(pad_b, pad_r, pad_t, pad_l))
op = core.CreateOperator(
"PadImage",
["X"],
["Y"],
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
mode=mode,
order=order,
)
if order == "NHWC":
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
def numpy_pad_ref(x):
return (np.pad(
x, ((0, 0), (pad_t, pad_b), (pad_l, pad_r), (0, 0)),
mode),)
else:
X = np.random.rand(
batch_size, input_channels, size, size).astype(np.float32) - 0.5
def numpy_pad_ref(x):
return (np.pad(
x, ((0, 0), (0, 0), (pad_t, pad_b), (pad_l, pad_r)),
mode),)
self.assertReferenceChecks(gc, op, [X], numpy_pad_ref)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(size=st.integers(7, 10),
input_channels=st.integers(1, 10),
batch_size=st.integers(1, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
epsilon=st.floats(min_value=1e-4, max_value=1e-2),
**hu.gcs_cpu_only)
def test_instance_norm(self, size, input_channels, batch_size, order,
epsilon, gc, dc):
op = core.CreateOperator(
"InstanceNorm",
["X", "scale", "bias"],
["Y"],
order=order,
epsilon=epsilon,
)
np.random.seed(1701)
scale = np.random.rand(input_channels).astype(np.float32) + 0.5
bias = np.random.rand(input_channels).astype(np.float32) - 0.5
X = np.random.rand(
batch_size, input_channels, size, size).astype(np.float32) - 0.5
if order == "NHWC":
X = X.swapaxes(1, 2).swapaxes(2, 3)
def ref_nchw(x, scale, bias):
x = x.reshape(batch_size * input_channels, size * size)
y = (x - x.mean(1)[:, np.newaxis])
y /= np.sqrt(x.var(1) + epsilon)[:, np.newaxis]
y = y.reshape(batch_size, input_channels, size, size)
y = y * scale.reshape(1, input_channels, 1, 1)
y = y + bias.reshape(1, input_channels, 1, 1)
return (y, )
def ref_nhwc(x, scale, bias):
x = x.swapaxes(2, 3).swapaxes(1, 2)
y = ref_nchw(x, scale, bias)[0]
return (y.swapaxes(1, 2).swapaxes(2, 3), )
self.assertReferenceChecks(
gc, op, [X, scale, bias],
ref_nchw if order == "NCHW" else ref_nhwc)
# TODO(jiayq): when there are backward and GPU implementations, enable
# these two.
# self.assertDeviceChecks(dc, op, [X, scale, bias], [0])
# self.assertGradientChecks(gc, op, [X, scale, bias], 0, [0])
ws = workspace.C.Workspace()
feeds = [("X", X), ("scale", scale), ("bias", bias)]
for blob, arr in feeds:
ws.create_blob(blob).feed(arr)
for _ in range(100):
ws.run(op)
for blob, arr in feeds:
np.testing.assert_array_equal(ws.blobs[blob].fetch(), arr)
@given(sizes=st.lists(st.integers(1, 100), min_size=1),
in_place=st.booleans(),
**hu.gcs)
def test_unsafe_coalesce(self, sizes, in_place, gc, dc):
gAlignment = 32
Xs = [np.random.randn(size)
.astype(np.random.choice([np.float32, np.float64, np.uint8]))
for size in sizes]
op = core.CreateOperator(
"UnsafeCoalesce",
["X_{}".format(i) for i, _ in enumerate(sizes)],
[("X_{}" if in_place else "Y_{}").format(i)
for i, _ in enumerate(sizes)] + ["coalesced"])
self.assertDeviceChecks(dc, op, Xs, list(range(len(sizes) + 1)))
def unsafe_coalesce(*xs):
def to_uint8(x):
x_aligned_bytes = ((x.nbytes + gAlignment - 1) // gAlignment) \
* gAlignment
x_aligned = np.zeros(
shape=(x_aligned_bytes // x.dtype.itemsize, ),
dtype=x.dtype)
x_aligned[:x.size] = x
x_cast = np.fromstring(x_aligned.tobytes(), dtype='<u1')
return x_cast
flat = [to_uint8(x) for x in xs]
coalesced = np.concatenate(flat)
return list(xs) + [coalesced]
self.assertReferenceChecks(gc, op, Xs, unsafe_coalesce)
@given(inp=_dtypes().flatmap(lambda dt: _tensor_and_indices(
elements=st.floats(min_value=0, max_value=1), dtype=dt)),
**hu.gcs)
def test_sparse_to_dense(self, inp, gc, dc):
first_dim, X, I = inp
if X.dtype != np.dtype('float32') and gc.device_type == 1:
# Cuda only support 32 bit float
print("Bailout {}".format(X.dtype))
return
if gc.device_type == 1:
# Cuda version only support int32
I = I.astype(np.int32)
# values don't matter
D = np.zeros((first_dim,) + X.shape[1:]).astype(X.dtype)
op = core.CreateOperator("SparseToDense", ["I", "X", "D"], ["Y"])
def sparse_to_dense(I, X, D):
O = np.zeros(D.shape)
for i, p in enumerate(I):
O[p] += X[i]
return [O]
self.assertReferenceChecks(gc, op, [I, X, D], sparse_to_dense)
X = X.astype(np.float32)
self.assertGradientChecks(gc, op, [I, X, D], 1, [0])
@given(inputs=hu.tensors(n=2, min_dim=2, max_dim=2), **hu.gcs_cpu_only)
def test_dot_product(self, inputs, gc, dc):
X, Y = inputs
op = core.CreateOperator("DotProduct", ["X", "Y"], 'out')
def dotproduct(X, Y):
return (np.sum(X * Y, axis=1), )
self.assertReferenceChecks(gc, op, [X, Y], dotproduct)
self.assertDeviceChecks(dc, op, [X, Y], [0])
self.assertGradientChecks(gc, op, [X, Y], 0, [0])
self.assertGradientChecks(gc, op, [X, Y], 1, [0])
@given(N=st.integers(min_value=2, max_value=10),
M=st.integers(min_value=2, max_value=10),
K=st.integers(min_value=2, max_value=10),
pad_value=st.floats(min_value=0.1, max_value=1.0),
**hu.gcs_cpu_only)
def test_dot_product_with_padding(self, N, M, K, pad_value, gc, dc):
X = np.random.rand(N, M).astype(np.float32) - 0.5
Y = np.random.rand(N, K).astype(np.float32) - 0.5
op = core.CreateOperator("DotProductWithPadding", ["X", "Y"], 'out',
pad_value=pad_value)
def dotproduct(X, Y):
Z = np.ones((N, max(M, K))).astype(np.float32) * pad_value
if M < K:
Z[:, :M] = X
return (np.sum(Z * Y, axis=1), )
else:
Z[:, :K] = Y
return (np.sum(Z * X, axis=1), )
self.assertReferenceChecks(gc, op, [X, Y], dotproduct)
self.assertDeviceChecks(dc, op, [X, Y], [0])
self.assertGradientChecks(gc, op, [X, Y], 0, [0])
self.assertGradientChecks(gc, op, [X, Y], 1, [0])
@given(N=st.integers(min_value=2, max_value=10),
M=st.integers(min_value=2, max_value=10),
pad_value=st.floats(min_value=0.1, max_value=1.0),
**hu.gcs_cpu_only)
def test_dot_product_with_rep_padding(self, N, M, pad_value, gc, dc):
K = 2 * M
X = np.random.rand(N, M).astype(np.float32) - 0.5
Y = np.random.rand(N, K).astype(np.float32) - 0.5
op = core.CreateOperator("DotProductWithPadding", ["X", "Y"], 'out',
replicate=True,
pad_value=pad_value)
def dotproduct(X, Y):
import numpy.matlib as npm
if M < K:
Z = npm.repmat(X, 1, K // M)
return (np.sum(Z * Y, axis=1), )
else:
Z = npm.repmat(Y, 1, M // K)
return (np.sum(Z * X, axis=1), )
self.assertReferenceChecks(gc, op, [X, Y], dotproduct)
self.assertDeviceChecks(dc, op, [X, Y], [0])
self.assertGradientChecks(gc, op, [X, Y], 0, [0])
self.assertGradientChecks(gc, op, [X, Y], 1, [0])
@given(N=st.integers(min_value=2, max_value=10),
M=st.integers(min_value=2, max_value=10), **hu.gcs_cpu_only)
def test_ensure_dense(self, N, M, gc, dc):
# in place
X = np.random.rand(N, M).astype(np.float32) - 0.5
op = core.CreateOperator("EnsureDense", ["X"], "X")
self.assertReferenceChecks(gc, op, [X], lambda x: [x])
self.assertDeviceChecks(dc, op, [X], [0])
# or not
X = np.random.rand(N, M).astype(np.float32) - 0.5
op = core.CreateOperator("EnsureDense", ["X"], "out")
self.assertReferenceChecks(gc, op, [X], lambda x: [x])
self.assertDeviceChecks(dc, op, [X], [0])
@given(N=st.integers(min_value=10, max_value=100),
M=st.integers(min_value=2, max_value=10),
num_buckets=st.integers(min_value=1, max_value=5),
**hu.gcs_cpu_only)
def test_accumulate_histogram_op(self, N, M, num_buckets, gc, dc):
X = np.random.rand(N, M).astype(np.float32)
lower_bound, upper_bound = 0.1, 0.9
op = core.CreateOperator("AccumulateHistogram", ["X"],
['cur_hist', 'acc_hist'],
lower_bound=lower_bound,
upper_bound=upper_bound,
num_buckets=num_buckets)
def histogram(X):
hist = np.zeros((num_buckets + 2, ), dtype=np.int32)
segment = (upper_bound - lower_bound) / num_buckets
Y = np.zeros((N, M), dtype=np.int32)
Y[X < lower_bound] = 0
Y[X >= upper_bound] = num_buckets + 1
Y[(X >= lower_bound) & (X < upper_bound)] = \
((X[(X >= lower_bound) & (X < upper_bound)] - lower_bound) /
segment + 1).astype(np.int32)
for i in range(Y.shape[0]):
for j in range(Y.shape[1]):
hist[Y[i][j]] += 1
cur_hist, acc_hist = hist, hist
return [cur_hist, acc_hist]
self.assertDeviceChecks(dc, op, [X], [0, 1])
self.assertReferenceChecks(gc, op, [X], histogram)
if __name__ == "__main__":
unittest.main()
|
## @package visualize
# Module caffe2.python.visualize
"""Functions that could be used to visualize Tensors.
This is adapted from the old-time iceberk package that Yangqing wrote... Oh gold
memories. Before decaf and caffe. Why iceberk? Because I was at Berkeley,
bears are vegetarian, and iceberg lettuce has layers of leaves.
(This joke is so lame.)
"""
import numpy as np
from matplotlib import cm, pyplot
def ChannelFirst(arr):
"""Convert a HWC array to CHW."""
ndim = arr.ndim
return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
def ChannelLast(arr):
"""Convert a CHW array to HWC."""
ndim = arr.ndim
return arr.swapaxes(ndim - 3, ndim - 2).swapaxes(ndim - 2, ndim - 1)
class PatchVisualizer(object):
"""PatchVisualizer visualizes patches.
"""
def __init__(self, gap=1):
self.gap = gap
def ShowSingle(self, patch, cmap=None):
"""Visualizes one single patch.
The input patch could be a vector (in which case we try to infer the shape
of the patch), a 2-D matrix, or a 3-D matrix whose 3rd dimension has 3
channels.
"""
if len(patch.shape) == 1:
patch = patch.reshape(self.get_patch_shape(patch))
elif len(patch.shape) > 2 and patch.shape[2] != 3:
raise ValueError("The input patch shape isn't correct.")
# determine color
if len(patch.shape) == 2 and cmap is None:
cmap = cm.gray
pyplot.imshow(patch, cmap=cmap)
return patch
def ShowMultiple(self, patches, ncols=None, cmap=None, bg_func=np.mean):
"""Visualize multiple patches.
In the passed in patches matrix, each row is a patch, in the shape of either
n*n, n*n*1 or n*n*3, either in a flattened format (so patches would be a
2-D array), or a multi-dimensional tensor. We will try our best to figure
out automatically the patch size.
"""
num_patches = patches.shape[0]
if ncols is None:
ncols = int(np.ceil(np.sqrt(num_patches)))
nrows = int(np.ceil(num_patches / float(ncols)))
if len(patches.shape) == 2:
patches = patches.reshape(
(patches.shape[0], ) + self.get_patch_shape(patches[0])
)
patch_size_expand = np.array(patches.shape[1:3]) + self.gap
image_size = patch_size_expand * np.array([nrows, ncols]) - self.gap
if len(patches.shape) == 4:
if patches.shape[3] == 1:
# gray patches
patches = patches.reshape(patches.shape[:-1])
image_shape = tuple(image_size)
if cmap is None:
cmap = cm.gray
elif patches.shape[3] == 3:
# color patches
image_shape = tuple(image_size) + (3, )
else:
raise ValueError("The input patch shape isn't expected.")
else:
image_shape = tuple(image_size)
if cmap is None:
cmap = cm.gray
image = np.ones(image_shape) * bg_func(patches)
for pid in range(num_patches):
row = pid // ncols * patch_size_expand[0]
col = pid % ncols * patch_size_expand[1]
image[row:row+patches.shape[1], col:col+patches.shape[2]] = \
patches[pid]
pyplot.imshow(image, cmap=cmap, interpolation='nearest')
pyplot.axis('off')
return image
def ShowImages(self, patches, *args, **kwargs):
"""Similar to ShowMultiple, but always normalize the values between 0 and 1
for better visualization of image-type data.
"""
patches = patches - np.min(patches)
patches /= np.max(patches) + np.finfo(np.float64).eps
return self.ShowMultiple(patches, *args, **kwargs)
def ShowChannels(self, patch, cmap=None, bg_func=np.mean):
""" This function shows the channels of a patch.
The incoming patch should have shape [w, h, num_channels], and each channel
will be visualized as a separate gray patch.
"""
if len(patch.shape) != 3:
raise ValueError("The input patch shape isn't correct.")
patch_reordered = np.swapaxes(patch.T, 1, 2)
return self.ShowMultiple(patch_reordered, cmap=cmap, bg_func=bg_func)
def get_patch_shape(self, patch):
"""Gets the shape of a single patch.
Basically it tries to interprete the patch as a square, and also check if it
is in color (3 channels)
"""
edgeLen = np.sqrt(patch.size)
if edgeLen != np.floor(edgeLen):
# we are given color patches
edgeLen = np.sqrt(patch.size / 3.)
if edgeLen != np.floor(edgeLen):
raise ValueError("I can't figure out the patch shape.")
return (edgeLen, edgeLen, 3)
else:
edgeLen = int(edgeLen)
return (edgeLen, edgeLen)
_default_visualizer = PatchVisualizer()
"""Utility functions that directly point to functions in the default visualizer.
These functions don't return anything, so you won't see annoying printouts of
the visualized images. If you want to save the images for example, you should
explicitly instantiate a patch visualizer, and call those functions.
"""
class NHWC(object):
@staticmethod
def ShowSingle(*args, **kwargs):
_default_visualizer.ShowSingle(*args, **kwargs)
@staticmethod
def ShowMultiple(*args, **kwargs):
_default_visualizer.ShowMultiple(*args, **kwargs)
@staticmethod
def ShowImages(*args, **kwargs):
_default_visualizer.ShowImages(*args, **kwargs)
@staticmethod
def ShowChannels(*args, **kwargs):
_default_visualizer.ShowChannels(*args, **kwargs)
class NCHW(object):
@staticmethod
def ShowSingle(patch, *args, **kwargs):
_default_visualizer.ShowSingle(ChannelLast(patch), *args, **kwargs)
@staticmethod
def ShowMultiple(patch, *args, **kwargs):
_default_visualizer.ShowMultiple(ChannelLast(patch), *args, **kwargs)
@staticmethod
def ShowImages(patch, *args, **kwargs):
_default_visualizer.ShowImages(ChannelLast(patch), *args, **kwargs)
@staticmethod
def ShowChannels(patch, *args, **kwargs):
_default_visualizer.ShowChannels(ChannelLast(patch), *args, **kwargs)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python.schema import Struct, ConstRecord
from caffe2.python import core, workspace, model_helper
from caffe2.python.session import LocalSession
from caffe2.python.dataset import Dataset
from caffe2.python.pipeline import pipe
from caffe2.python.checkpoint import (
CheckpointManager, MultiNodeCheckpointManager, Job, JobRunner, epoch_limiter,
UploadTaskGroupBuilder, db_name)
from caffe2.python.net_builder import ops
from caffe2.python.task import Node, Task, TaskGroup, WorkspaceType, Cluster
from caffe2.python.test_util import TestCase
from caffe2.python.dataio import ReaderWithLimit
import numpy as np
import os
import shutil
import tempfile
def build_pipeline(node_id):
with Node('trainer_%d' % node_id):
with Job.current().init_group, Task():
data_arr = Struct(('val', np.array(list(range(10)))))
data = ConstRecord(ops, data_arr)
ds = Dataset(data, name='dataset:%d' % node_id)
full_reader = ds.reader(ops)
total = ops.Const([100])
def inc_total(rec):
ops.Add([total, rec.val()], [total])
epoch_reader = ReaderWithLimit(full_reader, num_iter=3)
pipe(epoch_reader, processor=inc_total)
Job.current().add_stop_signal(epoch_reader.data_finished())
return [total]
EXPECTED_TOTALS = [103, 115, 136, 145]
def local_copy_op(src, dest):
def copy_op(inputs, outputs):
shutil.copyfile(src, dest)
return copy_op
class UploadToLocalFile(UploadTaskGroupBuilder):
def __init__(self, dest_dir):
self.dest_dir = dest_dir
def build(self, epoch, checkpoint_manager):
with TaskGroup(WorkspaceType.GLOBAL) as upload_task_group:
for node, manager in checkpoint_manager._node_managers:
with Node(str(node)), Task():
src_path = db_name(epoch, manager._node_name, manager._db_prefix)
dest_path = os.path.join(self.dest_dir, str(node))
ops.Python((local_copy_op,
[src_path, dest_path], {}))([], [])
return upload_task_group
class TestCheckpoint(TestCase):
def run_with(self, builder):
with Cluster():
with Job() as job:
outputs = build_pipeline(node_id=0)
output_fetcher = Task(step=core.Net('empty'), outputs=outputs)
def fetch_total(session):
session.run(output_fetcher)
return output_fetcher.outputs()[0].fetch()
session, checkpoint = builder()
compiled_job = job.compile(LocalSession)
num_epochs = JobRunner(compiled_job, checkpoint)(session)
self.assertEquals(num_epochs, len(EXPECTED_TOTALS))
self.assertEquals(fetch_total(session), EXPECTED_TOTALS[-1])
for initial_epoch in range(1, num_epochs + 1):
session, checkpoint = builder()
JobRunner(
compiled_job,
checkpoint, resume_from_epoch=initial_epoch)(session)
self.assertEquals(fetch_total(session), EXPECTED_TOTALS[-1])
for epoch in range(1, num_epochs + 1):
session.run(checkpoint.load(epoch))
self.assertEquals(fetch_total(session),
EXPECTED_TOTALS[epoch - 1])
def test_single_checkpoint(self):
# test single node
try:
tmpdir = tempfile.mkdtemp()
def builder():
ws = workspace.C.Workspace()
session = LocalSession(ws)
checkpoint = CheckpointManager(tmpdir, 'temp_node', 'minidb')
return session, checkpoint
self.run_with(builder)
finally:
shutil.rmtree(tmpdir)
# test multi-node
try:
tmpdir = tempfile.mkdtemp()
def builder():
ws = workspace.C.Workspace()
session = LocalSession(ws)
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
return session, checkpoint
self.run_with(builder)
finally:
shutil.rmtree(tmpdir)
def test_ckpt_name_and_load_model_from_ckpts(self):
try:
num_nodes = 3
tmpdir = tempfile.mkdtemp()
# First, check if the checkpoint name generation mechanism is
# correct.
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
with Cluster():
with Job() as job:
for node_id in range(num_nodes):
build_pipeline(node_id)
compiled_job = job.compile(LocalSession)
checkpoint.init(compiled_job.nodes_to_checkpoint())
for node_id in range(num_nodes):
epoch = 5
node_name = 'trainer_%d' % node_id
expected_db_name = tmpdir + '/' + node_name + '.5'
self.assertEquals(
checkpoint.get_ckpt_db_name(node_name, epoch),
expected_db_name)
shutil.rmtree(tmpdir)
# Next, check mechanism to load model from checkpoints.
tmpdir = tempfile.mkdtemp()
workspace.ResetWorkspace()
for node_id in range(num_nodes):
ws = workspace.C.Workspace()
session = LocalSession(ws)
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
with Cluster():
with Job() as job:
build_pipeline(node_id)
compiled_job = job.compile(LocalSession)
job_runner = JobRunner(compiled_job, checkpoint)
num_epochs = job_runner(session)
self.assertEquals(num_epochs, len(EXPECTED_TOTALS))
# There are 12 global blobs after finishing up the job runner.
# (only blobs on init_group are checkpointed)
self.assertEquals(len(ws.blobs), 12)
ws = workspace.C.Workspace()
session = LocalSession(ws)
self.assertEquals(len(ws.blobs), 0)
model_blob_names = ['trainer_1/task_2/GivenTensorInt64Fill:0',
'trainer_2/task_2/GivenTensorInt64Fill:0']
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
with Cluster():
with Job() as job:
for node_id in range(num_nodes):
build_pipeline(node_id)
compiled_job = job.compile(LocalSession)
job_runner = JobRunner(compiled_job, checkpoint)
job_runner.load_blobs_from_checkpoints(
blob_names=model_blob_names, epoch=1, session=session)
# Check that we can successfully load from checkpoints of epochs
# 1 to 4, but not epoch 5.
for epoch in range(1, 5):
self.assertTrue(
job_runner.load_blobs_from_checkpoints(
blob_names=model_blob_names, epoch=epoch,
session=session))
# Check that all the model blobs are loaded.
for blob_name in model_blob_names:
self.assertTrue(ws.has_blob(blob_name))
self.assertEquals(
ws.fetch_blob(blob_name),
np.array([EXPECTED_TOTALS[epoch - 1]]))
self.assertFalse(
job_runner.load_blobs_from_checkpoints(
blob_names=model_blob_names, epoch=5, session=session))
finally:
shutil.rmtree(tmpdir)
def test_upload_checkpoint(self):
try:
tmpdir = tempfile.mkdtemp()
upload_dir = os.path.join(tmpdir, "upload")
os.mkdir(upload_dir)
num_nodes = 3
# The uploaded files do not exist yet.
for node_id in range(num_nodes):
node_name = 'trainer_%d' % node_id
upload_path = os.path.join(upload_dir, node_name)
self.assertFalse(os.path.exists(upload_path))
# Create and run the job runner.
for node_id in range(3):
ws = workspace.C.Workspace()
session = LocalSession(ws)
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
with Cluster():
with Job() as job:
build_pipeline(node_id)
compiled_job = job.compile(LocalSession)
local_upload_builder = UploadToLocalFile(upload_dir)
job_runner = JobRunner(
compiled_job, checkpoint,
upload_task_group_builder=local_upload_builder)
num_epochs = job_runner(session)
self.assertEquals(num_epochs, len(EXPECTED_TOTALS))
# The uploaded files should exist now.
for node_id in range(num_nodes):
node_name = 'trainer_%d' % node_id
upload_path = os.path.join(upload_dir, node_name)
self.assertTrue(os.path.exists(upload_path))
finally:
shutil.rmtree(tmpdir)
def test_ckpt_save_failure(self):
num_nodes = 3
# The goal of this test is to ensure that the job runs
# successfully even if saving a checkpoint fails.
# Hence tmpdir is a non existent directory to emulate a failure
# while saving checkpoints
tmpdir = "/tmp/path_does_not_exist/"
# Check the saving checkpoint failure does not cause job failure
workspace.ResetWorkspace()
for node_id in range(num_nodes):
ws = workspace.C.Workspace()
session = LocalSession(ws)
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
with Cluster():
with Job() as job:
build_pipeline(node_id)
compiled_job = job.compile(LocalSession)
job_runner = JobRunner(compiled_job, checkpoint)
num_epochs = job_runner(session)
# make sure all epochs are executed even though saving the checkpoint failed
# Saving checkpoint failure should not cause job failure
self.assertEquals(num_epochs, len(EXPECTED_TOTALS))
def test_download_group_simple(self):
"""
A simple test that ensures we have download task group
executed between epoch_group and exit_group.
"""
model = model_helper.ModelHelper(name="test_model")
download_net = core.Net("download_net")
for name in ["input1", "input2", "output", "download_result"]:
model.param_init_net.ConstantFill([],
[name],
shape=[8, ],
value=1.0,
run_once=0)
model.net.Add(["input1", "input2"], ["output"])
download_net.Copy(["output"], ["download_result"])
# All blob values are initialized as 1.0, after download_net executed
# we expect to see download result is the same as training result.
with Job() as job:
with Node("trainer:0"):
with job.init_group:
Task(step=model.param_init_net)
with job.epoch_group:
with Task():
with ops.loop(1):
ops.net(model.net)
with job.download_group:
Task(step=download_net)
epoch_limiter(job, 1)
ws = workspace.C.Workspace()
session = LocalSession(ws)
job_runner = JobRunner(job)
job_runner(session)
expected_result = np.full(8, 2.0).astype(np.float32)
self.assertTrue(np.array_equal(expected_result,
ws.fetch_blob("output")))
self.assertTrue(np.array_equal(expected_result,
ws.fetch_blob("download_result")))
def test_reuse_checkpoint_manager(self):
"""
A simple test that ensures we can reuse a MultiNodeCheckpointManager
object.
"""
try:
tmpdir = tempfile.mkdtemp()
ws = workspace.C.Workspace()
session = LocalSession(ws)
checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')
with Job() as job:
outputs = build_pipeline(node_id=0)
output_fetcher = Task(step=core.Net('empty'), outputs=outputs)
compiled_job = job.compile(LocalSession)
def fetch_total(session):
session.run(output_fetcher)
return output_fetcher.outputs()[0].fetch()
num_epochs = JobRunner(compiled_job, checkpoint)(session)
for initial_epoch in range(1, num_epochs + 1):
JobRunner(
compiled_job,
checkpoint, resume_from_epoch=initial_epoch)(session)
self.assertEquals(fetch_total(session), EXPECTED_TOTALS[-1])
finally:
shutil.rmtree(tmpdir)
|
## @package cnn
# Module caffe2.python.cnn
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import brew
from caffe2.python.model_helper import ModelHelper
from caffe2.proto import caffe2_pb2
import logging
class CNNModelHelper(ModelHelper):
"""A helper model so we can write CNN models more easily, without having to
manually define parameter initializations and operators separately.
"""
def __init__(self, order="NCHW", name=None,
use_cudnn=True, cudnn_exhaustive_search=False,
ws_nbytes_limit=None, init_params=True,
skip_sparse_optim=False,
param_model=None):
logging.warning(
"[====DEPRECATE WARNING====]: you are creating an "
"object from CNNModelHelper class which will be deprecated soon. "
"Please use ModelHelper object with brew module. For more "
"information, please refer to caffe2.ai and python/brew.py, "
"python/brew_test.py for more information."
)
cnn_arg_scope = {
'order': order,
'use_cudnn': use_cudnn,
'cudnn_exhaustive_search': cudnn_exhaustive_search,
}
if ws_nbytes_limit:
cnn_arg_scope['ws_nbytes_limit'] = ws_nbytes_limit
super(CNNModelHelper, self).__init__(
skip_sparse_optim=skip_sparse_optim,
name="CNN" if name is None else name,
init_params=init_params,
param_model=param_model,
arg_scope=cnn_arg_scope,
)
self.order = order
self.use_cudnn = use_cudnn
self.cudnn_exhaustive_search = cudnn_exhaustive_search
self.ws_nbytes_limit = ws_nbytes_limit
if self.order != "NHWC" and self.order != "NCHW":
raise ValueError(
"Cannot understand the CNN storage order %s." % self.order
)
def ImageInput(self, blob_in, blob_out, use_gpu_transform=False, **kwargs):
return brew.image_input(
self,
blob_in,
blob_out,
order=self.order,
use_gpu_transform=use_gpu_transform,
**kwargs
)
def VideoInput(self, blob_in, blob_out, **kwargs):
return brew.video_input(
self,
blob_in,
blob_out,
**kwargs
)
def PadImage(self, blob_in, blob_out, **kwargs):
# TODO(wyiming): remove this dummy helper later
self.net.PadImage(blob_in, blob_out, **kwargs)
def ConvNd(self, *args, **kwargs):
return brew.conv_nd(
self,
*args,
use_cudnn=self.use_cudnn,
order=self.order,
cudnn_exhaustive_search=self.cudnn_exhaustive_search,
ws_nbytes_limit=self.ws_nbytes_limit,
**kwargs
)
def Conv(self, *args, **kwargs):
return brew.conv(
self,
*args,
use_cudnn=self.use_cudnn,
order=self.order,
cudnn_exhaustive_search=self.cudnn_exhaustive_search,
ws_nbytes_limit=self.ws_nbytes_limit,
**kwargs
)
def ConvTranspose(self, *args, **kwargs):
return brew.conv_transpose(
self,
*args,
use_cudnn=self.use_cudnn,
order=self.order,
cudnn_exhaustive_search=self.cudnn_exhaustive_search,
ws_nbytes_limit=self.ws_nbytes_limit,
**kwargs
)
def GroupConv(self, *args, **kwargs):
return brew.group_conv(
self,
*args,
use_cudnn=self.use_cudnn,
order=self.order,
cudnn_exhaustive_search=self.cudnn_exhaustive_search,
ws_nbytes_limit=self.ws_nbytes_limit,
**kwargs
)
def GroupConv_Deprecated(self, *args, **kwargs):
return brew.group_conv_deprecated(
self,
*args,
use_cudnn=self.use_cudnn,
order=self.order,
cudnn_exhaustive_search=self.cudnn_exhaustive_search,
ws_nbytes_limit=self.ws_nbytes_limit,
**kwargs
)
def FC(self, *args, **kwargs):
return brew.fc(self, *args, **kwargs)
def PackedFC(self, *args, **kwargs):
return brew.packed_fc(self, *args, **kwargs)
def FC_Prune(self, *args, **kwargs):
return brew.fc_prune(self, *args, **kwargs)
def FC_Decomp(self, *args, **kwargs):
return brew.fc_decomp(self, *args, **kwargs)
def FC_Sparse(self, *args, **kwargs):
return brew.fc_sparse(self, *args, **kwargs)
def Dropout(self, *args, **kwargs):
return brew.dropout(
self, *args, order=self.order, use_cudnn=self.use_cudnn, **kwargs
)
def LRN(self, *args, **kwargs):
return brew.lrn(
self, *args, order=self.order, use_cudnn=self.use_cudnn, **kwargs
)
def Softmax(self, *args, **kwargs):
return brew.softmax(self, *args, use_cudnn=self.use_cudnn, **kwargs)
def SpatialBN(self, *args, **kwargs):
return brew.spatial_bn(self, *args, order=self.order, **kwargs)
def InstanceNorm(self, *args, **kwargs):
return brew.instance_norm(self, *args, order=self.order, **kwargs)
def Relu(self, *args, **kwargs):
return brew.relu(
self, *args, order=self.order, use_cudnn=self.use_cudnn, **kwargs
)
def PRelu(self, *args, **kwargs):
return brew.prelu(self, *args, **kwargs)
def Concat(self, *args, **kwargs):
return brew.concat(self, *args, order=self.order, **kwargs)
def DepthConcat(self, *args, **kwargs):
"""The old depth concat function - we should move to use concat."""
print("DepthConcat is deprecated. use Concat instead.")
return self.Concat(*args, **kwargs)
def Sum(self, *args, **kwargs):
return brew.sum(self, *args, **kwargs)
def Transpose(self, *args, **kwargs):
return brew.transpose(self, *args, use_cudnn=self.use_cudnn, **kwargs)
def Iter(self, *args, **kwargs):
return brew.iter(self, *args, **kwargs)
def Accuracy(self, *args, **kwargs):
return brew.accuracy(self, *args, **kwargs)
def MaxPool(self, *args, **kwargs):
return brew.max_pool(
self, *args, use_cudnn=self.use_cudnn, order=self.order, **kwargs
)
def MaxPoolWithIndex(self, *args, **kwargs):
return brew.max_pool_with_index(self, *args, order=self.order, **kwargs)
def AveragePool(self, *args, **kwargs):
return brew.average_pool(
self, *args, use_cudnn=self.use_cudnn, order=self.order, **kwargs
)
@property
def XavierInit(self):
return ('XavierFill', {})
def ConstantInit(self, value):
return ('ConstantFill', dict(value=value))
@property
def MSRAInit(self):
return ('MSRAFill', {})
@property
def ZeroInit(self):
return ('ConstantFill', {})
def AddWeightDecay(self, weight_decay):
return brew.add_weight_decay(self, weight_decay)
@property
def CPU(self):
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CPU
return device_option
@property
def GPU(self, gpu_id=0):
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = gpu_id
return device_option
|
## @package test_util
# Module caffe2.python.test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
# clear the default engines settings to separate out its
# affect from the ops tests
core.SetEnginePref({}, {})
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import control, core, test_util, workspace
import logging
logger = logging.getLogger(__name__)
class TestControl(test_util.TestCase):
def setUp(self):
super(TestControl, self).setUp()
self.N_ = 10
self.init_net_ = core.Net("init-net")
cnt = self.init_net_.CreateCounter([], init_count=0)
const_n = self.init_net_.ConstantFill(
[], shape=[], value=self.N_, dtype=core.DataType.INT64)
const_0 = self.init_net_.ConstantFill(
[], shape=[], value=0, dtype=core.DataType.INT64)
self.cnt_net_ = core.Net("cnt-net")
self.cnt_net_.CountUp([cnt])
curr_cnt = self.cnt_net_.RetrieveCount([cnt])
self.init_net_.ConstantFill(
[], [curr_cnt], shape=[], value=0, dtype=core.DataType.INT64)
self.cnt_net_.AddExternalOutput(curr_cnt)
self.cnt_2_net_ = core.Net("cnt-2-net")
self.cnt_2_net_.CountUp([cnt])
self.cnt_2_net_.CountUp([cnt])
curr_cnt_2 = self.cnt_2_net_.RetrieveCount([cnt])
self.init_net_.ConstantFill(
[], [curr_cnt_2], shape=[], value=0, dtype=core.DataType.INT64)
self.cnt_2_net_.AddExternalOutput(curr_cnt_2)
self.cond_net_ = core.Net("cond-net")
cond_blob = self.cond_net_.LT([curr_cnt, const_n])
self.cond_net_.AddExternalOutput(cond_blob)
self.not_cond_net_ = core.Net("not-cond-net")
cond_blob = self.not_cond_net_.GE([curr_cnt, const_n])
self.not_cond_net_.AddExternalOutput(cond_blob)
self.true_cond_net_ = core.Net("true-cond-net")
true_blob = self.true_cond_net_.LT([const_0, const_n])
self.true_cond_net_.AddExternalOutput(true_blob)
self.false_cond_net_ = core.Net("false-cond-net")
false_blob = self.false_cond_net_.GT([const_0, const_n])
self.false_cond_net_.AddExternalOutput(false_blob)
self.idle_net_ = core.Net("idle-net")
self.idle_net_.ConstantFill(
[], shape=[], value=0, dtype=core.DataType.INT64)
def CheckNetOutput(self, nets_and_expects):
"""
Check the net output is expected
nets_and_expects is a list of tuples (net, expect)
"""
for net, expect in nets_and_expects:
output = workspace.FetchBlob(
net.Proto().external_output[-1])
self.assertEqual(output, expect)
def CheckNetAllOutput(self, net, expects):
"""
Check the net output is expected
expects is a list of bools.
"""
self.assertEqual(len(net.Proto().external_output), len(expects))
for i in range(len(expects)):
output = workspace.FetchBlob(
net.Proto().external_output[i])
self.assertEqual(output, expects[i])
def BuildAndRunPlan(self, step):
plan = core.Plan("test")
plan.AddStep(control.Do('init', self.init_net_))
plan.AddStep(step)
self.assertEqual(workspace.RunPlan(plan), True)
def ForLoopTest(self, nets_or_steps):
step = control.For('myFor', nets_or_steps, self.N_)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, self.N_)])
def testForLoopWithNets(self):
self.ForLoopTest(self.cnt_net_)
self.ForLoopTest([self.cnt_net_, self.idle_net_])
def testForLoopWithStep(self):
step = control.Do('count', self.cnt_net_)
self.ForLoopTest(step)
self.ForLoopTest([step, self.idle_net_])
def WhileLoopTest(self, nets_or_steps):
step = control.While('myWhile', self.cond_net_, nets_or_steps)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, self.N_)])
def testWhileLoopWithNet(self):
self.WhileLoopTest(self.cnt_net_)
self.WhileLoopTest([self.cnt_net_, self.idle_net_])
def testWhileLoopWithStep(self):
step = control.Do('count', self.cnt_net_)
self.WhileLoopTest(step)
self.WhileLoopTest([step, self.idle_net_])
def UntilLoopTest(self, nets_or_steps):
step = control.Until('myUntil', self.not_cond_net_, nets_or_steps)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, self.N_)])
def testUntilLoopWithNet(self):
self.UntilLoopTest(self.cnt_net_)
self.UntilLoopTest([self.cnt_net_, self.idle_net_])
def testUntilLoopWithStep(self):
step = control.Do('count', self.cnt_net_)
self.UntilLoopTest(step)
self.UntilLoopTest([step, self.idle_net_])
def DoWhileLoopTest(self, nets_or_steps):
step = control.DoWhile('myDoWhile', self.cond_net_, nets_or_steps)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, self.N_)])
def testDoWhileLoopWithNet(self):
self.DoWhileLoopTest(self.cnt_net_)
self.DoWhileLoopTest([self.idle_net_, self.cnt_net_])
def testDoWhileLoopWithStep(self):
step = control.Do('count', self.cnt_net_)
self.DoWhileLoopTest(step)
self.DoWhileLoopTest([self.idle_net_, step])
def DoUntilLoopTest(self, nets_or_steps):
step = control.DoUntil('myDoUntil', self.not_cond_net_, nets_or_steps)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, self.N_)])
def testDoUntilLoopWithNet(self):
self.DoUntilLoopTest(self.cnt_net_)
self.DoUntilLoopTest([self.cnt_net_, self.idle_net_])
def testDoUntilLoopWithStep(self):
step = control.Do('count', self.cnt_net_)
self.DoUntilLoopTest(step)
self.DoUntilLoopTest([self.idle_net_, step])
def IfCondTest(self, cond_net, expect, cond_on_blob):
if cond_on_blob:
step = control.Do(
'if-all',
control.Do('count', cond_net),
control.If('myIf', cond_net.Proto().external_output[-1],
self.cnt_net_))
else:
step = control.If('myIf', cond_net, self.cnt_net_)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, expect)])
def testIfCondTrueOnNet(self):
self.IfCondTest(self.true_cond_net_, 1, False)
def testIfCondTrueOnBlob(self):
self.IfCondTest(self.true_cond_net_, 1, True)
def testIfCondFalseOnNet(self):
self.IfCondTest(self.false_cond_net_, 0, False)
def testIfCondFalseOnBlob(self):
self.IfCondTest(self.false_cond_net_, 0, True)
def IfElseCondTest(self, cond_net, cond_value, expect, cond_on_blob):
if cond_value:
run_net = self.cnt_net_
else:
run_net = self.cnt_2_net_
if cond_on_blob:
step = control.Do(
'if-else-all',
control.Do('count', cond_net),
control.If('myIfElse', cond_net.Proto().external_output[-1],
self.cnt_net_, self.cnt_2_net_))
else:
step = control.If('myIfElse', cond_net,
self.cnt_net_, self.cnt_2_net_)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(run_net, expect)])
def testIfElseCondTrueOnNet(self):
self.IfElseCondTest(self.true_cond_net_, True, 1, False)
def testIfElseCondTrueOnBlob(self):
self.IfElseCondTest(self.true_cond_net_, True, 1, True)
def testIfElseCondFalseOnNet(self):
self.IfElseCondTest(self.false_cond_net_, False, 2, False)
def testIfElseCondFalseOnBlob(self):
self.IfElseCondTest(self.false_cond_net_, False, 2, True)
def IfNotCondTest(self, cond_net, expect, cond_on_blob):
if cond_on_blob:
step = control.Do(
'if-not',
control.Do('count', cond_net),
control.IfNot('myIfNot', cond_net.Proto().external_output[-1],
self.cnt_net_))
else:
step = control.IfNot('myIfNot', cond_net, self.cnt_net_)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, expect)])
def testIfNotCondTrueOnNet(self):
self.IfNotCondTest(self.true_cond_net_, 0, False)
def testIfNotCondTrueOnBlob(self):
self.IfNotCondTest(self.true_cond_net_, 0, True)
def testIfNotCondFalseOnNet(self):
self.IfNotCondTest(self.false_cond_net_, 1, False)
def testIfNotCondFalseOnBlob(self):
self.IfNotCondTest(self.false_cond_net_, 1, True)
def IfNotElseCondTest(self, cond_net, cond_value, expect, cond_on_blob):
if cond_value:
run_net = self.cnt_2_net_
else:
run_net = self.cnt_net_
if cond_on_blob:
step = control.Do(
'if-not-else',
control.Do('count', cond_net),
control.IfNot('myIfNotElse',
cond_net.Proto().external_output[-1],
self.cnt_net_, self.cnt_2_net_))
else:
step = control.IfNot('myIfNotElse', cond_net,
self.cnt_net_, self.cnt_2_net_)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(run_net, expect)])
def testIfNotElseCondTrueOnNet(self):
self.IfNotElseCondTest(self.true_cond_net_, True, 2, False)
def testIfNotElseCondTrueOnBlob(self):
self.IfNotElseCondTest(self.true_cond_net_, True, 2, True)
def testIfNotElseCondFalseOnNet(self):
self.IfNotElseCondTest(self.false_cond_net_, False, 1, False)
def testIfNotElseCondFalseOnBlob(self):
self.IfNotElseCondTest(self.false_cond_net_, False, 1, True)
def testSwitch(self):
step = control.Switch(
'mySwitch',
(self.false_cond_net_, self.cnt_net_),
(self.true_cond_net_, self.cnt_2_net_)
)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, 0), (self.cnt_2_net_, 2)])
def testSwitchNot(self):
step = control.SwitchNot(
'mySwitchNot',
(self.false_cond_net_, self.cnt_net_),
(self.true_cond_net_, self.cnt_2_net_)
)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(self.cnt_net_, 1), (self.cnt_2_net_, 0)])
def testBoolNet(self):
bool_net = control.BoolNet(('a', True))
step = control.Do('bool', bool_net)
self.BuildAndRunPlan(step)
self.CheckNetAllOutput(bool_net, [True])
bool_net = control.BoolNet(('a', True), ('b', False))
step = control.Do('bool', bool_net)
self.BuildAndRunPlan(step)
self.CheckNetAllOutput(bool_net, [True, False])
bool_net = control.BoolNet([('a', True), ('b', False)])
step = control.Do('bool', bool_net)
self.BuildAndRunPlan(step)
self.CheckNetAllOutput(bool_net, [True, False])
def testCombineConditions(self):
# combined by 'Or'
combine_net = control.CombineConditions(
'test', [self.true_cond_net_, self.false_cond_net_], 'Or')
step = control.Do('combine',
self.true_cond_net_,
self.false_cond_net_,
combine_net)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(combine_net, True)])
# combined by 'And'
combine_net = control.CombineConditions(
'test', [self.true_cond_net_, self.false_cond_net_], 'And')
step = control.Do('combine',
self.true_cond_net_,
self.false_cond_net_,
combine_net)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(combine_net, False)])
def testMergeConditionNets(self):
# merged by 'Or'
merge_net = control.MergeConditionNets(
'test', [self.true_cond_net_, self.false_cond_net_], 'Or')
step = control.Do('merge', merge_net)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(merge_net, True)])
# merged by 'And'
merge_net = control.MergeConditionNets(
'test', [self.true_cond_net_, self.false_cond_net_], 'And')
step = control.Do('merge', merge_net)
self.BuildAndRunPlan(step)
self.CheckNetOutput([(merge_net, False)])
|
## @package embedding_generation_benchmark
# Module caffe2.python.embedding_generation_benchmark
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from caffe2.python import workspace, core, utils, model_helper
import argparse
import numpy as np
import time
import logging
logging.basicConfig()
log = logging.getLogger("embedding_generation_benchmark")
log.setLevel(logging.DEBUG)
def generate_data(T, batch_size, max_seq_length):
'''
Fill a queue with input data
'''
log.info("Generating T={} batches".format(T))
generate_input_init_net = core.Net('generate_input_init')
queue = generate_input_init_net.CreateBlobsQueue(
[], "inputqueue", num_blobs=1, capacity=T,
)
workspace.RunNetOnce(generate_input_init_net)
generate_input_net = core.Net('generate_input')
generate_input_net.EnqueueBlobs([queue, "scratch"], ["scratch"])
np.random.seed(2603)
for t in range(T):
if (t % (max(10, T // 10)) == 0):
log.info("Generating data {}/{}".format(t, T))
X = np.tile(np.arange(max_seq_length), [batch_size, 1]).transpose()
workspace.FeedBlob("scratch", X)
workspace.RunNetOnce(generate_input_net.Proto())
log.info("Finished data generation")
return queue
def generate_embedding_table(vocab_size, embedding_size):
log.info("Generating embedding table with dimensions {}"
.format([vocab_size, embedding_size]))
generate_table_net = core.Net('generate_table')
table = generate_table_net.GaussianFill(
[],
['embedding_table'],
shape=[vocab_size, embedding_size],
)
workspace.RunNetOnce(generate_table_net)
return table
def create_model(args, queue, embedding_table, embedding_size):
model = model_helper.ModelHelper(name='embedding_generation_bench')
input_blob = model.net.DequeueBlobs(queue, 'input_data')
if args.implementation == 'sinusoid':
model.net.SinusoidPositionEncoding(
[input_blob],
['output'],
embedding_size=embedding_size
)
else:
model.net.Gather(
[embedding_table, input_blob],
['output'],
)
return model
def Caffe2EmbeddingGeneration(args):
T = args.data_size // args.batch_size
queue = generate_data(T, args.batch_size, args.seq_length)
embedding_table = None
if args.implementation == 'table':
embedding_table = generate_embedding_table(
args.seq_length,
args.embedding_size,
)
model = create_model(args, queue, embedding_table, args.embedding_size)
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
start_time = time.time()
num_iters = T
total_iters = 0
# Run the Benchmark
log.info("------ Warming up ------")
workspace.RunNet(model.net.Proto().name)
log.info("------ Starting benchmark ------")
start_time = time.time()
last_time = time.time()
for iteration in range(1, num_iters, args.iters_to_report):
iters_once = min(args.iters_to_report, num_iters - iteration)
total_iters += iters_once
workspace.RunNet(model.net.Proto().name, iters_once)
new_time = time.time()
log.info(
"Iter: {} / {}. Embeddings Generated Per Second: {}k.".format(
iteration,
num_iters,
(iters_once * args.batch_size * args.seq_length) /
(new_time - last_time) // 100 / 10,
)
)
last_time = new_time
total_per_sec = (num_iters - 1) * args.batch_size * args.seq_length
total_per_sec = total_per_sec / (time.time() - start_time) // 100 / 10
log.info("Done. Total embeddings generated per second " +
"excluding 1st iteration: {}k".format(total_per_sec))
return time.time() - start_time
@utils.debug
def Benchmark(args):
return Caffe2EmbeddingGeneration(args)
def GetArgumentParser():
parser = argparse.ArgumentParser(
description="Embedding generation benchmark."
)
parser.add_argument(
"--embedding_size",
type=int,
default=512,
help="Embedding size",
)
parser.add_argument(
"--batch_size",
type=int,
default=16,
help="The batch size."
)
parser.add_argument(
"--data_size",
type=int,
default=10000,
help="Number of sequences to generate"
)
parser.add_argument(
"--seq_length",
type=int,
default=128,
help="Max sequence length"
)
parser.add_argument(
"--iters_to_report",
type=int,
default=20,
help="Number of iterations to report progress"
)
parser.add_argument(
"--implementation",
type=str,
default="sinusoid",
help="'table' or 'sinusoid'",
)
return parser
if __name__ == '__main__':
args, extra_args = GetArgumentParser().parse_known_args()
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
'--caffe2_print_blob_sizes_at_exit=0'] + extra_args)
device = core.DeviceOption(caffe2_pb2.CPU)
with core.DeviceScope(device):
Benchmark(args)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import workspace
import os
import tempfile
import unittest
class TestDB(unittest.TestCase):
def setUp(self):
handle, self.file_name = tempfile.mkstemp()
os.close(handle)
self.data = [
(
"key{}".format(i).encode("ascii"),
"value{}".format(i).encode("ascii")
)
for i in range(1, 10)
]
def testSimple(self):
db = workspace.C.create_db(
"minidb", self.file_name, workspace.C.Mode.write)
for key, value in self.data:
transaction = db.new_transaction()
transaction.put(key, value)
del transaction
del db # should close DB
db = workspace.C.create_db(
"minidb", self.file_name, workspace.C.Mode.read)
cursor = db.new_cursor()
data = []
while cursor.valid():
data.append((cursor.key(), cursor.value()))
cursor.next() # noqa: B305
del cursor
db.close() # test explicit db closer
self.assertEqual(data, self.data)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from inspect import currentframe, getframeinfo
import unittest
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace, test_util
from caffe2.python.task import Node, Task
class TestScopes(test_util.TestCase):
def testBlobReferenceIsIndependentFromNameScope(self):
blob_v = core.BlobReference("v")
with core.NameScope("foo"):
blob_w = core.BlobReference("w")
with core.NameScope("bar"):
blob_x = core.BlobReference("x")
self.assertEqual(str(blob_v), "v")
self.assertEqual(str(blob_w), "w")
self.assertEqual(str(blob_x), "x")
def testNameScopeWithOp(self):
global_x = core.BlobReference("x")
global_y = core.BlobReference("y")
with core.NameScope("foo"):
# Raw strings should have namescope prepended.
op = core.CreateOperator("Relu", "x", "y")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "foo/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "foo/y")
# BlobReferences should not.
op = core.CreateOperator("Relu", global_x, global_y)
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "y")
def testNameScopeWithReset(self):
with core.NameScope("foo"):
# foo/
op = core.CreateOperator("Relu", "x", "y")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "foo/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "foo/y")
with core.NameScope("bar"):
# foo/bar/
op = core.CreateOperator("Relu", "x", "y")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "foo/bar/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "foo/bar/y")
# Back to foo/
op = core.CreateOperator("Relu", "x", "y")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "foo/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "foo/y")
with core.NameScope("bar", reset=True):
# bar/
op = core.CreateOperator("Relu", "x", "y")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "bar/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "bar/y")
# Back to foo/
op = core.CreateOperator("Relu", "x", "y")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "foo/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "foo/y")
def testDeviceScope(self):
# No device
op = core.CreateOperator("Relu", "x", "y")
self.assertFalse(op.HasField('device_option'))
# explicitly setting a device
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
op = core.CreateOperator("Relu", "x", "y", device_option=device_option)
self.assertTrue(op.HasField('device_option'))
self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
with core.DeviceScope(device_option):
# from device scope
op = core.CreateOperator("Relu", "x", "y")
self.assertTrue(op.HasField('device_option'))
self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
# from an overridden device option
override_device = caffe2_pb2.DeviceOption()
override_device.device_type = caffe2_pb2.CPU
op = core.CreateOperator(
"Relu", "x", "y", device_option=override_device)
self.assertTrue(op.HasField('device_option'))
self.assertEqual(op.device_option.device_type, caffe2_pb2.CPU)
# back from normal: no device
op = core.CreateOperator("Relu", "x", "y")
self.assertFalse(op.HasField('device_option'))
device_option = caffe2_pb2.DeviceOption()
def testNameAndDeviceScopeTogether(self):
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
with core.DeviceScope(device_option):
with core.NameScope("foo"):
op = core.CreateOperator("Relu", "x", "y")
self.assertTrue(op.HasField('device_option'))
self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "foo/x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "foo/y")
class TestCloneNet(test_util.TestCase):
def testPartialClone(self):
params = core.Net('params')
p1 = params.ConstantFill([], ['p1'])
workspace.CreateNet(params)
workspace.RunNetOnce(params)
n = core.Net('original')
a1 = n.AddExternalInput('a1')
a2 = n.AddExternalInput('a2')
b1, b2 = n.Concat([a1, a2], ['b1', 'b2'], axis=0)
c1 = n.Sum([b1, p1], ['c1'])
c2 = n.Sum([b2], ['c2'])
d = n.Sum([c1, c2], ['d'])
# test that gradient ops are ignored when partial-cloning
n.AddGradientOperators([d])
# test some in-place ops
k = n.Sum([p1], ['k'])
e = n.Sum([d], ['e'])
e = n.Sum([e, k], [e])
e = n.Sum([e], [e])
f = n.Sum(e, ['f'])
def net_assert(net, num_ops, inputs, outputs, internals):
self.assertEqual(len(net.Proto().op), num_ops)
self.assertEqual(set(net.Proto().external_input), inputs)
self.assertEqual(set(net.Proto().external_output), outputs)
all_blobs = set(net.Proto().external_input)
all_blobs |= set(net.Proto().external_output)
for op in net.Proto().op:
all_blobs |= set(op.input) | set(op.output)
self.assertEqual(all_blobs, inputs | outputs | internals)
# create net to make sure its valid
for input in inputs:
workspace.FeedBlob(input, np.array([]))
workspace.CreateNet(net)
n2, (d22, ) = n.ClonePartial('f1', {a1: 'a11', a2: 'a22'}, [d])
net_assert(
n2, 4, {'p1', 'a11', 'a22'}, {'f1/d'},
{'f1/b1', 'f1/b2', 'f1/c1', 'f1/c2', 'p1'})
self.assertTrue(isinstance(d22, core.BlobReference))
self.assertEqual(d22.Net(), n2)
self.assertEqual(str(d22), 'f1/d')
n3, (d22, ) = n.ClonePartial('f2', [b1, b2], [d])
net_assert(
n3, 3, {'p1', 'b1', 'b2'}, {'f2/d'}, {'f2/c1', 'f2/c2', 'p1'})
self.assertEqual(str(d22), 'f2/d')
n4, (c22, ) = n.ClonePartial('f3', [b1], [c1])
net_assert(n4, 1, {'p1', 'b1'}, {'f3/c1'}, {'p1'})
self.assertEqual(str(c22), 'f3/c1')
n5, (c11, c22) = n.ClonePartial('f4', [b1, b2], [c1, c2])
net_assert(n5, 2, {'p1', 'b1', 'b2'}, {'f4/c1', 'f4/c2'}, {'p1'})
self.assertEqual(str(c11), 'f4/c1')
self.assertEqual(str(c22), 'f4/c2')
with self.assertRaises(AssertionError):
n.ClonePartial('f4', [a1, a2, c2], [d])
n6, (e22, ) = n.ClonePartial('f5', [d], [e])
net_assert(n6, 4, {'p1', 'd'}, {'f5/e'}, {'f5/k', 'p1'})
self.assertEqual(str(e22), 'f5/e')
n8, (e22, f22) = n.ClonePartial('f7', [d], [e, f])
net_assert(n8, 5, {'p1', 'd'}, {'f7/e', 'f7/f'}, {'p1', 'f7/k'})
self.assertEqual(str(e22), 'f7/e')
self.assertEqual(str(f22), 'f7/f')
params._CheckLookupTables()
n._CheckLookupTables()
class TestCreateOperator(test_util.TestCase):
def testCreate(self):
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
op = core.CreateOperator(
"Ludicrous", "x", "y", name="ludicrous",
control_input="z", device_option=device_option,
engine="WARP", arg1=1, arg2="2", arg3=[1, 2, 3])
self.assertEqual(op.type, "Ludicrous")
self.assertEqual(op.name, "ludicrous")
self.assertEqual(op.engine, "WARP")
self.assertEqual(len(op.input), 1)
self.assertEqual(op.input[0], "x")
self.assertEqual(len(op.output), 1)
self.assertEqual(op.output[0], "y")
self.assertEqual(len(op.control_input), 1)
self.assertEqual(op.control_input[0], "z")
self.assertTrue(op.HasField('device_option'))
self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertTrue(len(op.arg), 3)
# can't guarantee ordering of kwargs, so generate a set of args
# to test with
arg_map = {}
for arg in op.arg:
arg_map[arg.name] = arg
# Check all elements exist that should
self.assertEqual("arg1" in arg_map, True)
self.assertEqual("arg2" in arg_map, True)
self.assertEqual("arg3" in arg_map, True)
# Now test that all args were initialized correctly
self.assertEqual(arg_map["arg1"].i, 1)
self.assertEqual(arg_map["arg2"].s, b"2")
self.assertEqual(list(arg_map["arg3"].ints), [1, 2, 3])
def testCreateWithNoneKwarg(self):
with self.assertRaises(ValueError):
core.CreateOperator("Ludicrous", "x", "y", arg1=None)
class TestAutoNaming(test_util.TestCase):
def assertOperatorListEqual(self, operatorDefList1, operatorDefList2):
for op in operatorDefList1:
op.debug_info = ""
for op in operatorDefList2:
op.debug_info = ""
self.assertEqual(operatorDefList1, operatorDefList2)
"""
Test that operators are named with different names, and that automatically
named blob names don't clash intra or inter networks.
"""
def test_next_blob(self):
def create_net():
net = core.Net('net')
with core.NameScope('foo'):
net.Add(['a', 'b'], net.NextScopedBlob('ab'))
net.Add(['c', 'd'], net.NextBlob('cd'))
return net
net_a = create_net()
net_b = create_net()
# created net proto is predicatable.
self.assertOperatorListEqual(net_a.Proto().op,
net_b.Proto().op)
self.assertEqual(net_a.Proto().op[0].output[0], 'foo/ab')
self.assertEqual(net_a.Proto().op[1].output[0], 'cd')
net_c = core.Net('net')
# different calls return different blob names
self.assertNotEqual(str(net_c.NextBlob('b')), str(net_c.NextBlob('b')))
def test_auto_naming(self):
a = core.Net('net')
b = core.Net('net')
self.assertNotEqual(a.Proto().name, b.Proto().name)
a_in1 = a.AddExternalInput('a')
b_in1 = b.AddExternalInput('b')
all_outputs_single = []
all_outputs_list = []
def add_ops():
all_outputs_single.append(a.Sum([a_in1, a_in1]))
all_outputs_single.append(a.Sum([a_in1, a_in1]))
all_outputs_single.append(b.Sum([b_in1, b_in1]))
all_outputs_single.append(b.Sum([b_in1, b_in1]))
all_outputs_list.append(a.Sum([a_in1, a_in1], outputs=2))
all_outputs_list.append(a.Sum([a_in1, a_in1], outputs=2))
all_outputs_list.append(b.Sum([b_in1, b_in1], outputs=2))
all_outputs_list.append(b.Sum([b_in1, b_in1], outputs=2))
add_ops()
with core.NameScope('n1'):
add_ops()
# Force reset of lookup tables
a.Proto().name
with core.NameScope('n2'):
add_ops()
all_outputs = []
for s in all_outputs_single:
all_outputs.append(str(s))
for l in all_outputs_list:
for o in l:
all_outputs.append(str(o))
for i, o1 in enumerate(all_outputs):
for j, o2 in enumerate(all_outputs):
if i != j:
self.assertNotEqual(str(o1), str(o2))
a._CheckLookupTables()
b._CheckLookupTables()
class TestAppendNet(test_util.TestCase):
def test_external_inputs_merged_correctly(self):
netA = core.Net("A")
netA.Sum(["in1", "in2"], ["sum1"])
self.assertTrue("in1" in netA.external_inputs)
netB = core.Net("B")
netB.Sum(["in3", "in4"], ["in1"])
netB.AppendNet(netA)
self.assertFalse("in1" in netB.external_inputs)
def test_external_inputs_merged_correctlyB(self):
netA = core.Net("A")
netA.Sum(["in1", "in2"], ["sum1"])
self.assertTrue("in1" in netA.external_inputs)
netB = core.Net("B")
netB.Sum(["in3", "in4"], ["in1"])
netA.AppendNet(netB) # note different order than in prev test
self.assertTrue("in1" in netA.external_inputs)
class TestExtractPredictorNet(test_util.TestCase):
def test_extract_simple(self):
from caffe2.python import brew
from caffe2.python.model_helper import ModelHelper, ExtractPredictorNet
model = ModelHelper(name="test", arg_scope={'order': 'NCHW'})
[data, label] = brew.image_input(
model,
"reader", ["xx/data", "label"],
is_test=1,
)
cnv = brew.conv(model, data, 'cnv', 32, 32, 4)
a = brew.fc(model, cnv, 'a', 100, 200)
pred = brew.fc(model, a, 'pred', 200, 5)
brew.softmax(model, [pred, label], "softmax")
(predict_net, export_blobs) = ExtractPredictorNet(
net_proto=model.net.Proto(),
input_blobs=["xx/data"],
output_blobs=["pred"],
renames={"xx/data": "image"},
)
export_blobs = set(export_blobs)
ops = list(predict_net.Proto().op)
for op in ops:
self.assertFalse(op.type == "Softmax")
self.assertFalse("xx/data" in op.input)
# Note: image input should not be included
self.assertEquals(ops[0].type, "Conv")
self.assertEquals(ops[1].type, "FC")
self.assertEquals(ops[2].type, "FC")
self.assertEquals(len(ops), 3)
# test rename happened
self.assertEquals(ops[0].input[0], "image")
# Check export blobs
self.assertTrue("image" not in export_blobs)
self.assertTrue("xx/data" not in export_blobs)
self.assertEqual(set([str(p) for p in model.params]), export_blobs)
# Check external inputs/outputs
self.assertTrue("image" in predict_net.Proto().external_input)
self.assertEquals(set(["pred"]), set(predict_net.Proto().external_output))
self.assertEqual(
set(predict_net.Proto().external_input) -
set([str(p) for p in model.params]), set(["image"])
)
class TestOperatorTraceback(test_util.TestCase):
def op_name_check(self, net, cf, line, func):
net.PopulateProtoWithFileName()
filename = getframeinfo(cf).filename
self.assertEqual(net.Proto().op[0].name, '{}:{}:{}'.format(
filename, line, func))
def test_operator_constructor_traceback(self):
net = core.Net("test")
a, b = net.AddExternalInput("a", "b")
net.Mul([a, b], "c"); cf = currentframe(); line = cf.f_lineno
func = cf.f_code.co_name
with self.assertRaises(Exception):
workspace.RunNetOnce(net)
with self.assertRaises(Exception):
workspace.CreateNet(net)
self.op_name_check(net, cf, line, func)
def test_operator_runtime_traceback(self):
net = core.Net("test")
a = net.AddExternalInput("a")
workspace.blobs[a] = np.array([1, 2, 3], dtype=np.float32)
net.Split(a, ["b", "c"], axis=0); cf = currentframe(); line = cf.f_lineno
func = cf.f_code.co_name
with self.assertRaises(Exception):
workspace.RunNetOnce(net)
workspace.CreateNet(net)
with self.assertRaises(Exception):
workspace.RunNet(net)
self.op_name_check(net, cf, line, func)
def test_c_workspace_constructor(self):
net = core.Net("test")
a, b = net.AddExternalInput("a", "b")
net.Mul([a, b], "c"); cf = currentframe(); line = cf.f_lineno
func = cf.f_code.co_name
ws = workspace.C.Workspace()
with self.assertRaises(Exception):
ws.run(net)
with self.assertRaises(Exception):
ws.create_net(net)
self.op_name_check(net, cf, line, func)
def test_c_workspace_runtime(self):
net = core.Net("test")
a = net.AddExternalInput("a")
net.Split(a, ["b", "c"], axis=0); cf = currentframe(); line = cf.f_lineno
func = cf.f_code.co_name
ws = workspace.C.Workspace()
ws.create_blob(str(a)).feed(np.array([1, 2, 3], dtype=np.float32))
ws.create_net(net)
with self.assertRaises(Exception):
ws.run(net)
self.op_name_check(net, cf, line, func)
def test_async_exception_handling(self):
net = core.Net("test")
net.Proto().type = 'dag' # this runs operators on background threads
a = net.AddExternalInput("a")
net.Split(a, ["b", "c"], axis=0); cf = currentframe(); line = cf.f_lineno
func = cf.f_code.co_name
workspace.FeedBlob(a, np.array([1, 2, 3], dtype=np.float32))
with self.assertRaises(Exception) as enforceNotMet:
workspace.RunNetOnce(net)
self.assertIn('enforce fail', str(enforceNotMet.exception))
self.op_name_check(net, cf, line, func)
class TestCreatePlan(test_util.TestCase):
def test_create_plan_from_proto_correctly(self):
from caffe2.python.net_builder import ops
with Node('trainer'), Task(name='my_task', num_instances=2) as task:
with ops.task_init():
globl = ops.Const(0)
with ops.task_instance_init():
local = ops.Const(0)
with ops.loop(100):
ops.Copy(globl, local)
with ops.task_instance_exit():
ops.Add([globl, local], [globl])
with ops.task_exit():
ops.Mul([globl, globl], [globl])
plan = core.Plan(task.get_step())
test_plan = core.Plan.create_from_proto(plan.Proto())
self.assertEqual(len(plan.Steps()), 1)
self.assertEqual(len(test_plan.Steps()), 1)
self.assertEqual(plan.Steps()[0].Name(), test_plan.Steps()[0].Name())
self.assertEqual(len(plan.Nets()), len(test_plan.Nets()))
for idx in range(0, len(plan.Nets())):
# When we create Net for test_plan, we will end up with new Net
# name with postfix.
net_1 = plan.Nets()[idx]
net_2 = test_plan.Nets()[idx]
trim_size = len(net_1.Name())
self.assertEqual(net_1.Name(), net_2.Name()[:trim_size])
class TestOpRegistryKey(test_util.TestCase):
def test_is_operator(self):
self.assertTrue(core.IsOperator('Relu'))
self.assertFalse(core.IsOperator('NOEXIST'))
def test_is_operator_with_engine(self):
self.assertTrue(core.IsOperatorWithEngine('Relu', 'DEFAULT'))
self.assertFalse(core.IsOperatorWithEngine('Relu', 'NOEXIST'))
class TestDeviceOption(test_util.TestCase):
def test_check_equal_node_name(self):
opt1 = core.DeviceOption(0)
opt2 = core.DeviceOption(0)
self.assertTrue(core.device_option_equal(opt1, opt2))
opt2.node_name = 'test'
self.assertTrue(core.device_option_equal(opt1, opt2))
self.assertFalse(core.device_option_equal(opt1, opt2, ignore_node_name=False))
opt1.node_name = 'test'
self.assertTrue(core.device_option_equal(opt1, opt2, ignore_node_name=False))
def test_check_equal_default_value(self):
opt1 = caffe2_pb2.DeviceOption()
opt2 = caffe2_pb2.DeviceOption()
opt1.device_type = 0
self.assertTrue(core.device_option_equal(opt1, opt2))
opt1.cuda_gpu_id = 5
# opt1 still is on CPU, so the options should be equal
self.assertTrue(core.device_option_equal(opt1, opt2))
opt2.device_type = 0
self.assertTrue(core.device_option_equal(opt1, opt2))
opt1.device_type = 1
self.assertFalse(core.device_option_equal(opt1, opt2))
@unittest.skipIf(not workspace.has_gpu_support, 'No GPU support')
class TestInferDevice(test_util.TestCase):
def setUp(self):
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
self.cuda_option = device_option
self.cpu_option = caffe2_pb2.DeviceOption()
def _test_op(
self,
op_name,
in_option,
out_option,
op_option=None,
inputs=None,
outputs=None
):
op_option = self.cuda_option if not op_option else op_option
inputs = ["blob_1"] if not inputs else inputs
outputs = ["blob_2"] if not outputs else outputs
with core.DeviceScope(op_option):
op = core.CreateOperator(op_name, inputs, outputs)
input_dev, output_dev = core.InferOpBlobDevices(op)
for in_dev in input_dev:
self.assertEqual(in_dev, in_option)
for out_dev in output_dev:
self.assertEqual(out_dev, out_option)
def test_infer_device(self):
self._test_op(
"FC",
self.cuda_option,
self.cuda_option,
op_option=self.cuda_option,
inputs=["data", "fc_w", "fc_b"],
outputs=["fc_1"]
)
def test_infer_device_cross_device(self):
self._test_op("CopyGPUToCPU", self.cuda_option, self.cpu_option)
self._test_op("CopyCPUToGPU", self.cpu_option, self.cuda_option)
self._test_op("EnsureCPUOutput", self.cuda_option, self.cpu_option)
self._test_op("CopyFromCPUInput", self.cpu_option, self.cuda_option)
self._test_op(
"EnsureCPUOutput",
self.cpu_option,
self.cpu_option,
op_option=self.cpu_option
)
self._test_op(
"CopyFromCPUInput",
self.cpu_option,
self.cpu_option,
op_option=self.cpu_option
)
def test_device_inference_function(self):
# ConcatOp.
op_option = self.cuda_option
with core.DeviceScope(op_option):
op = core.CreateOperator(
'Concat',
['X_{}'.format(i) for i in range(4)],
['concat_result', 'split_info'],
axis=1)
input_dev, output_dev = core.InferOpBlobDevices(op)
# 2nd output's type is CPU irrespective of Concat op's device option.
self.assertEqual(output_dev[1], self.cpu_option)
#SplitOp.
op_option = self.cuda_option
with core.DeviceScope(op_option):
op = core.CreateOperator(
'Split',
['input', 'split'],
['X_{}'.format(i) for i in range(4)],
axis=0)
input_dev, output_dev = core.InferOpBlobDevices(op)
# 2nd input's type is CPU irrespective of Split op's device option.
self.assertEqual(input_dev[1], self.cpu_option)
def test_inject_copy(self):
net = core.Net("test")
init_net = core.Net("init")
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
weight = init_net.XavierFill([], 'fc_w', shape=[10, 100])
bias = init_net.ConstantFill([], 'fc_b', shape=[10, ])
with core.DeviceScope(device_option):
net.FC(["data", weight, bias], "fc1")
_, blob_to_device = core.InjectCrossDeviceCopies(init_net)
new_net, blob_to_device = core.InjectCrossDeviceCopies(
net, blob_to_device
)
op = new_net._net.op[-1]
self.assertEqual(op.type, "FC")
self.assertEqual(op.input[0], "data_cuda_1")
self.assertEqual(op.input[1], "fc_w_cuda_1")
self.assertEqual(op.input[2], "fc_b_cuda_1")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(new_net._net.op[-2].type, "CopyCPUToGPU")
self.assertEqual(new_net._net.op[0].type, "CopyCPUToGPU")
self.assertNotEqual(blob_to_device["fc_w"], device_option)
def test_cross_nets(self):
net = core.Net("test")
init_net = core.Net("init")
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
weight = init_net.XavierFill([], 'fc_w', shape=[10, 100])
bias = init_net.ConstantFill([], 'fc_b', shape=[10, ])
const = init_net.ConstantFill([], 'const', shape=[], value=1.)
with core.DeviceScope(device_option):
const = init_net.Add([const, const], [const])
fc_out = net.FC(["data", weight, bias], "fc1")
net.Add([fc_out, const], [fc_out])
data_remap = {'data': device_option}
nets, _ = core.InjectDeviceCopiesAmongNets(
[init_net, net], blob_to_device_init=data_remap
)
op = nets[1]._net.op[0]
self.assertEqual(op.type, "CopyCPUToGPU")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(op.output[0], "fc_w_cuda_1")
op = nets[1]._net.op[1]
self.assertEqual(op.type, "CopyCPUToGPU")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(op.output[0], "fc_b_cuda_1")
op = nets[1]._net.op[2]
self.assertEqual(op.type, "FC")
self.assertEqual(op.input[0], "data")
self.assertEqual(op.input[1], "fc_w_cuda_1")
self.assertEqual(op.input[2], "fc_b_cuda_1")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
op = nets[1]._net.op[3]
self.assertEqual(op.type, "Add")
self.assertEqual(op.input[0], "fc1")
self.assertEqual(op.input[1], "const_cuda_1")
# check that moved blob is in input to the new net
for c in ["data", "fc_w", "fc_b", "const_cuda_1"]:
self.assertTrue(c in nets[1]._net.external_input)
"""
For reference, net.Proto() should be like:
name: ""
op {
input: "fc_w"
output: "fc_w_cuda_1"
name: ""
type: "CopyCPUToGPU"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
op {
input: "fc_b"
output: "fc_b_cuda_1"
name: ""
type: "CopyCPUToGPU"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
op {
input: "data"
input: "fc_w_cuda_1"
input: "fc_b_cuda_1"
output: "fc1"
name: ""
type: "FC"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
op {
input: "fc1"
input: "const_cuda_1"
output: "fc1"
name: ""
type: "Add"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
external_input: "data"
external_input: "fc_w"
external_input: "fc_b"
external_input: "const"
external_input: "const_cuda_1"
"""
def test_cross_nets_no_change(self):
net = core.Net("test")
init_net = core.Net("init")
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
with core.DeviceScope(device_option):
weight = init_net.XavierFill([], 'fc_w', shape=[10, 100])
bias = init_net.ConstantFill([], 'fc_b', shape=[10, ])
net.FC(["data", weight, bias], "fc1")
data_remap = {'data': device_option}
nets = core.InjectDeviceCopiesAmongNetsWithoutB2D(
[init_net, net], blob_to_device_init=data_remap
)
op = nets[1]._net.op[0]
self.assertEqual(op.type, "FC")
self.assertEqual(op.input[0], "data")
self.assertEqual(op.input[1], "fc_w")
self.assertEqual(op.input[2], "fc_b")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
"""
For reference, net.Proto() should be like:
name: ""
op {
input: "data"
input: "fc_w"
input: "fc_b"
output: "fc1"
name: ""
type: "FC"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
external_input: "data"
external_input: "fc_w"
external_input: "fc_b"
"""
def test_inject_copy_multi_use(self):
net = core.Net("test")
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
with core.DeviceScope(device_option):
net.Relu("data", "relu1")
net.Relu("data", "relu2")
with core.DeviceScope(device_option):
net.Relu("data", "relu3")
net.Relu("data", "relu4")
device_option.cuda_gpu_id = 0
with core.DeviceScope(device_option):
net.Relu("data", "relu5")
device_option.cuda_gpu_id = 1
with core.DeviceScope(device_option):
net.Relu("data", "relu6")
new_net, _ = core.InjectCrossDeviceCopies(net)
op = new_net._net.op[0]
self.assertEqual(op.type, "CopyCPUToGPU")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(op.output[0], "data_cuda_1")
op = new_net._net.op[1]
self.assertEqual(op.type, "Relu")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(op.output[0], "relu1")
op = new_net._net.op[2]
self.assertEqual(op.type, "Relu")
self.assertEqual(op.device_option.device_type, 0)
self.assertEqual(op.output[0], "relu2")
op = new_net._net.op[3]
self.assertEqual(op.type, "Relu")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(op.input[0], "data_cuda_1")
self.assertEqual(op.output[0], "relu3")
op = new_net._net.op[4]
self.assertEqual(op.type, "Relu")
self.assertEqual(op.device_option.device_type, 0)
self.assertEqual(op.output[0], "relu4")
op = new_net._net.op[5]
self.assertEqual(op.type, "CopyCPUToGPU")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 0)
self.assertEqual(op.output[0], "data_cuda_0")
op = new_net._net.op[6]
self.assertEqual(op.type, "Relu")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 0)
self.assertEqual(op.input[0], "data_cuda_0")
self.assertEqual(op.output[0], "relu5")
op = new_net._net.op[7]
self.assertEqual(op.type, "Relu")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 1)
self.assertEqual(op.input[0], "data_cuda_1")
self.assertEqual(op.output[0], "relu6")
"""
For reference, net.Proto() should be like:
name: ""
op {
input: "data"
output: "data_cuda_1"
name: ""
type: "CopyCPUToGPU"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
op {
input: "data_cuda_1"
output: "relu1"
name: ""
type: "Relu"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
op {
input: "data"
output: "relu2"
name: ""
type: "Relu"
}
op {
input: "data_cuda_1"
output: "relu3"
name: ""
type: "Relu"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
op {
input: "data"
output: "relu4"
name: ""
type: "Relu"
}
op {
input: "data"
output: "data_cuda_0"
name: ""
type: "CopyCPUToGPU"
device_option {
device_type: 1
cuda_gpu_id: 0
}
}
op {
input: "data_cuda_0"
output: "relu5"
name: ""
type: "Relu"
device_option {
device_type: 1
cuda_gpu_id: 0
}
}
op {
input: "data_cuda_1"
output: "relu6"
name: ""
type: "Relu"
device_option {
device_type: 1
cuda_gpu_id: 1
}
}
external_input: "data"
"""
def test_inject_copy_placeholder_ops(self):
'''
Test inject cross device copies with placeholder ops. Placeholder ops
are decorator/fake ops that don't have operator schema.
'''
# Create CPU and GPU devices on 2 nodes.
cpu_device = []
gpu_device = []
for i in range(0, 2):
cpu_device.append(caffe2_pb2.DeviceOption())
cpu_device[i].node_name = 'node:' + str(i)
gpu_device.append(caffe2_pb2.DeviceOption())
gpu_device[i].device_type = caffe2_pb2.CUDA
gpu_device[i].cuda_gpu_id = 0
gpu_device[i].node_name = 'node:' + str(i)
send_node = 'node:0'
recv_node = 'node:1'
placeholder_send = 'Placeholder:Dummy:Send'
placeholder_recv = 'Placeholder:Dummy:Recv'
# init_net.
init_net = core.Net("init_net")
with core.DeviceScope(gpu_device[0]):
weight = init_net.XavierFill([], 'fc_w', shape=[10, 100])
bias = init_net.ConstantFill([], 'fc_b', shape=[10, ])
with core.DeviceScope(cpu_device[0]):
op = core.CreateOperator(
placeholder_send, [weight, bias], [],
dst_node=recv_node, callsite_id=0)
init_net._net.op.extend([op])
# train_net
train_net = core.Net("train_net")
with core.DeviceScope(cpu_device[1]):
# XXX. replace hardcoded op name. Move test to net_transforms.
op = core.CreateOperator(
placeholder_recv, [], [weight, bias],
src_node=send_node, callsite_id=0)
train_net._net.op.extend([op])
train_net.FC(["data", weight, bias], "fc1")
# Inject cross device copies.
init_net, x_dev_state = core.InjectCrossDeviceCopies(
init_net,
placeHolderOps=[placeholder_send, placeholder_recv])
train_net, x_dev_state = core.InjectCrossDeviceCopies(
train_net, x_dev_state,
placeHolderOps=[placeholder_send, placeholder_recv])
# Verify (init_net)
op = init_net._net.op[2]
self.assertEqual(op.type, "CopyGPUToCPU")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 0)
self.assertEqual(op.output[0], "fc_w_cpu")
op = init_net._net.op[3]
self.assertEqual(op.type, "CopyGPUToCPU")
self.assertEqual(op.device_option.device_type, 1)
self.assertEqual(op.device_option.cuda_gpu_id, 0)
self.assertEqual(op.output[0], "fc_b_cpu")
op = init_net._net.op[4]
self.assertEqual(op.type, placeholder_send)
self.assertEqual(op.device_option.device_type, 0)
self.assertEqual(op.input[0], "fc_w_cpu")
self.assertEqual(op.input[1], "fc_b_cpu")
# Verify (train_net)
op = train_net._net.op[0]
self.assertEqual(op.type, placeholder_recv)
self.assertEqual(op.device_option.device_type, 0)
self.assertEqual(op.output[0], "fc_w_cpu")
self.assertEqual(op.output[1], "fc_b_cpu")
op = train_net._net.op[3]
self.assertEqual(op.type, "FC")
self.assertEqual(op.device_option.device_type, 0)
self.assertEqual(op.input[1], "fc_w_cpu")
self.assertEqual(op.input[2], "fc_b_cpu")
def test_blob_inplace(self):
net = core.Net("test")
device_option = caffe2_pb2.DeviceOption()
device_option.device_type = caffe2_pb2.CUDA
device_option.cuda_gpu_id = 1
net.Adagrad(['param', 'moment', 'grad', 'lr'], ['param', 'moment'])
with core.DeviceScope(device_option):
net.Relu("param", "param_relu_no_sense")
net, _ = core.InjectCrossDeviceCopies(net)
op = net._net.op[1]
self.assertEqual(op.type, 'CopyCPUToGPU')
self.assertEqual(op.input[0], 'param')
self.assertEqual(op.output[0], 'param_cuda_1')
op = net._net.op[2]
self.assertEqual(op.input[0], 'param_cuda_1')
net.Relu('nonsense_input', 'moment')
# should not raise inplace error
core.InjectCrossDeviceCopies(net)
with core.DeviceScope(device_option):
net.Relu('nonsense_input_gpu', 'moment')
with self.assertRaises(RuntimeError):
core.InjectCrossDeviceCopies(net)
if __name__ == '__main__':
unittest.main()
|
## @package dataset
# Module caffe2.python.dataset
"""
Implementation of an in-memory dataset with structured schema.
Use this to store and iterate through datasets with complex schema that
fit in memory.
Iterating through entries of this dataset is very fast since the dataset
is stored as a set of native Caffe2 tensors, thus no type conversion or
deserialization is necessary.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from caffe2.python.dataio import Reader, Writer
from caffe2.python.schema import (
Struct, from_blob_list, from_column_list, InitEmptyRecord)
import numpy as np
class _DatasetReader(Reader):
def __init__(self, dataset, name, batch_size=1, enforce_batch_size=False):
"""Don't call this directly. Instead, use dataset.reader()"""
Reader.__init__(self, dataset.content())
self.dataset = dataset
self.name = name or (dataset.name + '_cursor')
self.batch_size = batch_size
self.enforce_batch_size = enforce_batch_size
self.cursor = None
def setup_ex(self, init_net, exit_net):
if self.cursor is None:
self.cursor = init_net.CreateTreeCursor(
[],
init_net.NextScopedBlob(self.name),
fields=self.dataset.fields)
def read(self, read_net):
assert self.cursor, 'setup not called.'
content = self.dataset.content()
with core.NameScope(read_net.NextName(self.name)):
fields = read_net.ReadNextBatch(
[self.cursor] + content.field_blobs(),
content.field_names(),
batch_size=self.batch_size,
enforce_batch_size=self.enforce_batch_size)
if type(fields) is core.BlobReference:
fields = [fields]
return (read_net.IsEmpty([fields[0]]), fields)
def reset(self, net):
net.ResetCursor([self.cursor], [])
class _DatasetRandomReader(Reader):
def __init__(self, dataset, name, indices, batch_size=1, loop_over=False,
enforce_batch_size=False):
"""Don't call this directly. Instead, use dataset.random_reader()"""
Reader.__init__(self, dataset.content())
self.dataset = dataset
self.cursor = None
self.name = name or (dataset.name + '_cursor')
self.indices = indices
self.batch_size = batch_size
self.loop_over = loop_over
self.enforce_batch_size = enforce_batch_size
def setup_ex(self, init_net, exit_net):
if self.cursor is None:
self.cursor = init_net.CreateTreeCursor(
[],
[self.name],
fields=self.dataset.fields)
def reset(self, net):
net.ResetCursor([self.cursor], [])
def computeoffset(self, net):
self.reset(net)
offsets = net.ComputeOffset(
[self.cursor] + self.dataset.content().field_blobs(),
'offsets')
self.offsets = offsets
def sort_and_shuffle(self, net, sort_by_field=None,
shuffle_size=1, batch_size=1):
# no sorting by default
content = self.dataset.content()
sort_by_field_idx = -1
if sort_by_field:
assert sort_by_field in content.field_names(), (
'Must be valid field.')
sort_by_field_idx = content.field_names().index(sort_by_field)
self.reset(net)
indices = net.SortAndShuffle(
[self.cursor] + content.field_blobs(),
'indices',
sort_by_field_idx=sort_by_field_idx,
shuffle_size=shuffle_size,
batch_size=batch_size)
self.indices = indices
def read(self, read_net):
with core.NameScope(read_net.NextName(self.name)):
fields = read_net.ReadRandomBatch(
[self.cursor, self.indices, self.offsets] + (
self.dataset.content().field_blobs()),
self.dataset.content().field_names(),
batch_size=self.batch_size,
enforce_batch_size=self.enforce_batch_size,
loop_over=self.loop_over)
return (read_net.IsEmpty([fields[0]]), fields)
class _DatasetWriter(Writer):
def __init__(self, content):
"""Don't call this directly. Use dataset.writer() instead."""
self._content = content
self.mutex = None
def setup_ex(self, init_net, exit_net):
if self.mutex is None:
self.mutex = init_net.CreateMutex([])
def write(self, writer_net, fields):
"""
Add operations to `net` that append the blobs in `fields` to the end
of the dataset. An additional operator will also be added that checks
the consistency of the data in `fields` against the dataset schema.
Args:
writer_net: The net that will contain the Append operators.
fields: A list of BlobReference to be appeneded to this dataset.
"""
assert self.mutex is not None, 'setup not called.'
field_blobs = self._content.field_blobs()
assert len(fields) == len(field_blobs), (
'Expected %s fields, got %s.' % (len(field_blobs), len(fields)))
writer_net.CheckDatasetConsistency(
fields, [], fields=self._content.field_names())
writer_net.AtomicAppend(
[self.mutex] + field_blobs + list(fields),
field_blobs)
def commit(self, finish_net):
"""Commit is a no-op for an in-memory dataset."""
pass
def Const(net, value, dtype=None, name=None):
"""
Create a 'constant' by first creating an external input in the given
net, and then feeding the corresponding blob with its provided value
in the current workspace. The name is automatically generated in order
to avoid clashes with existing blob names.
"""
assert isinstance(net, core.Net), 'net must be a core.Net instance.'
value = np.array(value, dtype=dtype)
blob = net.AddExternalInput(net.NextName(prefix=name))
workspace.FeedBlob(str(blob), value)
return blob
def execution_step_with_progress(name, init_net, substeps, rows_read):
# progress reporter
report_net = core.Net('report_net')
report_net.Print([rows_read], [])
return core.execution_step(
name,
substeps,
report_net=report_net,
concurrent_substeps=True,
report_interval=5)
class Dataset(object):
"""Represents an in-memory dataset with fixed schema.
Use this to store and iterate through datasets with complex schema that
fit in memory.
Iterating through entries of this dataset is very fast since the dataset
is stored as a set of native Caffe2 tensors, thus no type conversion or
deserialization is necessary.
"""
def __init__(self, fields, name=None):
"""Create an un-initialized dataset with schema provided by `fields`.
Before this dataset can be used, it must be initialized, either by
`init_empty` or `init_from_dataframe`.
Args:
fields: either a schema.Struct or a list of field names in a format
compatible with the one described in schema.py.
name: optional name to prepend to blobs that will store the data.
"""
assert isinstance(fields, list) or isinstance(fields, Struct), (
'fields must be either a Struct or a list of raw field names.')
if isinstance(fields, list):
fields = from_column_list(fields)
self.schema = fields
self.fields = fields.field_names()
self.field_types = fields.field_types()
self.name = name or 'dataset'
self.field_blobs = fields.field_blobs() if fields.has_blobs() else None
def trim(self, net, multiple_of):
"""
Trims the contents of this dataset so that the number of records is
multiple of the given argument.
"""
net.TrimDataset(
self.field_blobs,
self.field_blobs,
fields=self.fields,
multiple_of=multiple_of)
def init_empty(self, init_net):
"""Initialize the blobs for this dataset with empty values.
Empty arrays will be immediately fed into the current workspace,
and `init_net` will take those blobs as external inputs.
"""
self.field_blobs = InitEmptyRecord(
init_net, self.schema.clone_schema()).field_blobs()
def init_from_dataframe(self, net, dataframe):
"""Initialize the blobs for this dataset from a Pandas dataframe.
Each column of the dataframe will be immediately fed into the current
workspace, and the `net` will take this blobs as external inputs.
"""
assert len(self.fields) == len(dataframe.columns)
self.field_blobs = [
Const(net, dataframe.as_matrix([col]).flatten(), name=field)
for col, field in enumerate(self.fields)]
def get_blobs(self):
"""
Return the list of BlobReference pointing to the blobs that contain
the data for this dataset.
"""
assert self
return self.field_blobs
def content(self):
"""
Return a Record of BlobReferences pointing to the full content of
this dataset.
"""
return from_blob_list(self.schema, self.field_blobs)
def field_names(self):
"""Return the list of field names for this dataset."""
return self.fields
def field_types(self):
"""
Return the list of field dtypes for this dataset.
If a list of strings, not a schema.Struct, was passed to the
constructor, this will return a list of dtype(np.void).
"""
return self.field_types
def reader(self, init_net=None, cursor_name=None, batch_size=1,
enforce_batch_size=False):
"""Create a Reader object that is used to iterate through the dataset.
This will append operations to `init_net` that create a TreeCursor,
used to iterate through the data.
NOTE: Currently, it is not safe to append to a dataset while reading.
Args:
init_net: net that will be run once to create the cursor.
cursor_name: optional name for the blob containing a pointer
to the cursor.
batch_size: how many samples to read per iteration.
Returns:
A _DatasetReader that can be used to create operators that will
iterate through the dataset.
"""
assert self.field_blobs, 'Dataset not initialized.'
reader = _DatasetReader(self, cursor_name, batch_size,
enforce_batch_size)
if init_net is not None:
reader.setup_ex(init_net, None)
return reader
def random_reader(self, init_net=None, indices=None, cursor_name=None,
batch_size=1, loop_over=False, enforce_batch_size=False):
"""Create a Reader object that is used to iterate through the dataset.
NOTE: The reader order depends on the order in indices.
Args:
init_net: net that will be run once to create the cursor.
indices: blob of reading order
cursor_name: optional name for the blob containing a pointer
to the cursor.
batch_size: how many samples to read per iteration.
loop_over: repeat the dataset indefinitely (in the same order)
Returns:
A DatasetReader that can be used to create operators that will
iterate through the dataset according to indices.
"""
assert self.field_blobs, 'Dataset not initialized.'
reader = _DatasetRandomReader(
self, cursor_name, indices, batch_size, loop_over,
enforce_batch_size)
if init_net is not None:
reader.setup_ex(init_net, None)
return reader
def writer(self, init_net=None):
"""Create a Writer that can be used to append entries into the dataset.
NOTE: Currently, it is not safe to append to a dataset
while reading from it.
NOTE: Currently implementation of writer is not thread safe.
TODO: fixme
Args:
init_net: net that will be run once in order to create the writer.
(currently not used)
"""
assert self.field_blobs, 'Dataset not initialized.'
writer = _DatasetWriter(self.content())
if init_net is not None:
writer.setup_ex(init_net, None)
return writer
|
## @package text_file_reader
# Module caffe2.python.text_file_reader
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from caffe2.python.dataio import Reader
from caffe2.python.schema import Scalar, Struct, data_type_for_dtype
class TextFileReader(Reader):
"""
Wrapper around operators for reading from text files.
"""
def __init__(self, init_net, filename, schema, num_passes=1, batch_size=1):
"""
Create op for building a TextFileReader instance in the workspace.
Args:
init_net : Net that will be run only once at startup.
filename : Path to file to read from.
schema : schema.Struct representing the schema of the data.
Currently, only support Struct of strings.
num_passes : Number of passes over the data.
batch_size : Number of rows to read at a time.
"""
assert isinstance(schema, Struct), 'Schema must be a schema.Struct'
for name, child in schema.get_children():
assert isinstance(child, Scalar), (
'Only scalar fields are supported in TextFileReader.')
field_types = [
data_type_for_dtype(dtype) for dtype in schema.field_types()]
Reader.__init__(self, schema)
self._reader = init_net.CreateTextFileReader(
[],
filename=filename,
num_passes=num_passes,
field_types=field_types)
self._batch_size = batch_size
def read(self, net):
"""
Create op for reading a batch of rows.
"""
blobs = net.TextFileReaderRead(
[self._reader],
len(self.schema().field_names()),
batch_size=self._batch_size)
if type(blobs) is core.BlobReference:
blobs = [blobs]
is_empty = net.IsEmpty(
[blobs[0]],
core.ScopedBlobReference(net.NextName('should_stop'))
)
return (is_empty, blobs)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import unittest
import time
from caffe2.python import workspace, model_helper
from caffe2.python import timeout_guard
import caffe2.python.data_workers as data_workers
def dummy_fetcher(fetcher_id, batch_size):
# Create random amount of values
n = np.random.randint(64) + 1
data = np.zeros((n, 3))
labels = []
for j in range(n):
data[j, :] *= (j + fetcher_id)
labels.append(data[j, 0])
return [np.array(data), np.array(labels)]
def dummy_fetcher_rnn(fetcher_id, batch_size):
# Hardcoding some input blobs
T = 20
N = batch_size
D = 33
data = np.random.rand(T, N, D)
label = np.random.randint(N, size=(T, N))
seq_lengths = np.random.randint(N, size=(N))
return [data, label, seq_lengths]
class DataWorkersTest(unittest.TestCase):
def testNonParallelModel(self):
workspace.ResetWorkspace()
model = model_helper.ModelHelper(name="test")
old_seq_id = data_workers.global_coordinator._fetcher_id_seq
coordinator = data_workers.init_data_input_workers(
model,
["data", "label"],
dummy_fetcher,
32,
2,
input_source_name="unittest"
)
new_seq_id = data_workers.global_coordinator._fetcher_id_seq
self.assertEqual(new_seq_id, old_seq_id + 2)
coordinator.start()
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
for _i in range(500):
with timeout_guard.CompleteInTimeOrDie(5):
workspace.RunNet(model.net.Proto().name)
data = workspace.FetchBlob("data")
labels = workspace.FetchBlob("label")
self.assertEqual(data.shape[0], labels.shape[0])
self.assertEqual(data.shape[0], 32)
for j in range(32):
self.assertEqual(labels[j], data[j, 0])
self.assertEqual(labels[j], data[j, 1])
self.assertEqual(labels[j], data[j, 2])
coordinator.stop_coordinator("unittest")
self.assertEqual(coordinator._coordinators, [])
def testRNNInput(self):
workspace.ResetWorkspace()
model = model_helper.ModelHelper(name="rnn_test")
old_seq_id = data_workers.global_coordinator._fetcher_id_seq
coordinator = data_workers.init_data_input_workers(
model,
["data1", "label1", "seq_lengths1"],
dummy_fetcher_rnn,
32,
2,
dont_rebatch=False,
batch_columns=[1, 1, 0],
)
new_seq_id = data_workers.global_coordinator._fetcher_id_seq
self.assertEqual(new_seq_id, old_seq_id + 2)
coordinator.start()
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
while coordinator._coordinators[0]._state._inputs < 100:
time.sleep(0.01)
# Run a couple of rounds
workspace.RunNet(model.net.Proto().name)
workspace.RunNet(model.net.Proto().name)
# Wait for the enqueue thread to get blocked
time.sleep(0.2)
# We don't dequeue on caffe2 side (as we don't run the net)
# so the enqueue thread should be blocked.
# Let's now shutdown and see it succeeds.
self.assertTrue(coordinator.stop())
def testInputOrder(self):
#
# Create two models (train and validation) with same input blobs
# names and ensure that both will get the data in correct order
#
workspace.ResetWorkspace()
self.counters = {0: 0, 1: 1}
def dummy_fetcher_rnn_ordered1(fetcher_id, batch_size):
# Hardcoding some input blobs
T = 20
N = batch_size
D = 33
data = np.zeros((T, N, D))
data[0][0][0] = self.counters[fetcher_id]
label = np.random.randint(N, size=(T, N))
label[0][0] = self.counters[fetcher_id]
seq_lengths = np.random.randint(N, size=(N))
seq_lengths[0] = self.counters[fetcher_id]
self.counters[fetcher_id] += 1
return [data, label, seq_lengths]
workspace.ResetWorkspace()
model = model_helper.ModelHelper(name="rnn_test_order")
coordinator = data_workers.init_data_input_workers(
model,
input_blob_names=["data2", "label2", "seq_lengths2"],
fetch_fun=dummy_fetcher_rnn_ordered1,
batch_size=32,
max_buffered_batches=1000,
num_worker_threads=1,
dont_rebatch=True,
input_source_name='train'
)
coordinator.start()
val_model = model_helper.ModelHelper(name="rnn_test_order_val")
coordinator1 = data_workers.init_data_input_workers(
val_model,
input_blob_names=["data2", "label2", "seq_lengths2"],
fetch_fun=dummy_fetcher_rnn_ordered1,
batch_size=32,
max_buffered_batches=1000,
num_worker_threads=1,
dont_rebatch=True,
input_source_name='val'
)
coordinator1.start()
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
workspace.CreateNet(val_model.net)
while coordinator._coordinators[0]._state._inputs < 900:
time.sleep(0.01)
with timeout_guard.CompleteInTimeOrDie(5):
for m in (model, val_model):
print(m.net.Proto().name)
workspace.RunNet(m.net.Proto().name)
last_data = workspace.FetchBlob('data2')[0][0][0]
last_lab = workspace.FetchBlob('label2')[0][0]
last_seq = workspace.FetchBlob('seq_lengths2')[0]
# Run few rounds
for _i in range(10):
workspace.RunNet(m.net.Proto().name)
data = workspace.FetchBlob('data2')[0][0][0]
lab = workspace.FetchBlob('label2')[0][0]
seq = workspace.FetchBlob('seq_lengths2')[0]
self.assertEqual(data, last_data + 1)
self.assertEqual(lab, last_lab + 1)
self.assertEqual(seq, last_seq + 1)
last_data = data
last_lab = lab
last_seq = seq
time.sleep(0.2)
self.assertTrue(coordinator.stop())
|
## @package mkl_test_util
# Module caffe2.python.mkl_test_util
"""
The MKL test utils is a small addition on top of the hypothesis test utils
under caffe2/python, which allows one to more easily test MKL related
operators.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import hypothesis.strategies as st
from caffe2.proto import caffe2_pb2
from caffe2.python import workspace
from caffe2.python import hypothesis_test_util as hu
cpu_do = hu.cpu_do
gpu_do = hu.gpu_do
mkl_do = caffe2_pb2.DeviceOption(device_type=caffe2_pb2.MKLDNN)
device_options = hu.device_options + (
[mkl_do] if workspace.C.has_mkldnn else [])
def device_checker_device_options():
return st.just(device_options)
def gradient_checker_device_option():
return st.sampled_from(device_options)
gcs = dict(
gc=gradient_checker_device_option(),
dc=device_checker_device_options()
)
gcs_cpu_only = dict(gc=st.sampled_from([cpu_do]), dc=st.just([cpu_do]))
gcs_gpu_only = dict(gc=st.sampled_from([gpu_do]), dc=st.just([gpu_do]))
gcs_mkl_only = dict(gc=st.sampled_from([mkl_do]), dc=st.just([mkl_do]))
gcs_cpu_mkl = dict(gc=st.sampled_from([cpu_do, mkl_do]), dc=st.just([cpu_do, mkl_do]))
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from collections import namedtuple
from six import string_types
OpSchema = workspace.C.OpSchema
def namedtupledict(typename, field_names, *args, **kwargs):
field_names_map = {n: i for i, n in enumerate(field_names)}
# Some output names are invalid python identifier, e.g. "0"
kwargs.setdefault('rename', True)
data = namedtuple(typename, field_names, *args, **kwargs)
def getitem(self, key):
if isinstance(key, string_types):
key = field_names_map[key]
return super(type(self), self).__getitem__(key)
data.__getitem__ = getitem
return data
class _Functional(object):
def __getattribute__(self, op_type):
def op_func(*inputs, **args):
ws = workspace.C.Workspace()
schema = OpSchema.get(op_type)
input_prefix = 'input_'
output_prefix = 'output_'
def get_name_list(prefix, num, max_num):
return [prefix + str(x) for x in range(min(num, max_num))]
input_names, output_names = [], []
input_names = get_name_list(
input_prefix, len(inputs), schema.max_input
)
# verify the length of input name is in range
# of schema
num_input = len(input_names)
if num_input > schema.max_input or num_input < \
schema.min_input or not schema.num_inputs_allowed(num_input):
raise ValueError(
"Functional C2: Number of inputs not in \
range: {} - {} or not allowed."
.format(schema.min_input, schema.max_input)
)
if 'num_output' in args:
num_output = args['num_output']
if num_output > schema.max_output or \
num_output < schema.min_output or \
not schema.num_outputs_allowed(num_output) or \
not schema.num_inputs_outputs_allowed(num_input,
num_output):
raise ValueError(
"Functional C2: Number of output \
not in range: {} - {} or not allowed"
.format(schema.min_output, schema.max_output)
)
output_names = get_name_list(
output_prefix, num_output, schema.max_output
)
args.pop('num_output')
calculated = schema.CalculateOutput(num_input)
if not output_names and calculated != -1:
output_names = get_name_list(
output_prefix, calculated, schema.max_output
)
if not output_names:
max_output = schema.max_output
# For an op with max_output == inf
# and no Output defined in schema
# user should pass output_size explicitly
if schema.inf == max_output:
raise ValueError(
"For operators with max_output == inf,\
user should pass num_output explicity."
)
output_names = get_name_list(
output_prefix, max_output, max_output
)
for i, input_blob in enumerate(inputs):
ws.create_blob(input_names[i]).feed(input_blob)
op = core.CreateOperator(
op_type, input_names, output_names, **args
)
ws._run_operator(op.SerializeToString())
# RunOperator
output_values = [ws.fetch_blob(x) for x in output_names]
return namedtupledict('output', output_names)(*output_values)
return op_func
Functional = _Functional()
|
## @package net_builder
# Module caffe2.python.net_builder
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, context
from caffe2.python.task import Task, TaskGroup
from caffe2.python.control_ops_util import add_if_op, add_while_op
@context.define_context()
class NetBuilder(object):
"""
Scope-driven mechanism for building nets, loops and conditional blocks.
Arguments:
name: NetBuilder's name
initial_scope: list of blobs that are available for reading/writing
Example:
from caffe2.python.net_builder import NetBuilder, ops
with NetBuilder() as nb:
c = ops.Const(5)
d = ops.Const(0)
with ops.loop():
ops.stop_if(ops.LE([c, ops.Const(0)]))
ops.Add([c, ops.Const(-1)], [c])
with ops.If(ops.GE([c, ops.Const(3)])):
ops.Add([d, ops.Const(10)], [d])
ops.Print(c, [])
ops.Print(d, [])
step = core.to_execution_step(nb)
"""
def __init__(self, name=None, initial_scope=None, _stop_blob_required=False,
_stop_blob=None, _fullname=None, _use_control_ops=False):
parent = NetBuilder.current(required=False)
assert not _fullname or not name, 'Cannot set both _fullname and name'
assert not _use_control_ops or \
(not _stop_blob_required and not _stop_blob), \
'Stop blobs are not used with control operators'
self.name = _fullname or '/'.join(
n for n in (parent.name if parent else None, name) if n
)
self._frozen = False
self._current_net = None
self._children = []
if parent:
# make sure parent has an up to date lexical scope computed
parent._update_lexical_scope()
self._init_lexical_scope = set(parent._lexical_scope) if parent else set()
if initial_scope:
self._init_lexical_scope |= set([str(b) for b in initial_scope])
self._lexical_scope = set(self._init_lexical_scope)
self._stop_blob = _stop_blob
self._stop_blob_required = _stop_blob_required
self._use_control_ops = _use_control_ops
def stop_blob(self):
"""
Returns the BlobReference to the stop_blob of this NetBuilder.
If one is not yet available, creates one.
This function assumes that the stop_blob() will be used immediatelly
in the current net, so it doesn't initialize it if the current net is
the first of the builder.
"""
assert not self._use_control_ops, \
'Stop blobs are not used with control operators'
if self._stop_blob is None:
net = self.current_net()
self._stop_blob = core.BlobReference(
net.NextName('stop_blob'), net=net)
net.Const(False, blob_out=self._stop_blob)
if self._current_net != self._children[0]:
self._children.insert(0, core.Net('stop_blob_init'))
self._children[0].Const(False, blob_out=self._stop_blob)
return self._stop_blob
def stop_if(self, blob):
assert not self._use_control_ops, \
'Stop blobs are not used with control operators'
stop_blob = self.stop_blob()
ops.Or([stop_blob, blob], [stop_blob])
self._current_net = None
def _assert_mutable(self):
assert not self._frozen, (
'This NetBuilder (%s) has been built already.' % self.name)
def _update_lexical_scope(self):
"""
Updates lexical scope based on the current list of children.
Lexical scope contains names of blobs that are currently available
and were introduced in the net builder
"""
self._lexical_scope = set(self._init_lexical_scope)
for child in self._children:
if isinstance(child, core.Net):
self._lexical_scope |= child.UsedBlobNames()
elif isinstance(child, NetBuilder) and child._use_control_ops:
self._lexical_scope |= child._lexical_scope
def _reset_children(self):
self._current_net = None
self._children = []
self._lexical_scope = set(self._init_lexical_scope)
def add(self, child):
self._assert_mutable()
if self._use_control_ops:
assert isinstance(child, core.Net) or (
isinstance(child, NetBuilder) and child._use_control_ops), \
"Expected Net or NetBuilder with control ops"
self._current_net = None
self._children.append(child)
# to-do : check it's not a dag net
if isinstance(child, core.Net):
self._current_net = child
self._update_lexical_scope()
return child
def current_net(self, name=None):
self._assert_mutable()
if self._current_net is None or name is not None:
self.add(core.Net(name))
return self._current_net
def freeze(self):
for child in self._children:
if hasattr(child, 'freeze'):
child.freeze()
self._current_net = None
self._frozen = True
def get(self):
self.freeze()
return self._children
def __exit__(self, etype, *args):
if self._use_control_ops and len(self._children) > 0:
_children = self._children
self._reset_children()
merged_net = NetBuilder.merge_nets(
_children, self._lexical_scope)
assert merged_net, "Expected a non-empty merge of children"
self._children = [merged_net]
self.freeze()
if etype is not None:
return
assert (not self._stop_blob_required) or self._stop_blob is not None, (
'This NetBuilder (%s) requires a stop condition ' % self.name +
'to be set with `stop` or `stop_if`')
@staticmethod
def merge_nets(nets_or_builders, outer_blob_names):
# Only nets or builders with control ops are allowed.
# Need to pay attention to external outputs, e.g.
# ...
# IfNet1 (cond_blob):
# (Net1)
# X = 1
# IfNet2 (...):
# X = X + 1
# ...
# In this example there're two children in then branch of IfNet1:
# a subnet Net1 that creates blob X and sets its value to one, and
# a net builder IfNet2 that (conditionally) increments X.
# From IfNet2's point of view X is an external input
# and output blob, it will be put into IfNet2 net's external_output.
# At the same time, from the point of view of IfNet1 X is purely local.
# Net.AppendNet just merges external outputs of the networks, so
# without checking this the result of Net1.AppendNet(IfNet2's net)
# would have blob X in external_output
net = None
for n in nets_or_builders:
cur = None
if isinstance(n, NetBuilder):
assert n._use_control_ops, \
"Merging of NetBuilder supported only for control ops"
nets = n.get()
assert len(nets) == 1 and isinstance(nets[0], core.Net), \
"Invalid control op net builder"
cur = nets[0]
else:
assert isinstance(n, core.Net)
cur = n
if net:
net.AppendNet(cur)
else:
net = cur
if net:
# correct external output
external_outputs = [o for o in net.Proto().external_output
if o in outer_blob_names]
net.Proto().external_output[:] = external_outputs
return net
def __str__(self):
return self.name or 'Un-named NetBuilder'
class Operations(object):
"""
Operations to be used in the context of a NetBuilder.
"""
def net(self, net=None, name=None):
"""
Retrieves the current net, or add a new net to the builder.
Args:
net: If provided, add the given net to the active builder.
Else, returns the current Net or creates a new one as needed.
name: if provided, creates a new Net with given name and makes
it the new current net of the active builder. Cannot
be provided if net is provided.
"""
assert name is None or net is None, (
'Cannot provide both `net` and `name`.')
if net is not None:
NetBuilder.current().add(net)
return net
return NetBuilder.current().current_net(name=name)
def __getattr__(self, op_type):
"""
Adds an operator call to the currently active Net.
"""
if op_type.startswith('__'):
raise AttributeError()
# We want hasattr to work properly even if no context is active.
if NetBuilder.current(required=False) is None:
raise AttributeError('No active NetBuilder.')
return getattr(self.net(), op_type)
def task_group(self):
"""
Creates a local task group which will execute as the next step of
the current NetBuilder.
"""
from caffe2.python import task
group = NetBuilder.current()
with task.Cluster():
with task.Node('local'):
tg = task.TaskGroup()
group.add(tg)
return tg
def stop(self):
"""
Stop execution of the current execution step.
Example:
ops.Print(a, 0)
ops.stop()
ops.Print(b, 0)
In the example, 'b' will never be printed.
"""
return self.stop_if(ops.Const(True))
def stop_if(self, blob):
"""
Stop execution of the current execution step if the
condition `blob` is met.
Example:
ops.Print(a, 0)
ops.stop_if(ops.LE([x, ops.Const(0)]))
ops.Print(b, 0)
In the example, 'b' will only be printed if the value of scalar
tensor 'x' lower or equal to 0.
"""
return NetBuilder.current().stop_if(blob)
def loop(self, iters=None, name=None):
"""
Creates a NetBuilder that will execute in a loop as the next step of
the current NetBuilder. If `iters` is provided, the loop will execute
for `iters` iterations and then stop. `iters` can be a constant or a
BlobReference. If `iters` is not provided, the loop will execute
until `ops.stop` or `ops.stop_if` is called.
Examples:
a = ops.Const(5)
with ops.loop():
ops.stop_if(ops.LE([a, ops.Const(0)]))
ops.Print(a, 0)
ops.Add([a, ops.Const(-1)], [a])
Above, 'a' will be printed 5 times, with values 5 to 1.
with ops.loop(10) as loop:
ops.LogInfo(loop.iter())
This will print the numbers from 0 to 9.
x = ops.Add([ops.Const(10), ops.Const(10)])
with ops.loop(x) as loop:
ops.LogInfo(loop.iter())
This will print the numbers from 0 to 19.
"""
return NetBuilder.current().add(_Loop(iters, name=name))
def stop_guard(self, has_stopped_blob=None, name=None):
"""
Creates a NetBuilder that will execute once as the next step of the
current NetBuilder. After execution, a bool tensor will indicate
whether the inner execution was halted with `stop` or `stop_if`.
Example:
a = ops.Const(True)
with ops.stop_guard() as sg1:
ops.stop_if(a)
ops.Print(ops.Const('did not stop'))
b = ops.Const(False)
with ops.stop_guard() as sg2:
ops.stop_if(b)
ops.Print(ops.Const('did not stop'))
ops.Print(sg1.has_stopped(), [])
ops.Print(sg2.has_stopped(), [])
In the example, 'did not stop' will be printed once,
followed by True and False.
"""
return NetBuilder.current().add(
_StopGuard(has_stopped_blob=has_stopped_blob, name=name))
def If(self, cond, name=None):
"""
Creates a NetBuilder that will execute once as the next step of the
current NetBuilder if the blob `cond` is True.
Example:
with ops.If(ops.Const(True)):
ops.Print(ops.Const('Will print'))
with ops.If(ops.Const(False)):
ops.Print(ops.Const('Wont print'))
The example will print 'Will print' once.
"""
return NetBuilder.current().add(_RunIf(cond, name=name))
def IfNet(self, cond, name=None):
"""
Same as If, but uses 'If' operator instead of execution step logic
"""
return NetBuilder.current().add(_RunIfNet(cond, name=name))
def Else(self, name=None):
"""
Else branch of IfNet, has to be specified immediately after IfNet.
Example:
with ops.IfNet(ops.LT([x, y])):
...
with ops.Else():
...
"""
return _RunElseNet(name=name)
def WhileNet(self, name=None):
"""
NetBuilder for 'While' control operator
"""
return NetBuilder.current().add(_RunWhileNet(name=name))
def Condition(self, name=None):
"""
Loop's condition, executed within WhileNet context
"""
assert isinstance(NetBuilder.current(), _RunWhileNet), \
"Use of Condition outside of WhileNet"
return _RunWhileCondition(name=name)
def task_init(self):
"""
Defines operations that will be executed once at task startup.
Useful when implementing processors, that don't have access to the Task
top-level structure.
This setup will be run only once, even if multiple instances of the task
will run in parallel. For instance-local initialization, use
`task_instance_init` instead.
Example:
def my_processor(rec):
with ops.task_init():
one = ops.Const(1)
two = ops.Const(1)
return Tuple(
ops.Add(rec[0](), zero), ops.Add(rec[1](), two))
"""
setup = _SetupBuilder(_SetupBuilder.INIT)
self.net().add_attribute(Task.TASK_SETUP, setup)
return setup
def task_exit(self):
"""
Define operations to be executed once at task shutdown.
Useful when implementing processors, that don't have access to the Task
top-level structure.
This shutdown will be run only once, after all concurrent instances of
the task have already finished. For instance-local shutdown,
use `task_instance_exit` instead.
Example:
def read_queue(queue):
with ops.task_exit():
queue.close(ops.net())
return queue.read(ops.net())
"""
setup = _SetupBuilder(_SetupBuilder.EXIT)
self.net().add_attribute(Task.TASK_SETUP, setup)
return setup
def task_instance_init(self):
"""
Defines operations that will be executed once at startup of each
instance of a task. This can be seen as "thread_local" initialization.
It is guaranteed to run only after all `task_init` logic finishes.
This setup will be run concurrently for each instance of a task.
For global task initialization, use `task_init` instead.
"""
setup = _SetupBuilder(_SetupBuilder.INIT)
self.net().add_attribute(Task.TASK_INSTANCE_SETUP, setup)
return setup
def task_instance_exit(self):
"""
Defines operations that will be executed once at shutdown of each
instance of a task. This can be seen as "thread_local" finalization.
This shutdown will be run concurrently for each instance of a task.
For global task shutdown, use `task_exit` instead.
"""
setup = _SetupBuilder(_SetupBuilder.EXIT)
self.net().add_attribute(Task.TASK_INSTANCE_SETUP, setup)
return setup
def local_init(self):
"""
Similar to `task_init`, but executes at TaskGroup's startup instead,
before any task of the group starts executing. This will run only
once on each node, before initialization of any task, so it can be
used e.g. to initialize blobs shared across tasks.
"""
setup = _SetupBuilder(_SetupBuilder.INIT)
self.net().add_attribute(TaskGroup.LOCAL_SETUP, setup)
return setup
def local_exit(self, name=None):
"""
Similar to `task_exit`, but executes at TaskGroup's exit instead,
after all tasks of the group finished execution.
This will run only once on each node.
"""
setup = _SetupBuilder(_SetupBuilder.EXIT, name)
self.net().add_attribute(TaskGroup.LOCAL_SETUP, setup)
return setup
def task_reporter(self, interval_ms=1000, name=None):
"""
Define operations to be executed at every time interval from
task start-up to finish. These operations are guaranteed to
execute at least once after all other operations of the task are
finished.
Example:
with ops.task_reporter(interval_ms=10000):
ops.LogInfo('10s elapsed')
"""
return _ReporterBuilder(interval_ms, net=self.net(), name=name)
def local_reporter(self, interval_ms=1000, name=None):
"""
Similar to task_report, but operations defined within this block
will run repeatedly for as long as any of the tasks in the current
TaskGroup have not finished.
"""
return _ReporterBuilder(interval_ms, name=name)
ops = Operations()
class _ReporterBuilder(NetBuilder):
def __init__(self, interval_ms, net=None, name=None):
NetBuilder.__init__(self, name)
self._net = net
self.interval_ms = interval_ms
def __exit__(self, etype, *args):
if etype is None:
step = core.to_execution_step(self)
step.RunEveryMillis(self.interval_ms)
if self._net:
self._net.add_attribute(Task.REPORT_STEP, step)
else:
TaskGroup.current().report_step(
step, interval_ms=self.interval_ms)
NetBuilder.__exit__(self, etype, *args)
class _SetupBuilder(NetBuilder):
INIT = 'init'
EXIT = 'exit'
def __init__(self, type, name=None):
NetBuilder.__init__(self, name)
self.type = type
def setup(self, net):
if self.type == _SetupBuilder.INIT:
return core.to_execution_step(self)
def exit(self, net):
if self.type == _SetupBuilder.EXIT:
return core.to_execution_step(self)
class _RunOnce(NetBuilder):
def __init__(self, name=None):
NetBuilder.__init__(self, name)
def __exit__(self, etype, *args):
if etype is None and self._stop_blob is not None:
ops.stop()
NetBuilder.__exit__(self, etype, *args)
class _StopGuard(_RunOnce):
def __init__(self, has_stopped_blob=None, name=None):
_RunOnce.__init__(self, name)
self._stopped = has_stopped_blob
self._ran = False
def __enter__(self):
r = _RunOnce.__enter__(self)
self._stopped = ops.Const(True, blob_out=self._stopped)
return r
def __exit__(self, etype, *args):
if etype is None:
self._ran = True
ops.Const(False, blob_out=self._stopped)
_RunOnce.__exit__(self, etype, *args)
def has_stopped(self):
"""
Return a blob that will be set to scalar bool `True` after
this net builder ran, iff it was halted early.
"""
assert self._ran, 'Context not used yet.'
return self._stopped
class _Loop(NetBuilder):
def __init__(self, iters=None, name=None):
NetBuilder.__init__(self, name, _stop_blob_required=True)
if iters is not None:
self._inc = ops.Const(1)
self._iter = ops.Const(0)
self._num_iters = (
iters if isinstance(iters, core.BlobReference)
else ops.Const(iters))
else:
self._num_iters = None
def iter(self):
assert self._num_iters is not None, (
'This loop does not have a number of iterations.')
assert self._iter is not None, (
'iter() must be called from inside the loop context')
return self._iter
def __enter__(self):
builder = NetBuilder.__enter__(self)
if self._num_iters is not None:
ops.stop_if(ops.GE([self._iter, self._num_iters]))
return builder
def __exit__(self, type, *args):
if type is None and self._num_iters is not None:
self.current_net().Add([self._iter, self._inc], [self._iter])
NetBuilder.__exit__(self, type, *args)
class _RunIf(_RunOnce):
def __init__(self, cond_blob=None, name=None, _already_ran=None):
_RunOnce.__init__(self, name)
assert cond_blob or _already_ran
self._is_else = cond_blob is None
if _already_ran is None:
self._else_blob = ops.Not(cond_blob)
self._already_ran = ops.Const(False)
else:
self._already_ran = _already_ran
self._else_blob = _already_ran if cond_blob is None else (
ops.Or([_already_ran, ops.Not(cond_blob)]))
def __enter__(self):
r = _RunOnce.__enter__(self)
ops.stop_if(self._else_blob)
ops.Const(True, blob_out=self._already_ran)
return r
def Elif(self, cond, name=None):
assert not self._is_else, 'Else not allowed for an Else.'
return NetBuilder.current().add(_RunIf(
cond, name=name or self.name, _already_ran=self._already_ran))
def Else(self, name=None):
assert not self._is_else, 'Elif not allowed for an Else.'
return NetBuilder.current().add(
_RunIf(name=name or self.name, _already_ran=self._already_ran))
class _RunIfNet(NetBuilder):
"""
Generates a single net that uses If operator
"""
def __init__(self, cond_blob, name=None):
NetBuilder.__init__(self, name=name, _use_control_ops=True)
assert cond_blob, 'Conditional blob is not specified for an If net'
self._cond_blob = cond_blob
self._then_net = None
self._else_net = None
def add(self, child):
return NetBuilder.add(self, child)
def __exit__(self, type, *args):
if type is None:
_then_nets = self._children
self._reset_children()
self._then_net = NetBuilder.merge_nets(
_then_nets, self._lexical_scope)
if not self._then_net:
self._then_net = core.Net('empty_then_net')
if_net = core.Net(self.name + '/if_net')
add_if_op(if_net, self._cond_blob, self._lexical_scope,
self._then_net, self._else_net)
self._current_net = if_net
self._children = [if_net]
NetBuilder.__exit__(self, type, *args)
class _RunElseNet(NetBuilder):
"""
Else branch for _RunIfNet builder
"""
def __init__(self, name=None):
NetBuilder.__init__(self, name=name, _use_control_ops=True)
parent = NetBuilder.current(required=False)
assert parent and len(parent._children) > 0 and \
isinstance(parent._children[-1], _RunIfNet), \
'Invalid use of Else builder'
self._if_builder = parent._children[-1]
def __exit__(self, type, *args):
if type is None:
_else_nets = self._children
self._reset_children()
self._if_builder._else_net = NetBuilder.merge_nets(
_else_nets, self._lexical_scope)
if self._if_builder._else_net:
if_else_net = core.Net(self.name + '/if_else_net')
add_if_op(
if_else_net,
self._if_builder._cond_blob,
self._lexical_scope,
self._if_builder._then_net,
self._if_builder._else_net)
self._if_builder._current_net = if_else_net
self._if_builder._children = [if_else_net]
NetBuilder.__exit__(self, type, *args)
class _RunWhileNet(NetBuilder):
"""
Generates a single net that uses While operator
"""
def __init__(self, name=None):
NetBuilder.__init__(self, name=name, _use_control_ops=True)
self._cond_builder = None
def __exit__(self, type, *args):
if type is None:
assert self._cond_builder, \
'Condition builder must be specified in While op'
_cond_blob = self._cond_builder._cond_blob
_cond_net = self._cond_builder._cond_net
loop_body = self._children
self._reset_children()
loop_body_net = NetBuilder.merge_nets(
loop_body, self._lexical_scope)
if not loop_body_net:
loop_body_net = core.Net('empty_loop_body_net')
while_net = core.Net(self.name + '/while_net')
add_while_op(while_net, _cond_blob, self._lexical_scope,
loop_body_net, _cond_net)
self._current_net = while_net
self._children = [while_net]
NetBuilder.__exit__(self, type, *args)
class _RunWhileCondition(NetBuilder):
"""
Computes loop's condition, used in the context of WhileNet.
Last operator must have a single scalar boolean output that will be used
as a condition value, no other blobs created in the condition net are
visible outside of it
"""
def __init__(self, name=None):
NetBuilder.__init__(self, name=name, _use_control_ops=True)
parent = NetBuilder.current(required=False)
assert parent and isinstance(parent, _RunWhileNet), \
'Invalid use of loop condition builder'
assert not parent._cond_builder, \
'Multiple loop condition builders specified'
assert len(parent._children) == 0, \
'Condition definition must be specified before the loop\'s body'
parent._cond_builder = self
self._cond_blob = None
self._cond_net = None
def __exit__(self, type, *args):
if type is None:
condition_body = self._children
self._reset_children()
self._cond_net = NetBuilder.merge_nets(
condition_body, self._lexical_scope)
assert self._cond_net, 'Invalid loop condition specified'
assert len(self._cond_net.Proto().op) > 0, 'Invalid condition net'
last_op = self._cond_net.Proto().op[-1]
assert len(last_op.output) == 1, 'Invalid condition net'
self._cond_blob = core.BlobReference(name=last_op.output[0], net=None)
self._current_net = self._cond_net
self._children = [self._cond_net]
NetBuilder.__exit__(self, type, *args)
|
## @package device_checker
# Module caffe2.python.device_checker
import numpy as np
import copy
from caffe2.python import workspace
from future.utils import viewitems
class DeviceChecker(object):
"""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
will involve a lot of copies back and forth operations. Use at your own risk.
"""
def __init__(self, threshold, device_options):
self._threshold = threshold
self._device_options = device_options
def CheckSimple(self, op, inputs, outputs_to_check,
input_device_options=None):
"""Checks the operator with different device implementations.
Inputs:
op: the operator to be checked.
inputs: the input data in numpy arrays.
outputs_to_check: the outputs to check between devices.
input_device_options: a mapping from input name to a device to use
(instead of self._device_options)
Outputs:
boolean: True if it passes, False if it does not pass.
"""
op = copy.deepcopy(op)
input_device_options = input_device_options or {}
# Entering the checker workspace
old_ws_name = workspace.CurrentWorkspace()
results = []
workspace.SwitchWorkspace("_device_check_", True)
for i, device_option in enumerate(self._device_options):
for i, arr in enumerate(inputs):
workspace.FeedBlob(
op.input[i], np.array(arr),
input_device_options.get(op.input[i], device_option))
op.device_option.CopyFrom(device_option)
workspace.RunOperatorOnce(op)
results.append(
[workspace.FetchBlob(op.output[idx])
for idx in outputs_to_check])
# Everything is done, reset the workspace.
workspace.ResetWorkspace()
# After running on all devices, check correctness
success = True
for i in range(1, len(self._device_options)):
for j in range(len(outputs_to_check)):
x = results[i][j]
y = results[0][j]
if not np.allclose(x, y,
atol=self._threshold, rtol=self._threshold):
print('Failure in checking device option {}'
' and output {}. The outputs are:'
.format(i, op.output[outputs_to_check[j]]))
print(x.flatten())
print(y.flatten())
print(np.max(np.abs(x - y)))
success = False
# else:
# print ('Passed device pair (0, %d), %s %s' %
# (i, outputs_to_check[j], y.shape))
workspace.SwitchWorkspace(old_ws_name)
return success
def CheckNet(self, net, inputs=None, blobs_to_check=None, ignore=None):
"""Checks a network by inspecting all of its intermediate results, and
see if things match.
"""
if inputs is None:
inputs = {}
if ignore is None:
ignore = set()
old_ws_name = workspace.CurrentWorkspace()
results = []
if blobs_to_check is None:
blobs_to_check = sum([list(op.output) for op in net.op], [])
blobs_to_check = [b for b in blobs_to_check if b not in ignore]
workspace.SwitchWorkspace("_device_check_", True)
for device_option in self._device_options:
for name, arr in viewitems(inputs):
# print 'feeding', name
workspace.FeedBlob(name, arr, device_option)
for op in net.op:
op.device_option.CopyFrom(device_option)
workspace.RunNetOnce(net)
results.append(
[workspace.FetchBlob(name) for name in blobs_to_check]
)
# After running on all devices, check correctness
success = True
for i in range(1, len(results)):
for j in range(len(blobs_to_check)):
x = results[i][j]
y = results[0][j]
if not np.allclose(x, y,
atol=self._threshold, rtol=self._threshold):
print('Failure in checking device option {}'
' and output {}. The outputs are:'
.format(i, blobs_to_check[j]))
print(x.flatten())
print(y.flatten())
print(np.max(np.abs(x - y)))
success = False
# else:
# print ('Passed device pair (%d, %d), %s %s: %s' %
# (i, j, blobs_to_check[j], y.shape,
# str(y.flatten())))
workspace.SwitchWorkspace(old_ws_name)
return success
|
## @package context
# Module caffe2.python.context
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import threading
import six
class ContextInfo(object):
def __init__(self, cls, allow_default, arg_name):
self.cls = cls
self.allow_default = allow_default
self.arg_name = arg_name
self._local_stack = threading.local()
@property
def _stack(self):
if not hasattr(self._local_stack, 'obj'):
self._local_stack.obj = []
return self._local_stack.obj
def enter(self, value):
self._stack.append(value)
def exit(self, value):
assert len(self._stack) > 0, 'Context %s is empty.' % self.cls
assert self._stack.pop() == value
def get_active(self, required=True):
if len(self._stack) == 0:
if not required:
return None
assert self.allow_default, (
'Context %s is required but none is active.' % self.cls)
self.enter(self.cls())
return self._stack[-1]
class ContextManager(object):
def __init__(self):
self._ctxs = {}
def register(self, ctx_info):
assert isinstance(ctx_info, ContextInfo)
assert (ctx_info.cls not in self._ctxs), (
'Context %s already registered' % ctx_info.cls)
self._ctxs[ctx_info.cls] = ctx_info
def get(self, cls):
assert cls in self._ctxs, 'Context %s not registered.' % cls
return self._ctxs[cls]
_CONTEXT_MANAGER = ContextManager()
def context_manager():
global _CONTEXT_MANAGER
return _CONTEXT_MANAGER
def __enter__(self):
if self._prev_enter is not None:
self._prev_enter()
context_manager().get(self._ctx_class).enter(self)
return self
def __exit__(self, *args):
context_manager().get(self._ctx_class).exit(self)
if self._prev_exit is not None:
self._prev_exit(*args)
def __call__(self, func):
@six.wraps(func)
def wrapper(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapper
@classmethod
def current(cls, value=None, required=True):
return get_active_context(cls, value, required)
class define_context(object):
def __init__(self, arg_name=None, allow_default=False):
self.arg_name = arg_name
self.allow_default = allow_default
def __call__(self, cls):
assert not hasattr(cls, '_ctx_class'), (
'%s parent class (%s) already defines context.' % (
cls, cls._ctx_class))
context_manager().register(
ContextInfo(cls, self.allow_default, self.arg_name))
cls._prev_enter = cls.__enter__ if hasattr(cls, '__enter__') else None
cls._prev_exit = cls.__exit__ if hasattr(cls, '__exit__') else None
cls._ctx_class = cls
cls.__enter__ = __enter__
cls.__exit__ = __exit__
cls.__call__ = __call__
cls.current = current
return cls
def get_active_context(cls, val=None, required=True):
ctx_info = context_manager().get(cls)
if val is not None:
assert isinstance(val, cls), (
'Wrong context type. Expected: %s, got %s.' % (cls, type(val)))
return val
return ctx_info.get_active(required=required)
|
# This a large test that goes through the translation of the bvlc caffenet
# model, runs an example through the whole model, and verifies numerically
# that all the results look right. In default, it is disabled unless you
# explicitly want to run it.
from caffe.proto import caffe_pb2
from google.protobuf import text_format
import numpy as np
import os
from caffe2.python import caffe_translator, utils, workspace, test_util
import sys
import unittest
@unittest.skipIf(not os.path.exists('data/testdata/caffe_translator'),
'No testdata existing for the caffe translator test. Exiting.')
def setUpModule():
# We will do all the computation stuff in the global space.
caffenet = caffe_pb2.NetParameter()
caffenet_pretrained = caffe_pb2.NetParameter()
text_format.Merge(
open('data/testdata/caffe_translator/deploy.prototxt').read(), caffenet
)
caffenet_pretrained.ParseFromString(
open(
'data/testdata/caffe_translator/bvlc_reference_caffenet.caffemodel')
.read()
)
for remove_legacy_pad in [True, False]:
net, pretrained_params = caffe_translator.TranslateModel(
caffenet, caffenet_pretrained, is_test=True,
remove_legacy_pad=remove_legacy_pad
)
with open('data/testdata/caffe_translator/'
'bvlc_reference_caffenet.translatedmodel',
'w') as fid:
fid.write(str(net))
for param in pretrained_params.protos:
workspace.FeedBlob(param.name, utils.Caffe2TensorToNumpyArray(param))
# Let's also feed in the data from the Caffe test code.
data = np.load('data/testdata/caffe_translator/data_dump.npy').astype(
np.float32)
workspace.FeedBlob('data', data)
# Actually running the test.
workspace.RunNetOnce(net.SerializeToString())
class TestNumericalEquivalence(test_util.TestCase):
def testBlobs(self):
names = [
"conv1", "pool1", "norm1", "conv2", "pool2", "norm2", "conv3",
"conv4", "conv5", "pool5", "fc6", "fc7", "fc8", "prob"
]
for name in names:
print('Verifying {}'.format(name))
caffe2_result = workspace.FetchBlob(name)
reference = np.load(
'data/testdata/caffe_translator/' + name + '_dump.npy'
)
self.assertEqual(caffe2_result.shape, reference.shape)
scale = np.max(caffe2_result)
np.testing.assert_almost_equal(
caffe2_result / scale,
reference / scale,
decimal=5
)
if __name__ == '__main__':
if len(sys.argv) == 1:
print(
'If you do not explicitly ask to run this test, I will not run it. '
'Pass in any argument to have the test run for you.'
)
sys.exit(0)
unittest.main()
|
## @package caffe_translator
# Module caffe2.python.caffe_translator
#!/usr/bin/env python2
import argparse
import copy
import logging
import re
import numpy as np # noqa
from caffe2.proto import caffe2_pb2, caffe2_legacy_pb2
from caffe.proto import caffe_pb2
from caffe2.python import core, utils, workspace
from google.protobuf import text_format
logging.basicConfig()
log = logging.getLogger("caffe_translator")
log.setLevel(logging.INFO)
def _StateMeetsRule(state, rule):
"""A function that reproduces Caffe's StateMeetsRule functionality."""
if rule.HasField('phase') and rule.phase != state.phase:
return False
if rule.HasField('min_level') and state.level < rule.min_level:
return False
if rule.HasField('max_level') and state.level > rule.max_level:
return False
curr_stages = set(list(state.stage))
# all stages in rule.stages should be in, otherwise it's not a match.
if len(rule.stage) and any([s not in curr_stages for s in rule.stage]):
return False
# none of the stage in rule.stages should be in, otherwise it's not a match.
if len(rule.not_stage) and any([s in curr_stages for s in rule.not_stage]):
return False
# If none of the nonmatch happens, return True.
return True
def _ShouldInclude(net_state, layer):
"""A function that reproduces Caffe's inclusion and exclusion rule."""
ret = (len(layer.include) == 0)
# check exclude rules: if any exclusion is met, we shouldn't include.
ret &= not any([_StateMeetsRule(net_state, rule) for rule in layer.exclude])
if len(layer.include):
# check include rules: if any inclusion is met, we should include.
ret |= any([_StateMeetsRule(net_state, rule) for rule in layer.include])
return ret
def _GetLegacyDims(net, net_params, dummy_input, legacy_pad_ops):
dim_map = {}
ws = workspace.C.Workspace()
for param in net_params.protos:
ws.create_blob(param.name) \
.feed(utils.Caffe2TensorToNumpyArray(param))
external_input = net.op[0].input[0]
ws.create_blob(external_input).feed(dummy_input)
# Get dimensions with legacy pad
for i in range(len(net.op)):
op_def = net.op[i]
ws._run_operator(op_def.SerializeToString())
if i in legacy_pad_ops:
output = op_def.output[0]
blob_legacy = ws.fetch_blob(output)
dim_map[i] = blob_legacy.shape
return dim_map
def _GetLegacyPadArgs(op_def, arg_map):
pads = {}
keys = ['pad_l', 'pad_t', 'pad_r', 'pad_b']
is_pad = 'pad' in arg_map
if is_pad:
for k in keys:
pads[k] = arg_map['pad'].i
else:
pads = {x: arg_map[x].i for x in keys}
return pads
def _AdjustDims(op_def, arg_map, pads, dim1, dim2):
n1, c1, h1, w1 = dim1
n2, c2, h2, w2 = dim2
assert(n1 == n2)
assert(c1 == c2)
is_pad = 'pad' in arg_map
if h1 != h2 or w1 != w2:
if h1 == h2 + 1:
pads['pad_b'] += 1
elif h1 != h2:
raise Exception("Unexpected dimensions for height:", h1, h2)
if w1 == w2 + 1:
pads['pad_r'] += 1
elif w1 != w2:
raise Exception("Unexpected dimensions for width:", w1, w2)
if is_pad:
op_def.arg.remove(arg_map['pad'])
args = []
for name in pads.keys():
arg = caffe2_pb2.Argument()
arg.name = name
arg.i = pads[name]
args.append(arg)
op_def.arg.extend(args)
else:
for name in pads.keys():
arg_map[name].i = pads[name]
def _RemoveLegacyPad(net, net_params, input_dims):
legacy_pad_ops = []
for i in range(len(net.op)):
op_def = net.op[i]
if re.match(r'^(Conv|ConvTranspose|MaxPool|AveragePool)(\dD)?$',
op_def.type):
for arg in op_def.arg:
if arg.name == 'legacy_pad':
legacy_pad_ops.append(i)
break
if legacy_pad_ops:
n, c, h, w = input_dims
dummy_input = np.random.randn(n, c, h, w).astype(np.float32)
dim_map = _GetLegacyDims(net, net_params, dummy_input, legacy_pad_ops)
# Running with the legacy pad argument removed
# compare the dimensions and adjust pad argument when necessary
ws = workspace.C.Workspace()
external_input = net.op[0].input[0]
ws.create_blob(external_input).feed_blob(dummy_input)
for param in net_params.protos:
ws.create_blob(param.name) \
.feed_blob(utils.Caffe2TensorToNumpyArray(param))
for i in range(len(net.op)):
op_def = net.op[i]
if i in legacy_pad_ops:
arg_map = {}
for arg in op_def.arg:
arg_map[arg.name] = arg
pads = _GetLegacyPadArgs(op_def, arg_map)
# remove legacy pad arg
for j in range(len(op_def.arg)):
arg = op_def.arg[j]
if arg.name == 'legacy_pad':
del op_def.arg[j]
break
output = op_def.output[0]
# use a new name to avoid the interference with inplace
nonlegacy_output = output + '_nonlegacy'
op_def.output[0] = nonlegacy_output
ws._run_operator(op_def.SerializeToString())
blob_nonlegacy = ws.fetch_blob(nonlegacy_output)
# reset output name
op_def.output[0] = output
dim1 = dim_map[i]
dim2 = blob_nonlegacy.shape
_AdjustDims(op_def, arg_map, pads, dim1, dim2)
ws._run_operator(op_def.SerializeToString())
return net
def _GetBlobDimMap(net, net_params, dummy_input):
dim_map = {}
ws = workspace.C.Workspace()
for param in net_params.protos:
ws.create_blob(param.name) \
.feed(utils.Caffe2TensorToNumpyArray(param))
external_input = net.op[0].input[0]
ws.create_blob(external_input).feed(dummy_input)
# Get dimensions with legacy pad
for i in range(len(net.op)):
op_def = net.op[i]
ws._run_operator(op_def.SerializeToString())
for output in op_def.output:
blob = ws.fetch_blob(output)
dim_map[output] = blob.shape
return dim_map
def _GetInputDims(caffe_net):
input_dims = []
if caffe_net.input_dim:
input_dims = caffe_net.input_dim
elif caffe_net.input_shape:
input_dims = caffe_net.input_shape[0].dim
elif caffe_net.layer[0].input_param.shape:
# getting input dimension from first layer
input_dims = caffe_net.layer[0].input_param.shape[0].dim
return input_dims
class TranslatorRegistry(object):
registry_ = {}
@classmethod
def Register(cls, op_name):
"""A decorator for registering gradient mappings."""
def Wrapper(func):
cls.registry_[op_name] = func
return func
return Wrapper
@classmethod
def TranslateLayer(cls, layer, pretrained_blobs, is_test, **kwargs):
try:
caffe_ops, params = cls.registry_[layer.type](
layer, pretrained_blobs, is_test, **kwargs)
except KeyError:
raise KeyError('No translator registered for layer: %s yet.' %
str(layer))
if caffe_ops is None:
caffe_ops = []
if type(caffe_ops) is not list:
caffe_ops = [caffe_ops]
return caffe_ops, params
@classmethod
def TranslateModel(
cls,
caffe_net,
pretrained_net,
is_test=False,
net_state=None,
remove_legacy_pad=False,
input_dims=None
):
net_state = caffe_pb2.NetState() if net_state is None else net_state
net = caffe2_pb2.NetDef()
net.name = caffe_net.name
net_params = caffe2_pb2.TensorProtos()
if len(caffe_net.layers) > 0:
raise ValueError(
'I think something is wrong. This translation script '
'only accepts new style layers that are stored in the '
'layer field.'
)
if not input_dims:
input_dims = _GetInputDims(caffe_net)
for layer in caffe_net.layer:
if not _ShouldInclude(net_state, layer):
log.info('Current net state does not need layer {}'
.format(layer.name))
continue
log.info('Translate layer {}'.format(layer.name))
# Get pretrained one
pretrained_layers = (
[l for l in pretrained_net.layer
if l.name == layer.name] + [l
for l in pretrained_net.layers
if l.name == layer.name]
)
if len(pretrained_layers) > 1:
raise ValueError(
'huh? more than one pretrained layer of one name?')
elif len(pretrained_layers) == 1:
pretrained_blobs = [
utils.CaffeBlobToNumpyArray(blob)
for blob in pretrained_layers[0].blobs
]
else:
# No pretrained layer for the given layer name. We'll just pass
# no parameter blobs.
# print 'No pretrained layer for layer', layer.name
pretrained_blobs = []
operators, params = cls.TranslateLayer(
layer, pretrained_blobs, is_test, net=net,
net_params=net_params, input_dims=input_dims)
net.op.extend(operators)
net_params.protos.extend(params)
if remove_legacy_pad:
assert input_dims, \
'Please specify input_dims to remove legacy_pad'
net = _RemoveLegacyPad(net, net_params, input_dims)
return net, net_params
def TranslateModel(*args, **kwargs):
return TranslatorRegistry.TranslateModel(*args, **kwargs)
def ConvertTensorProtosToInitNet(net_params, input_name):
"""Takes the net_params returned from TranslateModel, and wrap it as an
init net that contain GivenTensorFill.
This is a very simple feature that only works with float tensors, and is
only intended to be used in an environment where you want a single
initialization file - for more complex cases, use a db to store the
parameters.
"""
init_net = caffe2_pb2.NetDef()
for tensor in net_params.protos:
if len(tensor.float_data) == 0:
raise RuntimeError(
"Only float tensors are supported in this util.")
op = core.CreateOperator(
"GivenTensorFill", [], [tensor.name],
arg=[
utils.MakeArgument("shape", list(tensor.dims)),
utils.MakeArgument("values", tensor.float_data)])
init_net.op.extend([op])
init_net.op.extend([core.CreateOperator("ConstantFill", [], [input_name], shape=[1])])
return init_net
def BaseTranslate(layer, caffe2_type):
"""A simple translate interface that maps the layer input and output."""
caffe2_op = caffe2_pb2.OperatorDef()
caffe2_op.type = caffe2_type
caffe2_op.input.extend(layer.bottom)
caffe2_op.output.extend(layer.top)
return caffe2_op
def AddArgument(op, key, value):
"""Makes an argument based on the value type."""
op.arg.extend([utils.MakeArgument(key, value)])
################################################################################
# Common translators for layers.
################################################################################
@TranslatorRegistry.Register("Input")
def TranslateInput(layer, pretrained_blobs, is_test, **kwargs):
return [], []
@TranslatorRegistry.Register("VideoData")
def TranslateVideoData(layer, pretrained_blobs, is_test, **kwargs):
return [], []
@TranslatorRegistry.Register("Data")
def TranslateData(layer, pretrained_blobs, is_test, **kwargs):
return [], []
# A function used in convolution, pooling and deconvolution to deal with
# conv pool specific parameters.
def _TranslateStridePadKernelHelper(param, caffe_op):
try:
if (len(param.stride) > 1 or len(param.kernel_size) > 1 or
len(param.pad) > 1):
raise NotImplementedError(
"Translator currently does not support non-conventional "
"pad/kernel/stride settings."
)
stride = param.stride[0] if len(param.stride) else 1
pad = param.pad[0] if len(param.pad) else 0
kernel = param.kernel_size[0] if len(param.kernel_size) else 0
except TypeError:
# This catches the case of a PoolingParameter, in which case we are
# having non-repeating pad, stride and kernel.
stride = param.stride
pad = param.pad
kernel = param.kernel_size
# Get stride
if param.HasField("stride_h") or param.HasField("stride_w"):
AddArgument(caffe_op, "stride_h", param.stride_h)
AddArgument(caffe_op, "stride_w", param.stride_w)
else:
AddArgument(caffe_op, "stride", stride)
# Get pad
if param.HasField("pad_h") or param.HasField("pad_w"):
if param.pad_h == param.pad_w:
AddArgument(caffe_op, "pad", param.pad_h)
else:
AddArgument(caffe_op, "pad_t", param.pad_h)
AddArgument(caffe_op, "pad_b", param.pad_h)
AddArgument(caffe_op, "pad_l", param.pad_w)
AddArgument(caffe_op, "pad_r", param.pad_w)
else:
AddArgument(caffe_op, "pad", pad)
# Get kernel
if param.HasField("kernel_h") or param.HasField("kernel_w"):
AddArgument(caffe_op, "kernel_h", param.kernel_h)
AddArgument(caffe_op, "kernel_w", param.kernel_w)
else:
AddArgument(caffe_op, "kernel", kernel)
@TranslatorRegistry.Register("Convolution3D")
def TranslateConvNd(layer, pretrained_blobs, is_test, **kwargs):
param = layer.convolution3d_param
caffe_op = BaseTranslate(layer, "Conv")
output = caffe_op.output[0]
caffe_op.input.append(output + '_w')
AddArgument(
caffe_op,
"kernels",
[param.kernel_depth, param.kernel_size, param.kernel_size])
AddArgument(
caffe_op,
"strides",
[param.temporal_stride, param.stride, param.stride])
temporal_pad = 0
spatial_pad = 0
if hasattr(param, 'temporal_pad'):
temporal_pad = param.temporal_pad
if hasattr(param, 'pad'):
spatial_pad = param.pad
AddArgument(caffe_op, "pads", [temporal_pad, spatial_pad, spatial_pad] * 2)
# weight
params = [
utils.NumpyArrayToCaffe2Tensor(pretrained_blobs[0], output + '_w')]
# bias
if len(pretrained_blobs) == 2:
caffe_op.input.append(output + '_b')
params.append(
utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[1].flatten(), output + '_b'))
return caffe_op, params
@TranslatorRegistry.Register("Convolution")
def TranslateConv(layer, pretrained_blobs, is_test, **kwargs):
param = layer.convolution_param
caffe_op = BaseTranslate(layer, "Conv")
output = caffe_op.output[0]
caffe_op.input.append(output + '_w')
_TranslateStridePadKernelHelper(param, caffe_op)
# weight
params = [
utils.NumpyArrayToCaffe2Tensor(pretrained_blobs[0], output + '_w')]
# bias
if len(pretrained_blobs) == 2:
caffe_op.input.append(output + '_b')
params.append(
utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[1].flatten(), output + '_b'))
# Group convolution option
if param.group != 1:
AddArgument(caffe_op, "group", param.group)
# Get dilation - not tested. If you have a model and this checks out,
# please provide a test and uncomment this.
if len(param.dilation) > 0:
if len(param.dilation) == 1:
AddArgument(caffe_op, "dilation", param.dilation[0])
elif len(param.dilation) == 2:
AddArgument(caffe_op, "dilation_h", param.dilation[0])
AddArgument(caffe_op, "dilation_w", param.dilation[1])
return caffe_op, params
@TranslatorRegistry.Register("Deconvolution")
def TranslateDeconv(layer, pretrained_blobs, is_test, **kwargs):
param = layer.convolution_param
if param.group > 1:
raise NotImplementedError(
"Translator currently does not support group deconvolution."
)
caffe_op = BaseTranslate(layer, "ConvTranspose")
output = caffe_op.output[0]
_TranslateStridePadKernelHelper(param, caffe_op)
caffe_op.input.extend([output + '_w'])
AddArgument(caffe_op, "order", "NCHW")
weight = utils.NumpyArrayToCaffe2Tensor(pretrained_blobs[0], output + '_w')
if param.bias_term:
bias = utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[1].flatten(), output + '_b'
)
caffe_op.input.extend([output + '_b'])
return caffe_op, [weight, bias]
else:
return caffe_op, [weight]
@TranslatorRegistry.Register("Crop")
def TranslateCrop(layer, pretrained_blobs, is_test, **kwargs):
net, net_params, input_dims = kwargs['net'], kwargs['net_params'], kwargs['input_dims']
n, c, h, w = input_dims
dummy_input = np.random.randn(n, c, h, w).astype(np.float32)
dim_map = _GetBlobDimMap(net, net_params, dummy_input)
param = layer.crop_param
axis, offsets = param.axis, param.offset
caffe_op = BaseTranslate(layer, "Slice")
input_1 = caffe_op.input[1]
input_1_dim = dim_map[input_1]
starts, ends = [], []
dims = len(dim_map[input_1])
assert len(offsets) == 1, 'Caffe Translator for Crop only works for offset \
of 1 for now'
for _ in range(axis):
starts.append(0)
ends.append(-1)
end_offset = [int(offsets[0] + input_1_dim[i]) for i in range(axis, dims)]
ends.extend(end_offset)
starts.extend([offsets[0]] * len(end_offset))
op = caffe2_pb2.OperatorDef()
op.input.extend([caffe_op.input[0]])
op.output.extend(caffe_op.output)
op.arg.extend(caffe_op.arg)
op.type = caffe_op.type
AddArgument(op, "starts", starts)
AddArgument(op, "ends", ends)
return op, []
@TranslatorRegistry.Register("ReLU")
def TranslateRelu(layer, pretrained_blobs, is_test, **kwargs):
return BaseTranslate(layer, "Relu"), []
@TranslatorRegistry.Register("Pooling")
def TranslatePool(layer, pretrained_blobs, is_test, **kwargs):
param = layer.pooling_param
if param.pool == caffe_pb2.PoolingParameter.MAX:
caffe_op = BaseTranslate(layer, "MaxPool")
elif param.pool == caffe_pb2.PoolingParameter.AVE:
caffe_op = BaseTranslate(layer, "AveragePool")
_TranslateStridePadKernelHelper(param, caffe_op)
AddArgument(caffe_op, "order", "NCHW")
try:
# In the Facebook port of Caffe, a torch_pooling field was added to
# map the pooling computation of Torch. Essentially, it uses
# floor((height + 2 * padding - kernel) / stride) + 1
# instead of
# ceil((height + 2 * padding - kernel) / stride) + 1
# which is Caffe's version.
# Torch pooling is actually the same as Caffe2 pooling, so we don't
# need to do anything.
is_torch_pooling = param.torch_pooling
except AttributeError:
is_torch_pooling = False
if not is_torch_pooling:
AddArgument(caffe_op, "legacy_pad",
caffe2_legacy_pb2.CAFFE_LEGACY_POOLING)
if param.global_pooling:
AddArgument(caffe_op, "global_pooling", 1)
return caffe_op, []
@TranslatorRegistry.Register("Pooling3D")
def TranslatePool3D(layer, pretrained_blobs, is_test, **kwargs):
param = layer.pooling3d_param
if param.pool == caffe_pb2.Pooling3DParameter.MAX:
caffe_op = BaseTranslate(layer, "MaxPool")
elif param.pool == caffe_pb2.Pooling3DParameter.AVE:
caffe_op = BaseTranslate(layer, "AveragePool")
AddArgument(caffe_op, "order", "NCHW")
AddArgument(
caffe_op,
"kernels",
[param.kernel_depth, param.kernel_size, param.kernel_size])
AddArgument(
caffe_op,
"strides",
[param.temporal_stride, param.stride, param.stride])
temporal_pad = 0
spatial_pad = 0
if hasattr(param, 'temporal_pad'):
temporal_pad = param.temporal_pad
if hasattr(param, 'pad'):
spatial_pad = param.pad
AddArgument(caffe_op, "pads", [temporal_pad, spatial_pad, spatial_pad] * 2)
return caffe_op, []
@TranslatorRegistry.Register("LRN")
def TranslateLRN(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "LRN")
caffe_op.output.extend(['_' + caffe_op.output[0] + '_scale'])
param = layer.lrn_param
if param.norm_region != caffe_pb2.LRNParameter.ACROSS_CHANNELS:
raise ValueError(
"Does not support norm region other than across channels.")
AddArgument(caffe_op, "size", int(param.local_size))
AddArgument(caffe_op, "alpha", float(param.alpha))
AddArgument(caffe_op, "beta", float(param.beta))
AddArgument(caffe_op, "bias", float(param.k))
AddArgument(caffe_op, "order", "NCHW")
return caffe_op, []
@TranslatorRegistry.Register("InnerProduct")
def TranslateInnerProduct(layer, pretrained_blobs, is_test, **kwargs):
param = layer.inner_product_param
try:
if param.axis != 1 or param.transpose:
raise ValueError(
"We don't have testing case for non-default axis and transpose "
"cases yet so we are disabling it for now. If you have a model "
"with this, please do send us your model for us to update this "
"support, and you are more than welcome to send a PR for this.")
except AttributeError:
# We might be using an historic Caffe protobuf that does not have axis
# and transpose arguments, so we will silently pass.
pass
caffe_op = BaseTranslate(layer, "FC")
output = caffe_op.output[0]
caffe_op.input.extend([output + '_w', output + '_b'])
# To provide the old-style 4-dimensional blob (1, 1, dim_output, dim_input)
# case, we always explicitly reshape the pretrained blob.
if pretrained_blobs[0].ndim not in [2, 4]:
raise ValueError("Unexpected weight ndim.")
if (pretrained_blobs[0].ndim == 4 and
list(pretrained_blobs[0].shape[:2]) != [1, 1]):
raise ValueError(
"If pretrained blob has 4 dims (old-style Caffe), the first two "
"should be of value 1, but I got " + str(pretrained_blobs[0].shape))
weight = utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[0].reshape(-1, pretrained_blobs[0].shape[-1]),
output + '_w'
)
bias = utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[1].flatten(), output + '_b'
)
return caffe_op, [weight, bias]
@TranslatorRegistry.Register("Dropout")
def TranslateDropout(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Dropout")
caffe_op.output.extend(['_' + caffe_op.output[0] + '_mask'])
param = layer.dropout_param
AddArgument(caffe_op, "ratio", param.dropout_ratio)
if (is_test):
AddArgument(caffe_op, "is_test", 1)
return caffe_op, []
@TranslatorRegistry.Register("Softmax")
def TranslateSoftmax(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Softmax")
return caffe_op, []
@TranslatorRegistry.Register("SoftmaxWithLoss")
def TranslateSoftmaxWithLoss(layer, pretrained_blobs, is_test, **kwargs):
softmax_op = core.CreateOperator(
"Softmax", [layer.bottom[0]],
layer.bottom[0] + "_translator_autogen_softmax")
xent_op = core.CreateOperator(
"LabelCrossEntropy",
[softmax_op.output[0], layer.bottom[1]],
layer.bottom[0] + "_translator_autogen_xent")
loss_op = core.CreateOperator(
"AveragedLoss",
xent_op.output[0],
layer.top[0])
return [softmax_op, xent_op, loss_op], []
@TranslatorRegistry.Register("Accuracy")
def TranslateAccuracy(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Accuracy")
if layer.accuracy_param.top_k != 1:
AddArgument(caffe_op, "top_k", layer.accuracy_param.top_k)
return caffe_op, []
@TranslatorRegistry.Register("Concat")
def TranslateConcat(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Concat")
caffe_op.output.extend(['_' + caffe_op.output[0] + '_dims'])
AddArgument(caffe_op, "order", "NCHW")
return caffe_op, []
@TranslatorRegistry.Register("TanH")
def TranslateTanH(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Tanh")
return caffe_op, []
@TranslatorRegistry.Register("InstanceNorm")
def TranslateInstanceNorm(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "InstanceNorm")
output = caffe_op.output[0]
weight = utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[0].flatten(), output + '_w')
bias = utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[1].flatten(), output + '_b')
caffe_op.input.extend([output + '_w', output + '_b'])
AddArgument(caffe_op, "order", "NCHW")
return caffe_op, [weight, bias]
@TranslatorRegistry.Register("BatchNorm")
def TranslateBatchNorm(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "SpatialBN")
output = caffe_op.output[0]
param = layer.batch_norm_param
AddArgument(caffe_op, "is_test", is_test)
AddArgument(caffe_op, "epsilon", param.eps)
AddArgument(caffe_op, "order", "NCHW")
caffe_op.input.extend(
[output + "_scale",
output + "_bias",
output + "_mean",
output + "_var"])
if not is_test:
caffe_op.output.extend(
[output + "_mean",
output + "_var",
output + "_saved_mean",
output + "_saved_var"])
n_channels = pretrained_blobs[0].shape[0]
if pretrained_blobs[2][0] != 0:
mean = utils.NumpyArrayToCaffe2Tensor(
(1. / pretrained_blobs[2][0]) * pretrained_blobs[0],
output + '_mean')
var = utils.NumpyArrayToCaffe2Tensor(
(1. / pretrained_blobs[2][0]) * pretrained_blobs[1],
output + '_var')
else:
raise RuntimeError("scalar is zero.")
pretrained_blobs[2][0] = 1
pretrained_blobs[2] = np.tile(pretrained_blobs[2], (n_channels, ))
scale = utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[2],
output + '_scale')
bias = utils.NumpyArrayToCaffe2Tensor(
np.zeros_like(pretrained_blobs[2]),
output + '_bias')
return caffe_op, [scale, bias, mean, var]
@TranslatorRegistry.Register("Eltwise")
def TranslateElementWise(layer, pretrained_blobs, is_test, **kwargs):
param = layer.eltwise_param
# TODO(jiayq): if we have a protobuf that uses this, lift this constraint
# and verify that we can correctly translate.
if len(param.coeff) or param.operation != 1:
raise RuntimeError("This eltwise layer is not yet supported.")
caffe_op = BaseTranslate(layer, "Sum")
return caffe_op, []
@TranslatorRegistry.Register("Scale")
def TranslateScale(layer, pretrained_blobs, is_test, **kwargs):
mul_op = BaseTranslate(layer, "Mul")
scale_param = layer.scale_param
AddArgument(mul_op, "axis", scale_param.axis)
AddArgument(mul_op, "broadcast", True)
if len(mul_op.input) == 1:
# the scale parameter is in pretrained blobs
if scale_param.num_axes != 1:
raise RuntimeError("This path has not been verified yet.")
output = mul_op.output[0]
mul_op_param = output + '_w'
mul_op.input.append(mul_op_param)
weights = []
weights.append(utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[0].flatten(), mul_op_param))
add_op = None
if len(pretrained_blobs) == 1:
# No bias-term in Scale layer
pass
elif len(pretrained_blobs) == 2:
# Caffe Scale layer supports a bias term such that it computes
# (scale_param * X + bias), whereas Caffe2 Mul op doesn't.
# Include a separate Add op for the bias followed by Mul.
add_op = copy.deepcopy(mul_op)
add_op.type = "Add"
add_op_param = output + '_b'
internal_blob = output + "_internal"
del mul_op.output[:]
mul_op.output.append(internal_blob)
del add_op.input[:]
add_op.input.append(internal_blob)
add_op.input.append(add_op_param)
weights.append(utils.NumpyArrayToCaffe2Tensor(
pretrained_blobs[1].flatten(), add_op_param))
else:
raise RuntimeError("Unexpected number of pretrained blobs in Scale")
caffe_ops = [mul_op]
if add_op:
caffe_ops.append(add_op)
assert len(caffe_ops) == len(weights)
return caffe_ops, weights
elif len(mul_op.input) == 2:
# TODO(jiayq): find a protobuf that uses this and verify.
raise RuntimeError("This path has not been verified yet.")
else:
raise RuntimeError("Unexpected number of inputs.")
@TranslatorRegistry.Register("Reshape")
def TranslateReshape(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Reshape")
caffe_op.output.append("_" + caffe_op.input[0] + "_dims")
reshape_param = layer.reshape_param
AddArgument(caffe_op, 'shape', reshape_param.shape.dim)
return caffe_op, []
@TranslatorRegistry.Register("Flatten")
def TranslateFlatten(layer, pretrained_blobs, is_test, **kwargs):
param = layer.flatten_param
if param.end_axis != -1:
raise NotImplementedError("flatten_param.end_axis not supported yet.")
if param.axis == 0:
caffe_op = BaseTranslate(layer, "FlattenToVec")
elif param.axis == 1:
caffe_op = BaseTranslate(layer, "Flatten")
else:
# This could be a Reshape op, but dim size is not known here.
raise NotImplementedError(
"Not supported yet for flatten_param.axis {}.".format(param.axis))
return caffe_op, []
@TranslatorRegistry.Register("Sigmoid")
def TranslateSigmoid(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "Sigmoid")
return caffe_op, []
@TranslatorRegistry.Register("ROIPooling")
def TranslateROIPooling(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "RoIPool")
AddArgument(caffe_op, "order", "NCHW")
if is_test:
AddArgument(caffe_op, "is_test", is_test)
else:
# Only used for gradient computation
caffe_op.output.append(caffe_op.output[0] + '_argmaxes')
param = layer.roi_pooling_param
if param.HasField('pooled_h'):
AddArgument(caffe_op, 'pooled_h', param.pooled_h)
if param.HasField('pooled_w'):
AddArgument(caffe_op, 'pooled_w', param.pooled_w)
if param.HasField('spatial_scale'):
AddArgument(caffe_op, 'spatial_scale', param.spatial_scale)
return caffe_op, []
@TranslatorRegistry.Register("PReLU")
def TranslatePRelu(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, "PRelu")
output = caffe_op.output[0]
caffe_op.input.extend([output + '_Slope'])
slope = utils.NumpyArrayToCaffe2Tensor(pretrained_blobs[0], output + '_Slope')
return caffe_op, [slope]
@TranslatorRegistry.Register("Reduction")
def TranslateReduction(layer, pretrained_blobs, is_test, **kwargs):
param = layer.reduction_param
if param.operation == caffe_pb2.ReductionParameter.SUM:
caffe_op = BaseTranslate(layer, "ReduceBackSum")
elif param.operation == caffe_pb2.ReductionParameter.MEAN:
caffe_op = BaseTranslate(layer, "ReduceBackMean")
else:
raise NotImplementedError("Not yet supported")
if param.axis > 0:
# We can't figure out the number of dims to reduce from positive axis
# for back reduction since the shape info is not known here.
raise NotImplementedError("Not yet supported")
num_reduce_dim = -param.axis
AddArgument(caffe_op, "num_reduce_dim", num_reduce_dim)
return caffe_op, []
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Utilitity to convert pretrained caffe models to Caffe2 models.")
parser.add_argument("prototext", help="Caffe prototext.")
parser.add_argument("caffemodel", help="Caffe trained model.")
parser.add_argument("--init_net", help="Caffe2 initialization net.",
default="init_net.pb")
parser.add_argument("--predict_net", help="Caffe2 prediction net.",
default="predict_net.pb")
parser.add_argument("--remove_legacy_pad", help="Remove legacy pad \
(Only works for nets with one input blob)",
action="store_true",
default=False)
parser.add_argument("--input_dims", help="Dimension of input blob", nargs='+',
type=int, default=[])
args = parser.parse_args()
caffenet = caffe_pb2.NetParameter()
caffenet_pretrained = caffe_pb2.NetParameter()
input_proto = args.prototext
input_caffemodel = args.caffemodel
output_init_net = args.init_net
output_predict_net = args.predict_net
text_format.Merge(
open(input_proto, 'r').read(), caffenet
)
caffenet_pretrained.ParseFromString(
open(input_caffemodel, 'rb').read()
)
net, pretrained_params = TranslateModel(
caffenet, caffenet_pretrained, is_test=True,
remove_legacy_pad=args.remove_legacy_pad,
input_dims=args.input_dims
)
# Assume there is one input and one output
external_input = net.op[0].input[0]
external_output = net.op[-1].output[0]
net.external_input.extend([external_input])
net.external_input.extend([param.name for param in pretrained_params.protos])
net.external_output.extend([external_output])
init_net = ConvertTensorProtosToInitNet(pretrained_params, external_input)
with open(output_predict_net, 'wb') as f:
f.write(net.SerializeToString())
with open(output_predict_net + 'txt', 'w') as f:
f.write(str(net))
with open(output_init_net, 'wb') as f:
f.write(init_net.SerializeToString())
|
## @package utils
# Module caffe2.python.utils
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from future.utils import viewitems
from google.protobuf.message import DecodeError, Message
from google.protobuf import text_format
import sys
import copy
import collections
import functools
import numpy as np
from six import integer_types, binary_type, text_type
def OpAlmostEqual(op_a, op_b, ignore_fields=None):
'''
Two ops are identical except for each field in the `ignore_fields`.
'''
ignore_fields = ignore_fields or []
if not isinstance(ignore_fields, list):
ignore_fields = [ignore_fields]
assert all(isinstance(f, text_type) for f in ignore_fields), (
'Expect each field is text type, but got {}'.format(ignore_fields))
def clean_op(op):
op = copy.deepcopy(op)
for field in ignore_fields:
if op.HasField(field):
op.ClearField(field)
return op
op_a = clean_op(op_a)
op_b = clean_op(op_b)
return op_a == op_b
def CaffeBlobToNumpyArray(blob):
if (blob.num != 0):
# old style caffe blob.
return (np.asarray(blob.data, dtype=np.float32)
.reshape(blob.num, blob.channels, blob.height, blob.width))
else:
# new style caffe blob.
return (np.asarray(blob.data, dtype=np.float32)
.reshape(blob.shape.dim))
def Caffe2TensorToNumpyArray(tensor):
if tensor.data_type == caffe2_pb2.TensorProto.FLOAT:
return np.asarray(
tensor.float_data, dtype=np.float32).reshape(tensor.dims)
elif tensor.data_type == caffe2_pb2.TensorProto.DOUBLE:
return np.asarray(
tensor.double_data, dtype=np.float64).reshape(tensor.dims)
elif tensor.data_type == caffe2_pb2.TensorProto.INT32:
return np.asarray(
tensor.int32_data, dtype=np.int).reshape(tensor.dims) # pb.INT32=>np.int use int32_data
elif tensor.data_type == caffe2_pb2.TensorProto.INT16:
return np.asarray(
tensor.int32_data, dtype=np.int16).reshape(tensor.dims) # pb.INT16=>np.int16 use int32_data
elif tensor.data_type == caffe2_pb2.TensorProto.UINT16:
return np.asarray(
tensor.int32_data, dtype=np.uint16).reshape(tensor.dims) # pb.UINT16=>np.uint16 use int32_data
elif tensor.data_type == caffe2_pb2.TensorProto.INT8:
return np.asarray(
tensor.int32_data, dtype=np.int8).reshape(tensor.dims) # pb.INT8=>np.int8 use int32_data
elif tensor.data_type == caffe2_pb2.TensorProto.UINT8:
return np.asarray(
tensor.int32_data, dtype=np.uint8).reshape(tensor.dims) # pb.UINT8=>np.uint8 use int32_data
else:
# TODO: complete the data type: bool, float16, byte, int64, string
raise RuntimeError(
"Tensor data type not supported yet: " + str(tensor.data_type))
def NumpyArrayToCaffe2Tensor(arr, name=None):
tensor = caffe2_pb2.TensorProto()
tensor.dims.extend(arr.shape)
if name:
tensor.name = name
if arr.dtype == np.float32:
tensor.data_type = caffe2_pb2.TensorProto.FLOAT
tensor.float_data.extend(list(arr.flatten().astype(float)))
elif arr.dtype == np.float64:
tensor.data_type = caffe2_pb2.TensorProto.DOUBLE
tensor.double_data.extend(list(arr.flatten().astype(np.float64)))
elif arr.dtype == np.int or arr.dtype == np.int32:
tensor.data_type = caffe2_pb2.TensorProto.INT32
tensor.int32_data.extend(arr.flatten().astype(np.int).tolist())
elif arr.dtype == np.int16:
tensor.data_type = caffe2_pb2.TensorProto.INT16
tensor.int32_data.extend(list(arr.flatten().astype(np.int16))) # np.int16=>pb.INT16 use int32_data
elif arr.dtype == np.uint16:
tensor.data_type = caffe2_pb2.TensorProto.UINT16
tensor.int32_data.extend(list(arr.flatten().astype(np.uint16))) # np.uint16=>pb.UNIT16 use int32_data
elif arr.dtype == np.int8:
tensor.data_type = caffe2_pb2.TensorProto.INT8
tensor.int32_data.extend(list(arr.flatten().astype(np.int8))) # np.int8=>pb.INT8 use int32_data
elif arr.dtype == np.uint8:
tensor.data_type = caffe2_pb2.TensorProto.UINT8
tensor.int32_data.extend(list(arr.flatten().astype(np.uint8))) # np.uint8=>pb.UNIT8 use int32_data
else:
# TODO: complete the data type: bool, float16, byte, int64, string
raise RuntimeError(
"Numpy data type not supported yet: " + str(arr.dtype))
return tensor
def MakeArgument(key, value):
"""Makes an argument based on the value type."""
argument = caffe2_pb2.Argument()
argument.name = key
iterable = isinstance(value, collections.Iterable)
# Fast tracking common use case where a float32 array of tensor parameters
# needs to be serialized. The entire array is guaranteed to have the same
# dtype, so no per-element checking necessary and no need to convert each
# element separately.
if isinstance(value, np.ndarray) and value.dtype.type is np.float32:
argument.floats.extend(value.flatten().tolist())
return argument
if isinstance(value, np.ndarray):
value = value.flatten().tolist()
elif isinstance(value, np.generic):
# convert numpy scalar to native python type
value = np.asscalar(value)
if type(value) is float:
argument.f = value
elif type(value) in integer_types or type(value) is bool:
# We make a relaxation that a boolean variable will also be stored as
# int.
argument.i = value
elif isinstance(value, binary_type):
argument.s = value
elif isinstance(value, text_type):
argument.s = value.encode('utf-8')
elif isinstance(value, caffe2_pb2.NetDef):
argument.n.CopyFrom(value)
elif isinstance(value, Message):
argument.s = value.SerializeToString()
elif iterable and all(type(v) in [float, np.float_] for v in value):
argument.floats.extend(
v.item() if type(v) is np.float_ else v for v in value
)
elif iterable and all(
type(v) in integer_types or type(v) in [bool, np.int_] for v in value
):
argument.ints.extend(
v.item() if type(v) is np.int_ else v for v in value
)
elif iterable and all(
isinstance(v, binary_type) or isinstance(v, text_type) for v in value
):
argument.strings.extend(
v.encode('utf-8') if isinstance(v, text_type) else v
for v in value
)
elif iterable and all(isinstance(v, caffe2_pb2.NetDef) for v in value):
argument.nets.extend(value)
elif iterable and all(isinstance(v, Message) for v in value):
argument.strings.extend(v.SerializeToString() for v in value)
else:
if iterable:
raise ValueError(
"Unknown iterable argument type: key={} value={}, value "
"type={}[{}]".format(
key, value, type(value), set(type(v) for v in value)
)
)
else:
raise ValueError(
"Unknown argument type: key={} value={}, value type={}".format(
key, value, type(value)
)
)
return argument
def TryReadProtoWithClass(cls, s):
"""Reads a protobuffer with the given proto class.
Inputs:
cls: a protobuffer class.
s: a string of either binary or text protobuffer content.
Outputs:
proto: the protobuffer of cls
Throws:
google.protobuf.message.DecodeError: if we cannot decode the message.
"""
obj = cls()
try:
text_format.Parse(s, obj)
return obj
except text_format.ParseError:
obj.ParseFromString(s)
return obj
def GetContentFromProto(obj, function_map):
"""Gets a specific field from a protocol buffer that matches the given class
"""
for cls, func in viewitems(function_map):
if type(obj) is cls:
return func(obj)
def GetContentFromProtoString(s, function_map):
for cls, func in viewitems(function_map):
try:
obj = TryReadProtoWithClass(cls, s)
return func(obj)
except DecodeError:
continue
else:
raise DecodeError("Cannot find a fit protobuffer class.")
def ConvertProtoToBinary(proto_class, filename, out_filename):
"""Convert a text file of the given protobuf class to binary."""
proto = TryReadProtoWithClass(proto_class, open(filename).read())
with open(out_filename, 'w') as fid:
fid.write(proto.SerializeToString())
def GetGPUMemoryUsageStats():
"""Get GPU memory usage stats from CUDAContext. This requires flag
--caffe2_gpu_memory_tracking to be enabled"""
from caffe2.python import workspace, core
workspace.RunOperatorOnce(
core.CreateOperator(
"GetGPUMemoryUsage",
[],
["____mem____"],
device_option=core.DeviceOption(caffe2_pb2.CUDA, 0),
),
)
b = workspace.FetchBlob("____mem____")
return {
'total_by_gpu': b[0, :],
'max_by_gpu': b[1, :],
'total': np.sum(b[0, :]),
'max_total': np.sum(b[1, :])
}
def ResetBlobs(blobs):
from caffe2.python import workspace, core
workspace.RunOperatorOnce(
core.CreateOperator(
"Free",
list(blobs),
list(blobs),
device_option=core.DeviceOption(caffe2_pb2.CPU),
),
)
class DebugMode(object):
'''
This class allows to drop you into an interactive debugger
if there is an unhandled exception in your python script
Example of usage:
def main():
# your code here
pass
if __name__ == '__main__':
from caffe2.python.utils import DebugMode
DebugMode.run(main)
'''
@classmethod
def run(cls, func):
try:
return func()
except KeyboardInterrupt:
raise
except Exception:
import pdb
print(
'Entering interactive debugger. Type "bt" to print '
'the full stacktrace. Type "help" to see command listing.')
print(sys.exc_info()[1])
print
pdb.post_mortem()
sys.exit(1)
raise
def raiseIfNotEqual(a, b, msg):
if a != b:
raise Exception("{}. {} != {}".format(msg, a, b))
def debug(f):
'''
Use this method to decorate your function with DebugMode's functionality
Example:
@debug
def test_foo(self):
raise Exception("Bar")
'''
@functools.wraps(f)
def wrapper(*args, **kwargs):
def func():
return f(*args, **kwargs)
DebugMode.run(func)
return wrapper
|
## @package pipeline
# Module caffe2.python.pipeline
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, queue_util
from caffe2.python.dataio import Reader, Writer
from caffe2.python.net_builder import NetBuilder, ops
from caffe2.python.schema import as_record, Field
from caffe2.python.task import Node, Task, TaskGroup
class Output(object):
"""
Represents the result of a processor function. A processor can either
return an Output, or it can return a record, in which case an Output will be
created for it afterwards.
"""
def __init__(self, nets=None, record=None, should_stop=None):
builder_children = NetBuilder.current().get()
assert nets is None or len(builder_children) == 0, (
'Cannot both use `ops` syntax and return a list of nets.')
if nets is None:
nets = builder_children
if isinstance(nets, core.Net):
nets = [nets]
self.nets = [] if nets is None else list(nets)
self.record = None if record is None else as_record(record)
self.should_stop = should_stop
DEFAULT_QUEUE_CAPACITY = 100
def _init_output(output, capacity, global_init_net, global_exit_net):
if output is None:
out_queue = queue_util.Queue(
capacity=(
capacity if capacity is not None
else DEFAULT_QUEUE_CAPACITY))
writer = out_queue.writer()
elif isinstance(output, Writer):
assert capacity is None, 'capacity would not be used.'
out_queue = None
writer = output
elif hasattr(output, 'writer'):
assert capacity is None, 'capacity would not be used.'
out_queue = output
writer = output.writer()
else:
raise ValueError('output must be a reader, queue or stream.')
writer.setup_ex(global_init_net, global_exit_net)
return out_queue, writer
def make_processor(processor):
if processor is None:
return lambda rec: rec
elif isinstance(processor, core.Net):
return NetProcessor(processor)
else:
return processor
def normalize_processor_output(output):
"""
Allow for processors to return results in several formats.
TODO(azzolini): simplify once all processors use NetBuilder API.
"""
if isinstance(output, Output):
""" Processor returned an Output. """
return output
elif isinstance(output, Field):
""" Processor returned a record. """
return Output(record=output)
elif isinstance(output, tuple):
is_record_and_blob = (
len(output) == 2 and
isinstance(output[0], Field) and
isinstance(output[1], core.BlobReference))
if is_record_and_blob:
""" Processor returned (record, stop_blob) """
return Output(None, *output)
else:
""" Processor returned (nets, record, stop_blob) """
return Output(*output)
else:
""" Processor returned nets, no output """
return Output(output)
def pipe(
input, output=None, num_threads=1, processor=None, name=None,
capacity=None, group=None, num_runtime_threads=1):
"""
Given a Reader, Queue or DataStream in `input`, and optionally, a Writer,
Queue or DataStream in `output`, creates a Task that, when run, will
pipe the input into the output, using multiple parallel threads.
Additionally, if a processor is given, it will be called between reading
and writing steps, allowing it to transform the record.
Args:
input: either a Reader, Queue or DataStream that will be read
until a stop is signaled either by the reader or the
writer.
output: either a Writer, a Queue or a DataStream that will be
writen to as long as neither reader nor writer signal
a stop condition. If output is not provided or is None,
a Queue is created with given `capacity` and writen to.
num_threads: number of concurrent threads used for processing and
piping. If set to 0, no Task is created, and a
reader is returned instead -- the reader returned will
read from the reader passed in and process it.
** DEPRECATED **. Use `num_runtime_threads` instead.
This option will be removed once all readers/processors
support `num_runtime_threads`.
processor: (optional) function that takes an input record and
optionally returns a record; this will be called
between read and write steps. If the processor does
not return a record, a writer will not be instantiated.
Processor can also be a core.Net with input and output
records properly set. In that case, a NetProcessor is
instantiated, cloning the net for each of the threads.
name: (optional) name of the task to be created.
capacity: when output is not passed, a queue of given `capacity`
is created and written to.
group: (optional) explicitly add the created Task to this
TaskGroup, instead of using the currently active one.
num_runtime_threads: Similar to `num_threads`, but instead of expanding
the tasks with a `for` loop in python, does that at
runtime. This is preferable to `num_threads`, but some
processors/readers still require to be called multiple
times in python.
Returns:
Output Queue, DataStream, Reader, or None, depending on the parameters
passed.
"""
result, _ = _pipe_step(
input, output, num_threads, processor, name, capacity, group,
num_runtime_threads)
return result
def pipe_and_output(
input, output=None, num_threads=1, processor=None, name=None,
capacity=None, group=None, num_runtime_threads=1, final_outputs=None):
"""
Similar to `pipe`, with the additional ability for the pipe Task to
return output values to the `Session` once done.
Returns:
Tuple (out_queue, *task_outputs)
out_queue: same as return value of `pipe`.
task_outputs: TaskOutput object, fetchable from the client after
session.run() returns.
"""
assert num_threads > 0
result, task = _pipe_step(
input, output, num_threads, processor, name, capacity, group,
num_runtime_threads, final_outputs)
output = None
if final_outputs is not None:
output = task.outputs()
if type(final_outputs) not in (list, tuple):
output = output[0]
return result, output
def processor_name(processor):
if hasattr(processor, 'name'):
return processor.name
if hasattr(processor, 'func_name'):
if processor.func_name == '<lambda>':
return processor.__module__
if hasattr(processor, 'im_class'):
return '%s.%s' % (processor.im_class.__name__, processor.func_name)
return processor.func_name
return processor.__class__.__name__
def _runtime_threads_task(name, group, final_outputs, reader, num_threads,
output, capacity):
node_name = str(Node.current())
profiler_name = "{0}/{1}/{2}/{3}/{4}".format(
node_name,
"pipe",
name,
processor_name(input) if input else "NoInput",
processor_name(output) if output else "NoOutput")
with Task(name=name, group=group, outputs=final_outputs,
num_instances=num_threads) as task:
global_exit_net = core.Net('pipe:exit')
global_init_net = core.Net('pipe:init')
reader.setup_ex(global_init_net, global_exit_net)
init_net = core.Net('pipe:instance:init')
exit_net = core.Net('pipe:instance:exit')
read_nets, status, rec = reader.read_record_ex(init_net, exit_net)
init_net.ConstantFill(
[], [status],
shape=[],
value=False,
dtype=core.DataType.BOOL
)
if rec is not None:
out_queue, writer = _init_output(
output, capacity, global_init_net, global_exit_net)
write_nets, _ = writer.write_record_ex(
rec, init_net, exit_net, status)
else:
out_queue = None
write_nets = []
with ops.task_init():
ops.net(global_init_net)
with ops.task_instance_init():
ops.net(init_net)
timer_start_net = core.Net('timer_start')
timer = timer_start_net.TimerBegin([], counter_name=profiler_name)
timer_end_net = core.Net('timer_end')
timer_end_net.TimerEnd(timer, [])
ops.net(core.execution_step(
'body',
[timer_start_net] + list(read_nets) + list(write_nets) +
[timer_end_net],
should_stop_blob=status))
ops.net(timer_end_net)
with ops.task_instance_exit():
ops.net(exit_net)
with ops.task_exit():
ops.net(global_exit_net)
return out_queue, task
def _static_threads_task(name, group, final_outputs, reader, num_threads,
output, capacity):
node_name = str(Node.current())
profiler_name = "{0}/{1}/{2}/{3}/{4}".format(
node_name,
"pipe",
name,
processor_name(input) if input else "NoInput",
processor_name(output) if output else "NoOutput")
with Task(name=name, group=group, outputs=final_outputs) as task:
global_exit_net = core.Net('exit')
global_init_net = core.Net('init')
reader.setup_ex(global_init_net, global_exit_net)
out_queue = None
writer = None
steps = []
for thread_id in range(num_threads):
with NetBuilder(name='t:%d' % thread_id) as nb:
init_net = core.Net('init')
exit_net = core.Net('exit')
read_nets, status, rec = reader.read_record_ex(
init_net, exit_net)
init_net.ConstantFill(
[], [status],
shape=[],
value=False,
dtype=core.DataType.BOOL
)
if rec is not None:
if writer is None:
# hack so that the out queue gets the right name prefix
# (otherwise they would be prefixed with the thread id)
with NetBuilder(_fullname=task.name):
out_queue, writer = _init_output(
output, capacity, global_init_net,
global_exit_net)
write_nets, _ = writer.write_record_ex(
rec, init_net, exit_net, status)
else:
write_nets = []
timer_start_net = core.Net('timer_start')
timer = timer_start_net.TimerBegin([], counter_name=profiler_name)
timer_end_net = core.Net('timer_end')
timer_end_net.TimerEnd(timer, [])
ops.net(init_net)
ops.net(core.execution_step(
'body',
[timer_start_net] + list(read_nets) + list(write_nets) +
[timer_end_net],
should_stop_blob=status))
ops.net(timer_end_net)
ops.net(exit_net)
steps.append(core.to_execution_step(nb))
ops.net(global_init_net)
ops.net(core.execution_step('body', steps, concurrent_substeps=True))
ops.net(global_exit_net)
return out_queue, task
def _pipe_step(
input, output=None, num_threads=1, processor=None, name=None,
capacity=None, group=None, num_runtime_threads=None, final_outputs=None):
"""
"""
assert num_threads <= 1 or num_runtime_threads <= 1, (
'Only one of num_threads or num_runtime_threads must be set.')
if isinstance(input, Reader):
reader = input
elif hasattr(input, 'reader'):
reader = input.reader()
else:
raise ValueError('in must be a reader, queue or stream.')
if processor is not None:
reader = ProcessingReader(reader, processor)
if num_threads == 0 or num_runtime_threads == 0:
assert output is None
return reader, None
if name is None and processor is not None:
name = processor_name(processor)
if name is None and output is not None:
name = 'pipe_into:%s' % processor_name(output)
if name is None:
name = 'pipe_from:%s' % processor_name(input)
if num_threads > 1:
return _static_threads_task(
name, group, final_outputs, reader, num_threads, output, capacity)
else:
return _runtime_threads_task(
name, group, final_outputs, reader, num_runtime_threads, output,
capacity)
class ProcessingReader(Reader):
"""
Reader that reads from an upstream reader, calls the processor, and returns
the processed record.
"""
def __init__(self, reader, processor):
Reader.__init__(self)
self.reader = reader
self.processor = make_processor(processor)
def setup_ex(self, init_net, finish_net):
self.reader.setup_ex(init_net, finish_net)
def read_ex(self, init_net, exit_net):
read_nets, status, rec = self.reader.read_record_ex(init_net, exit_net)
# We don't use status as stop_blob of NetBuilder it's not guarantee that
# it would end up being the true stob_blob. For example,
# ReaderWithLimitBase doesn't pass the status through but rather copy
# from it.
with NetBuilder() as nb:
# Current NetBuilder is optionally used inside the processor,
# then its children are retrived inside of
# normalize_processor_output.
# Once readers and writers also use NetBuilder,
# this logic will be more natural.
result = normalize_processor_output(self.processor(rec))
read_nets += result.nets
if result.should_stop or nb._stop_blob:
stop_net = core.Net('stop_net')
if result.should_stop:
stop_net.Or([status, result.should_stop], [status])
if nb._stop_blob:
stop_net.Or([status, nb._stop_blob], [status])
read_nets.append(stop_net)
if hasattr(self.processor, 'setup'):
init_net.add_attribute(TaskGroup.LOCAL_SETUP, self.processor)
self._set_schema(result.record)
fields = result.record.field_blobs() if result.record else None
return read_nets, status, fields
class NetProcessor(object):
"""
Processor that clones a core.Net each time it's called, executing
the cloned net as the processor. It requires the Net to have input
and (optionally) output records set, with net.set_input_record() and
net.set_output_record().
"""
def __init__(self, net, stop_signal=None, thread_init_nets=None, name=None):
assert isinstance(net, core.Net)
assert stop_signal is None or isinstance(
stop_signal, core.BlobReference)
self.name = name or str(net)
self.thread_init_nets = thread_init_nets or []
self.net = net
self._stop_signal = stop_signal
self._blob_maps = []
self._frozen = False
self._cloned_init_nets = []
def setup(self, init_net):
self._frozen = True
cloned_init_nets = self._cloned_init_nets
self._cloned_init_nets = []
return cloned_init_nets
def __call__(self, rec):
assert not self._frozen
prefix = NetBuilder.current().name + '/'
blob_remap = {}
for net in self.thread_init_nets:
new_net, _ = core.clone_and_bind_net(
net, str(net) + prefix, prefix, blob_remap)
self._cloned_init_nets.append(new_net)
new_net, remappings = core.clone_and_bind_net(
self.net, str(self.net) + prefix, prefix, blob_remap, rec)
if self._stop_signal is None:
stop_signal = None
elif str(self._stop_signal) in remappings:
stop_signal = core.BlobReference(
remappings[str(self._stop_signal)],
net=new_net)
else:
stop_signal = self._stop_signal
self._blob_maps.append(remappings)
return Output([new_net], new_net.output_record(), stop_signal)
def blob_maps(self):
self._frozen = True
return self._blob_maps
|
import numpy as np
import unittest
from caffe2.python import core, workspace, muji, test_util
@unittest.skipIf(not workspace.has_gpu_support, "no gpu")
class TestMuji(test_util.TestCase):
def RunningAllreduceWithGPUs(self, gpu_ids, allreduce_function):
"""A base function to test different scenarios."""
net = core.Net("mujitest")
for id in gpu_ids:
net.ConstantFill(
[],
"testblob_gpu_" + str(id),
shape=[1, 2, 3, 4],
value=float(id + 1),
device_option=muji.OnGPU(id)
)
allreduce_function(
net, ["testblob_gpu_" + str(i)
for i in gpu_ids], "_reduced", gpu_ids
)
workspace.RunNetOnce(net)
target_value = sum(gpu_ids) + len(gpu_ids)
all_blobs = workspace.Blobs()
all_blobs.sort()
for blob in all_blobs:
print('{} {}'.format(blob, workspace.FetchBlob(blob)))
for idx in gpu_ids:
blob = workspace.FetchBlob("testblob_gpu_" + str(idx) + "_reduced")
np.testing.assert_array_equal(
blob,
target_value,
err_msg="gpu id %d of %s" % (idx, str(gpu_ids))
)
def testAllreduceFallback(self):
self.RunningAllreduceWithGPUs(
list(range(workspace.NumCudaDevices())), muji.AllreduceFallback
)
def testAllreduceSingleGPU(self):
for i in range(workspace.NumCudaDevices()):
self.RunningAllreduceWithGPUs([i], muji.Allreduce)
def testAllreduceWithTwoGPUs(self):
pattern = workspace.GetCudaPeerAccessPattern()
if pattern.shape[0] >= 2 and np.all(pattern[:2, :2]):
self.RunningAllreduceWithGPUs([0, 1], muji.Allreduce2)
else:
print('Skipping allreduce with 2 gpus. Not peer access ready.')
def testAllreduceWithFourGPUs(self):
pattern = workspace.GetCudaPeerAccessPattern()
if pattern.shape[0] >= 4 and np.all(pattern[:4, :4]):
self.RunningAllreduceWithGPUs([0, 1, 2, 3], muji.Allreduce4)
else:
print('Skipping allreduce with 4 gpus. Not peer access ready.')
def testAllreduceWithEightGPUs(self):
pattern = workspace.GetCudaPeerAccessPattern()
if (
pattern.shape[0] >= 8 and np.all(pattern[:4, :4]) and
np.all(pattern[4:, 4:])
):
self.RunningAllreduceWithGPUs(
list(range(8)), muji.Allreduce8)
else:
print('Skipping allreduce with 8 gpus. Not peer access ready.')
|
## @package cached_reader
# Module caffe2.python.cached_reader
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from caffe2.python import core
from caffe2.python.dataio import Reader
from caffe2.python.dataset import Dataset
from caffe2.python.pipeline import pipe
from caffe2.python.task import Cluster, TaskGroup
class CachedReader(Reader):
"""
Reader with persistent in-file cache.
Example usage:
cached_reader = CachedReader(reader)
build_cache_step = cached_reader.build_cache('/tmp/cache.db')
with LocalSession() as session:
session.run(build_cache_step)
Every time new reader is created, it's expected that build_cache will be
called before setup_ex and usage of the reader. build_cache will check
existence of provided file path and in case it's missing will initialize it
by reading data from original reader. All consequent attempts to read will
ignore original reader (i.e. no additional data will be read from it).
"""
def __init__(self, reader, db_type='leveldb', name='cached_reader'):
super(CachedReader, self).__init__(reader.schema())
self.original_reader = reader
self.cache_path = None
self.ds_reader = None
self.ds = Dataset(self._schema, name)
self.db_type = db_type
self.name = name
self.field_names = self._schema.field_names()
def setup_ex(self, init_net, finish_net):
assert self.cache_path, 'build_cache must be called first'
self._init_dataset(init_net)
self._load_from_file(init_net)
self.ds_reader = self.ds.reader(init_net, batch_size=100)
def read(self, read_net):
assert self.ds_reader, 'setup must be called first'
return self.ds_reader.read(read_net)
def has_cache(self):
return self.cache_path and os.path.exists(self.cache_path)
def build_cache(self, cache_path, overwrite=False):
if not self.has_cache() or overwrite:
self.cache_path = cache_path
if self.has_cache() and not overwrite:
# cache already exists, no need to rebuild it
return core.execution_step('build_step', [])
init_net = core.Net('init')
self._init_dataset(init_net)
with Cluster(), core.NameScope(self.name), TaskGroup() as copy_tg:
pipe(self.original_reader, self.ds.writer(), num_threads=16)
copy_step = copy_tg.to_task().get_step()
save_net = core.Net('save')
self._save_to_file(save_net)
return core.execution_step('build_cache', [init_net, copy_step, save_net])
def _init_dataset(self, init_net):
with core.NameScope(self.name):
self.ds.init_empty(init_net)
def _save_to_file(self, net):
net.Save(
self.ds.content().field_blobs(),
[],
db=self.cache_path,
db_type=self.db_type,
blob_name_overrides=self.field_names,
absolute_path=True,
)
def _load_from_file(self, net):
net.Load(
[],
self.ds.content().field_blobs(),
db=self.cache_path,
db_type=self.db_type,
absolute_path=True,
source_blob_names=self.field_names,
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import workspace
from caffe2.python.core import Plan, to_execution_step, Net
from caffe2.python.task import Task, TaskGroup, final_output
from caffe2.python.net_builder import ops, NetBuilder
from caffe2.python.session import LocalSession
import unittest
import threading
class PythonOpStats(object):
lock = threading.Lock()
num_instances = 0
num_calls = 0
def python_op_builder():
PythonOpStats.lock.acquire()
PythonOpStats.num_instances += 1
PythonOpStats.lock.release()
def my_op(inputs, outputs):
PythonOpStats.lock.acquire()
PythonOpStats.num_calls += 1
PythonOpStats.lock.release()
return my_op
def _test_loop():
x = ops.Const(5)
y = ops.Const(0)
with ops.loop():
ops.stop_if(ops.EQ([x, ops.Const(0)]))
ops.Add([x, ops.Const(-1)], [x])
ops.Add([y, ops.Const(1)], [y])
return y
def _test_inner_stop(x):
ops.stop_if(ops.LT([x, ops.Const(5)]))
def _test_outer():
x = ops.Const(10)
# test stop_if(False)
with ops.stop_guard() as g1:
_test_inner_stop(x)
# test stop_if(True)
y = ops.Const(3)
with ops.stop_guard() as g2:
_test_inner_stop(y)
# test no stop
with ops.stop_guard() as g4:
ops.Const(0)
# test empty clause
with ops.stop_guard() as g3:
pass
return (
g1.has_stopped(), g2.has_stopped(), g3.has_stopped(), g4.has_stopped())
def _test_if(x):
y = ops.Const(1)
with ops.If(ops.GT([x, ops.Const(50)])):
ops.Const(2, blob_out=y)
with ops.If(ops.LT([x, ops.Const(50)])):
ops.Const(3, blob_out=y)
ops.stop()
ops.Const(4, blob_out=y)
return y
class TestNetBuilder(unittest.TestCase):
def test_ops(self):
with NetBuilder() as nb:
y = _test_loop()
z, w, a, b = _test_outer()
p = _test_if(ops.Const(75))
q = _test_if(ops.Const(25))
plan = Plan('name')
plan.AddStep(to_execution_step(nb))
ws = workspace.C.Workspace()
ws.run(plan)
expected = [
(y, 5),
(z, False),
(w, True),
(a, False),
(b, False),
(p, 2),
(q, 3),
]
for b, expected in expected:
actual = ws.blobs[str(b)].fetch()
self.assertEquals(actual, expected)
def _expected_loop(self):
total = 0
total_large = 0
total_small = 0
total_tiny = 0
for loop_iter in range(10):
outer = loop_iter * 10
for inner_iter in range(loop_iter):
val = outer + inner_iter
if val >= 80:
total_large += val
elif val >= 50:
total_small += val
else:
total_tiny += val
total += val
return total, total_large, total_small, total_tiny
def _actual_loop(self):
total = ops.Const(0)
total_large = ops.Const(0)
total_small = ops.Const(0)
total_tiny = ops.Const(0)
with ops.loop(10) as loop:
outer = ops.Mul([loop.iter(), ops.Const(10)])
with ops.loop(loop.iter()) as inner:
val = ops.Add([outer, inner.iter()])
with ops.If(ops.GE([val, ops.Const(80)])) as c:
ops.Add([total_large, val], [total_large])
with c.Elif(ops.GE([val, ops.Const(50)])) as c:
ops.Add([total_small, val], [total_small])
with c.Else():
ops.Add([total_tiny, val], [total_tiny])
ops.Add([total, val], total)
return [
final_output(x)
for x in [total, total_large, total_small, total_tiny]
]
def test_net_multi_use(self):
with Task() as task:
total = ops.Const(0)
net = Net('my_net')
net.Add([total, net.Const(1)], [total])
ops.net(net)
ops.net(net)
result = final_output(total)
with LocalSession() as session:
session.run(task)
self.assertEquals(2, result.fetch())
def test_loops(self):
with Task() as task:
out_actual = self._actual_loop()
with LocalSession() as session:
session.run(task)
expected = self._expected_loop()
actual = [o.fetch() for o in out_actual]
for e, a in zip(expected, actual):
self.assertEquals(e, a)
def test_setup(self):
with Task() as task:
with ops.task_init():
one = ops.Const(1)
two = ops.Add([one, one])
with ops.task_init():
three = ops.Const(3)
accum = ops.Add([two, three])
# here, accum should be 5
with ops.task_exit():
# here, accum should be 6, since this executes after lines below
seven_1 = ops.Add([accum, one])
six = ops.Add([accum, one])
ops.Add([accum, one], [accum])
seven_2 = ops.Add([accum, one])
o6 = final_output(six)
o7_1 = final_output(seven_1)
o7_2 = final_output(seven_2)
with LocalSession() as session:
session.run(task)
self.assertEquals(o6.fetch(), 6)
self.assertEquals(o7_1.fetch(), 7)
self.assertEquals(o7_2.fetch(), 7)
def test_multi_instance_python_op(self):
"""
When task instances are created at runtime, C++ concurrently creates
multiple instances of operators in C++, and concurrently destroys them
once the task is finished. This means that the destructor of PythonOp
will be called concurrently, so the GIL must be acquired. This
test exercises this condition.
"""
with Task(num_instances=64) as task:
with ops.loop(4):
ops.Python((python_op_builder, [], {}))([], [])
with LocalSession() as session:
PythonOpStats.num_instances = 0
PythonOpStats.num_calls = 0
session.run(task)
self.assertEquals(PythonOpStats.num_instances, 64)
self.assertEquals(PythonOpStats.num_calls, 256)
def test_multi_instance(self):
NUM_INSTANCES = 10
NUM_ITERS = 15
with TaskGroup() as tg:
with Task(num_instances=NUM_INSTANCES):
with ops.task_init():
counter1 = ops.CreateCounter([], ['global_counter'])
counter2 = ops.CreateCounter([], ['global_counter2'])
counter3 = ops.CreateCounter([], ['global_counter3'])
# both task_counter and local_counter should be thread local
with ops.task_instance_init():
task_counter = ops.CreateCounter([], ['task_counter'])
local_counter = ops.CreateCounter([], ['local_counter'])
with ops.loop(NUM_ITERS):
ops.CountUp(counter1)
ops.CountUp(task_counter)
ops.CountUp(local_counter)
# gather sum of squares of local counters to make sure that
# each local counter counted exactly up to NUM_ITERS, and
# that there was no false sharing of counter instances.
with ops.task_instance_exit():
count2 = ops.RetrieveCount(task_counter)
with ops.loop(ops.Mul([count2, count2])):
ops.CountUp(counter2)
# This should have the same effect as the above
count3 = ops.RetrieveCount(local_counter)
with ops.loop(ops.Mul([count3, count3])):
ops.CountUp(counter3)
# The code below will only run once
with ops.task_exit():
total1 = final_output(ops.RetrieveCount(counter1))
total2 = final_output(ops.RetrieveCount(counter2))
total3 = final_output(ops.RetrieveCount(counter3))
with LocalSession() as session:
session.run(tg)
self.assertEquals(total1.fetch(), NUM_INSTANCES * NUM_ITERS)
self.assertEquals(total2.fetch(), NUM_INSTANCES * (NUM_ITERS ** 2))
self.assertEquals(total3.fetch(), NUM_INSTANCES * (NUM_ITERS ** 2))
def test_if_net(self):
with NetBuilder() as nb:
x0 = ops.Const(0)
x1 = ops.Const(1)
x2 = ops.Const(2)
y0 = ops.Const(0)
y1 = ops.Const(1)
y2 = ops.Const(2)
# basic logic
first_res = ops.Const(0)
with ops.IfNet(ops.Const(True)):
ops.Const(1, blob_out=first_res)
with ops.Else():
ops.Const(2, blob_out=first_res)
second_res = ops.Const(0)
with ops.IfNet(ops.Const(False)):
ops.Const(1, blob_out=second_res)
with ops.Else():
ops.Const(2, blob_out=second_res)
# nested and sequential ifs,
# empty then/else,
# passing outer blobs into branches,
# writing into outer blobs, incl. into input blob
# using local blobs
with ops.IfNet(ops.LT([x0, x1])):
local_blob = ops.Const(900)
ops.Add([ops.Const(100), local_blob], [y0])
gt = ops.GT([x1, x2])
with ops.IfNet(gt):
# empty then
pass
with ops.Else():
ops.Add([y1, local_blob], [local_blob])
ops.Add([ops.Const(100), y1], [y1])
with ops.IfNet(ops.EQ([local_blob, ops.Const(901)])):
ops.Const(7, blob_out=y2)
ops.Add([y1, y2], [y2])
with ops.Else():
# empty else
pass
plan = Plan('if_net_test')
plan.AddStep(to_execution_step(nb))
ws = workspace.C.Workspace()
ws.run(plan)
first_res_value = ws.blobs[str(first_res)].fetch()
second_res_value = ws.blobs[str(second_res)].fetch()
y0_value = ws.blobs[str(y0)].fetch()
y1_value = ws.blobs[str(y1)].fetch()
y2_value = ws.blobs[str(y2)].fetch()
self.assertEquals(first_res_value, 1)
self.assertEquals(second_res_value, 2)
self.assertEquals(y0_value, 1000)
self.assertEquals(y1_value, 101)
self.assertEquals(y2_value, 108)
self.assertTrue(str(local_blob) not in ws.blobs)
def test_while_net(self):
with NetBuilder() as nb:
x = ops.Const(0)
y = ops.Const(0)
with ops.WhileNet():
with ops.Condition():
ops.Add([x, ops.Const(1)], [x])
ops.LT([x, ops.Const(7)])
ops.Add([x, y], [y])
plan = Plan('while_net_test')
plan.AddStep(to_execution_step(nb))
ws = workspace.C.Workspace()
ws.run(plan)
x_value = ws.blobs[str(x)].fetch()
y_value = ws.blobs[str(y)].fetch()
self.assertEqual(x_value, 7)
self.assertEqual(y_value, 21)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future.utils import bytes_to_native_str
from hypothesis import given
import hypothesis.strategies as st
import unittest
from caffe2.proto import caffe2_pb2
from caffe2.python import core, test_util
from caffe2.python.core import CreateOperator, GradientRegistry
from caffe2.python import workspace
import numpy as np
# First, we will set up a few gradient registry entries so that we can manually
# construct some test cases.
def NeedAll(op, g_output):
"""A sanity check to make sure that all the gradient are given."""
for name, g in zip(op.output, g_output):
if g is None:
raise RuntimeError(
'Need gradient for "%s" but it is not provided.' % name)
return g_output
def GIS(op):
"""A test util function to generate the gradient name for input."""
return [s + '_grad' for s in op.input]
def CopyDeviceOption(op, src_op):
if src_op.HasField('device_option'):
op.device_option.CopyFrom(src_op.device_option)
return op
# First gradient: (in -> out) leading to (out_grad -> in_grad)
@GradientRegistry.RegisterGradient('Direct')
def AddDirectGradient(op, g_output):
return (
CopyDeviceOption(
CreateOperator('DirectGradient', NeedAll(op, g_output), GIS(op)),
op),
GIS(op)
)
# Second gradient: (in -> out) leading to (out, out_grad -> in_grad)
@GradientRegistry.RegisterGradient('UseOutput')
def AddUseOutputGradient(op, g_output):
return (
CopyDeviceOption(
CreateOperator(
'UseOutputGradient',
list(op.output) + NeedAll(op, g_output), GIS(op)),
op),
GIS(op)
)
@GradientRegistry.RegisterGradient('UseInput')
def AddUseInputGradient(op, g_output):
return (
CopyDeviceOption(
CreateOperator(
'UseInputGradient',
list(op.input) + NeedAll(op, g_output), GIS(op)),
op),
GIS(op)
)
@GradientRegistry.RegisterGradient('Nogradient')
def AddNogradient(op, g_output):
return (
[],
[None for s in op.input]
)
class TestGradientCalculation(test_util.TestCase):
def assertOperatorListEqual(self, operatorDefList1, operatorDefList2):
for op in operatorDefList1:
op.debug_info = ""
for op in operatorDefList2:
op.debug_info = ""
self.assertEqual(operatorDefList1, operatorDefList2)
@given(device_option=st.sampled_from([
None,
core.DeviceOption(caffe2_pb2.CUDA, 1)]))
def testDirect(self, device_option):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('Direct', 'hidden', 'out'),
]
if device_option:
for op in operators:
op.device_option.CopyFrom(device_option)
desired_grad_operators = [
CreateOperator('DirectGradient', 'out_grad', 'hidden_grad'),
CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'),
]
if device_option:
for op in desired_grad_operators:
op.device_option.CopyFrom(device_option)
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testDirectImplicitGradientSource(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('Direct', 'hidden', 'out'),
]
desired_grad_operators = [
CreateOperator(
"ConstantFill", 'out', "out_autogen_grad", value=1.0),
CreateOperator(
'DirectGradient', 'out_autogen_grad', 'hidden_grad'),
CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'),
]
for op in desired_grad_operators:
op.debug_info = ""
gradients, _ = GradientRegistry.GetBackwardPass(
operators, ['out'])
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testDoesNotGenerateUnnecessaryGradients(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('Direct', 'hidden', 'out'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'),
]
for op in desired_grad_operators:
op.debug_info = ""
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'hidden': 'hidden_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testDirectButNoOutputGradientGiven(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('Direct', 'hidden', 'out'),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {})
self.assertOperatorListEqual(gradients, [])
def testDirectInPlace(self):
operators = [
CreateOperator('Direct', 'in', 'in'),
CreateOperator('Direct', 'in', 'out'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'out_grad', 'in_grad'),
CreateOperator('DirectGradient', 'in_grad', 'in_grad'),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testVersionMismatch(self):
operators = [
CreateOperator('Direct', 'x', 'x'),
CreateOperator('Direct', 'y', 'x'),
CreateOperator('Direct', 'x', 'y'),
]
try:
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'y': 'y_grad'})
self.assertFalse(True, "Should raise exception of incorrect version")
except RuntimeError as e:
print(e)
self.assertTrue("version" in str(e))
pass
def testUseOutput(self):
operators = [
CreateOperator('UseOutput', 'in', 'hidden'),
CreateOperator('UseOutput', 'hidden', 'out'),
CreateOperator('Direct', 'out', 'sink'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'sink_grad', 'out_grad'),
CreateOperator(
'UseOutputGradient',
['out', 'out_grad'], 'hidden_grad'
),
CreateOperator(
'UseOutputGradient',
['hidden', 'hidden_grad'], 'in_grad'
),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'sink': 'sink_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testUseOutputInPlace(self):
operators = [
CreateOperator('UseOutput', 'in', 'in'),
CreateOperator('UseOutput', 'in', 'out'),
CreateOperator('Direct', 'out', 'sink'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'sink_grad', 'out_grad'),
CreateOperator(
'UseOutputGradient',
['out', 'out_grad'], 'in_grad'
),
CreateOperator(
'UseOutputGradient',
['in', 'in_grad'], 'in_grad'
),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'sink': 'sink_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testUseOutputButOutputHasBeenChanged(self):
operators = [
CreateOperator('UseOutput', 'in', 'hidden'),
# Note here: we overwrite hidden, but hidden will be needed by the
# gradient calculation of the first operator, so the gradient
# registry should return an error.
CreateOperator('Direct', 'hidden', 'hidden'),
CreateOperator('UseOutput', 'hidden', 'out'),
CreateOperator('Direct', 'out', 'sink'),
]
with self.assertRaises(RuntimeError):
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'sink': 'sink_grad'})
def testUseInput(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('UseInput', 'hidden', 'out'),
CreateOperator('Direct', 'out', 'sink'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'sink_grad', 'out_grad'),
CreateOperator(
'UseInputGradient',
['hidden', 'out_grad'], 'hidden_grad'
),
CreateOperator(
'DirectGradient',
'hidden_grad', 'in_grad'
),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'sink': 'sink_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testUseInputButInputHasBeenChanged(self):
"""Test gradient for the following case:
in -> out, with UseInput
in -> in
Since we overwrite in in op#1, but in will be needed by the gradient
calculation of op#0, the gradient registry should raise an error.
"""
operators = [
CreateOperator('UseInput', 'in', 'out'),
CreateOperator('Direct', 'in', 'in'),
]
with self.assertRaises(RuntimeError):
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
@given(device_option=st.sampled_from([
None,
core.DeviceOption(caffe2_pb2.CUDA, 1)]))
def testMultiUseInput(self, device_option):
"""Test gradient for the following case:
in -> hidden1
in -> hidden2
hidden1, hidden2 -> out
"""
operators = [
CreateOperator('Direct', 'in', 'hidden1'),
CreateOperator('Direct', 'in', 'hidden2'),
CreateOperator('Direct', ['hidden1', 'hidden2'], 'out'),
]
if device_option:
for op in operators:
op.device_option.CopyFrom(device_option)
desired_grad_operators = [
CreateOperator(
'DirectGradient',
'out_grad', ['hidden1_grad', 'hidden2_grad']
),
CreateOperator(
'DirectGradient',
'hidden2_grad', 'in_grad'
),
CreateOperator(
'DirectGradient',
'hidden1_grad', '_in_grad_autosplit_0'
),
CreateOperator(
'Sum',
['in_grad', '_in_grad_autosplit_0'], 'in_grad'
),
]
if device_option:
for op in desired_grad_operators:
op.device_option.CopyFrom(device_option)
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {"out": "out_grad"})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testMultiUseInputButWithNoGradient(self):
"""Test gradient for the following case:
in -> hidden1
in -(no gradient)-> hidden2
hidden1, hidden2 -> out
"""
operators = [
CreateOperator('Direct', 'in', 'hidden1'),
CreateOperator('Nogradient', 'in', 'hidden2'),
CreateOperator('Direct', ['hidden1', 'hidden2'], 'out'),
]
desired_grad_operators = [
CreateOperator(
'DirectGradient',
'out_grad', ['hidden1_grad', 'hidden2_grad']
),
CreateOperator(
'DirectGradient',
'hidden1_grad', 'in_grad'
),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testMultiUseInputAndMultipleVersions(self):
"""Test gradient for the following case:
in -> in
in -> hidden1, hidden2
hidden1, hidden2 -> out
"""
operators = [
CreateOperator('Direct', 'in', 'in'),
CreateOperator('Direct', 'in', 'hidden1'),
CreateOperator('Direct', 'in', 'hidden2'),
CreateOperator('Direct', ['hidden1', 'hidden2'], 'out'),
]
desired_grad_operators = [
CreateOperator(
'DirectGradient',
'out_grad', ['hidden1_grad', 'hidden2_grad']
),
CreateOperator(
'DirectGradient',
'hidden2_grad', 'in_grad'
),
CreateOperator(
'DirectGradient',
'hidden1_grad', '_in_grad_autosplit_0'
),
CreateOperator(
'Sum',
['in_grad', '_in_grad_autosplit_0'], 'in_grad'
),
CreateOperator(
'DirectGradient',
'in_grad', 'in_grad'
),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testMultiUseInputAndMultipleVersionsBig(self):
"""Test gradient for the following case:
in -> in
in -> hidden1, hidden2
hidden1, hidden2 -> in
in -> hidden3, hidden4, hidden5
hidden3, hidden4, hidden5 -> out
"""
operators = [
CreateOperator('Direct', 'in', 'in'),
CreateOperator('Direct', 'in', 'hidden1'),
CreateOperator('Direct', 'in', 'hidden2'),
CreateOperator('Direct', ['hidden1', 'hidden2'], 'in'),
CreateOperator('Direct', 'in', 'hidden3'),
CreateOperator('Direct', 'in', 'hidden4'),
CreateOperator('Direct', 'in', 'hidden5'),
CreateOperator('Direct', ['hidden3', 'hidden4', 'hidden5'], 'out'),
]
desired_grad_operators = [
CreateOperator(
'DirectGradient',
'out_grad', ['hidden3_grad', 'hidden4_grad', 'hidden5_grad']
),
CreateOperator(
'DirectGradient',
'hidden5_grad', 'in_grad'
),
CreateOperator(
'DirectGradient',
'hidden4_grad', '_in_grad_autosplit_0'
),
CreateOperator(
'DirectGradient',
'hidden3_grad', '_in_grad_autosplit_1'
),
CreateOperator(
'Sum',
['in_grad', '_in_grad_autosplit_0',
'_in_grad_autosplit_1'],
'in_grad'
),
CreateOperator(
'DirectGradient',
'in_grad', ['hidden1_grad', 'hidden2_grad']
),
CreateOperator(
'DirectGradient',
'hidden2_grad', 'in_grad'
),
CreateOperator(
'DirectGradient',
'hidden1_grad', '_in_grad_autosplit_0'
),
CreateOperator(
'Sum',
['in_grad', '_in_grad_autosplit_0'],
'in_grad'
),
CreateOperator(
'DirectGradient',
'in_grad', 'in_grad'
),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
for s in gradients:
print(str(s))
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testGradientMappingUsingSumOp(self):
"""Since Sum is used in accumulating gradients, we will test if
it is OK to also explicitly use it in the graph."""
operators = [
CreateOperator('FC', ['in', 'w', 'b'], 'fc'),
CreateOperator('Sum', 'fc', 'agg'),
CreateOperator('AveragedLoss', 'agg', 'loss'),
]
# This should run correctly.
gradient_ops, _ = GradientRegistry.GetBackwardPass(
operators, {'loss': 'loss_grad'})
for s in gradient_ops:
print(str(s))
def testGradientCalculationWithPrint(self):
"""Test a common use case where we have Print in the forward pass."""
operators = [
CreateOperator('FC', ['in', 'w', 'b'], 'fc'),
CreateOperator('Print', 'fc', []),
CreateOperator('AveragedLoss', 'fc', 'loss'),
]
desired_grad_operators = [
CreateOperator('AveragedLossGradient',
['fc', 'loss_grad'], 'fc_grad'),
CreateOperator('FCGradient', ['in', 'w', 'fc_grad'],
['w_grad', 'b_grad', 'in_grad']),
]
for g in desired_grad_operators:
g.is_gradient_op = 1
# This should run correctly.
gradient_ops, _ = GradientRegistry.GetBackwardPass(
operators, {'loss': 'loss_grad'})
for s in gradient_ops:
print(str(s))
self.assertOperatorListEqual(gradient_ops, desired_grad_operators)
def testStopGradient(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('StopGradient', 'hidden', 'hidden2'),
CreateOperator('Direct', 'hidden2', 'out'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'out_grad', 'hidden2_grad'),
]
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
def testStopGradientOrphan(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('StopGradient', 'hidden', 'auto_blobx'),
CreateOperator('Direct', 'hidden', 'out'),
]
with self.assertRaises(ValueError):
# This should complain about incorrect use of StopGradient
gradients, _ = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
def testStopGradientInplace(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('StopGradient', 'hidden', 'hidden'),
CreateOperator('Direct', 'hidden', 'out'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'out_grad', 'hidden_grad'),
]
gradients, grad_map = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
self.assertEqual(grad_map, {'out': 'out_grad'})
def testStopGradientWithMultiUseOperators(self):
operators = [
CreateOperator('Direct', 'in', 'hidden'),
CreateOperator('Direct', 'hidden', 'hidden2'),
CreateOperator('StopGradient', 'hidden', 'hidden3'),
CreateOperator('Direct', ['hidden2', 'hidden3'], 'out'),
]
desired_grad_operators = [
CreateOperator('DirectGradient', 'out_grad',
['hidden2_grad', 'hidden3_grad']),
CreateOperator('DirectGradient', 'hidden2_grad', 'hidden_grad'),
CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'),
]
gradients, grad_map = GradientRegistry.GetBackwardPass(
operators, {'out': 'out_grad'})
self.assertOperatorListEqual(gradients, desired_grad_operators)
self.assertEqual(
grad_map, {'out': 'out_grad', 'hidden2': 'hidden2_grad',
'hidden3': 'hidden3_grad', 'hidden': 'hidden_grad',
'in': 'in_grad'})
def test_zero_gradient(self):
net = core.Net("zero_grad_test")
hidden_prev, cell, gates, seq_lengths, timestep =\
net.AddExternalInput("h", "c", "g", "s", "t")
hidden, cell = net.LSTMUnit(
[hidden_prev, cell, gates, seq_lengths, timestep],
["hidden_t", "cell_t"])
with self.assertRaises(Exception):
net.AddGradientOperators([hidden])
net.ZeroGradient(cell, [])
net.AddGradientOperators([hidden])
def test_two_grads(self):
net = core.Net("test_two_grads")
input, two, three = net.AddExternalInput("input", "two", "three")
m1 = net.Mul([input, two], "mul_1")
m2 = net.Mul([m1, three], "mul_2")
grad_map = net.AddGradientOperators([m2, m1])
workspace.ResetWorkspace()
workspace.blobs[input] = np.array([1]).astype(np.float32)
workspace.blobs[two] = np.array([2]).astype(np.float32)
workspace.blobs[three] = np.array([3]).astype(np.float32)
workspace.RunNetOnce(net)
print(net.Proto())
for blob in workspace.blobs:
print(blob, workspace.blobs[blob])
print("Input grad: ", workspace.blobs[grad_map[str(input)]])
assert workspace.blobs[grad_map[str(input)]] == 8.0
# Skip if sparse operators are not available
@unittest.skipIf(not core.IsOperator('SparseFunHash'),
'Sparse operators not available')
class TestSparseGradientsAccumulation(test_util.TestCase):
def testSparseAccumulationWithValues(self):
# The gradient for "Gather" only computes values. indices are directly
# passed from the input
#
# x1-->Gather-->x4-->
# | |
# x2-----+ DotProduct-->x6
# | |
# x3-->Gather-->x5-->
net = core.Net("test_net")
net.Gather(["x2", "x1"], "x4")
net.Gather(["x2", "x3"], "x5")
net.DotProduct(["x4", "x5"], "x6")
net.AddGradientOperators(["x6"])
sum_op_i = net.Proto().op[-2]
sum_op_v = net.Proto().op[-1]
self.assertEqual(sum_op_i.input[0], "x3")
self.assertEqual(sum_op_i.input[1], "x1")
self.assertEqual(sum_op_i.output[0], "x2_grad_indices_concat")
self.assertEqual(sum_op_v.input[0], "x5_grad")
self.assertEqual(sum_op_v.input[1], "x4_grad")
self.assertEqual(sum_op_v.output[0], "x2_grad_values_concat")
def testSparseGradientToDense(self):
#
# x1-->Gather-->x4-->
# | |
# x0, w, b-->FC-->x2-->EnsureDenseGradient-->x2---+ DotProduct-->x6
# | |
# x3-->Gather-->x5-->
net = core.Net("test_net")
net.FC(["x0", "w", "b"], "x2")
net.EnsureDense(["x2"], "x2")
net.Gather(["x2", "x1"], "x4")
net.Gather(["x2", "x3"], "x5")
net.DotProduct(["x4", "x5"], "x6")
net.AddGradientOperators(["x6"])
ensure_dense_op = net.Proto().op[-2]
self.assertEqual(ensure_dense_op.input[0], "x2_grad_indices_concat")
self.assertEqual(ensure_dense_op.input[1], "x2_grad_values_concat")
self.assertEqual(ensure_dense_op.output[0], "x2_grad")
def testSparseAccumulationWithIndicesAndValues(self):
# The gradient for "SparseFunHash" computes both indices and values
#
# x1-------->
# |
# x2----> |
# | |
# x3---SparseFunHash-->x8
# / \
# x4---+ DotProduct-->x10
# \ /
# x5---SparseFunHash-->x9
# | |
# x6----> |
# |
# x7-------->
net = core.Net("test_net")
net.SparseFunHash(["x1", "x2", "x3", "x4"], "x8")
net.SparseFunHash(["x5", "x6", "x7", "x4"], "x9")
net.DotProduct(["x8", "x9"], "x10")
net.AddGradientOperators(["x10"])
sum_op_i = net.Proto().op[-2]
sum_op_v = net.Proto().op[-1]
self.assertEqual(sum_op_i.input[0], "_x4_grad_indices_autosplit_0")
self.assertEqual(sum_op_i.input[1], "_x4_grad_indices_autosplit_1")
self.assertEqual(sum_op_i.output[0], "x4_grad_indices_concat")
self.assertEqual(sum_op_v.input[0], "_x4_grad_values_autosplit_0")
self.assertEqual(sum_op_v.input[1], "_x4_grad_values_autosplit_1")
self.assertEqual(sum_op_v.output[0], "x4_grad_values_concat")
class TestGradientsAccumulationWithNoGradientOps(test_util.TestCase):
def testNormalAccumulation(self):
# x1-->Relu--x2----------------->DotProduct-->x4
# | |
# -->Softmax-->x3-->
net = core.Net("test_net")
net.Relu("x1", "x2")
net.Softmax("x2", "x3")
net.DotProduct(["x2", "x3"], "x4")
net.AddGradientOperators(["x4"])
sum_op = net.Proto().op[-2]
self.assertEqual(sum_op.input[0], "x2_grad")
self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_0")
self.assertEqual(sum_op.output[0], "x2_grad")
def testAccumulationWithNoGradientBranch(self):
# -->PRINT
# |
# x1-->Relu--x2----------------->DotProduct-->x4
# | |
# -->Softmax-->x3-->
net = core.Net("test_net")
net.Relu("x1", "x2")
net.Print("x2", [])
net.Softmax("x2", "x3")
net.DotProduct(["x2", "x3"], "x4")
net.AddGradientOperators(["x4"])
sum_op = net.Proto().op[-2]
self.assertEqual(sum_op.input[0], "x2_grad")
self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_0")
self.assertEqual(sum_op.output[0], "x2_grad")
class TestGradientsAccumulationWithPassThroughGradients(test_util.TestCase):
def testAddOpInMiddle(self):
# x1-->Relu--x2----------------->Add-->x4
# | |
# -->Softmax-->x3-->
#
# Expected gradient graph:
#
# x1_g<--ReluG<--x2_g<--Sum<------------<---------x4_g
# | |
# <--_x2_g_split_0<--SoftmaxG
net = core.Net("test_net")
net.Relu("x1", "x2")
net.Softmax("x2", "x3")
net.Add(["x2", "x3"], "x4")
input_to_grad = net.AddGradientOperators({"x4": "x4_grad"})
sum_op = net.Proto().op[-2]
self.assertEqual(sum_op.input[0], "x2_grad")
self.assertEqual(sum_op.input[1], "x4_grad")
self.assertEqual(sum_op.output[0], "x2_grad")
self.assertEqual(input_to_grad["x1"], "x1_grad")
def testAddAndDynamicConstant(self):
net = core.Net("test_net")
net.FC(["x1", "x1_w", "x1_b"], ["x2"])
net.Relu("x2", "x2")
net.ConstantFill(["x2"], ["x3"])
net.Add(["x2", "x3"], "x4")
net.FC(["x4", "x4_w", "x4_b"], ["x5"])
net.SoftmaxWithLoss(["x5", "labels"], ["softmax", "loss"])
input_to_grad = net.AddGradientOperators(["loss"])
for op in net.Proto().op:
self.assertFalse(op.type == 'Sum')
self.assertTrue("x4" in input_to_grad)
self.assertTrue("x1" in input_to_grad)
self.assertEqual(input_to_grad["x1"], "x1_grad")
def testAddAndStaticConstant(self):
net = core.Net("test_net")
net.FC(["x1", "x1_w", "x1_b"], ["x2"])
net.Relu("x2", "x2")
net.ConstantFill([], ["x3"], shape=[1])
net.Add(["x2", "x3"], "x4", broadcast=1)
net.FC(["x4", "x4_w", "x4_b"], ["x5"])
net.SoftmaxWithLoss(["x5", "labels"], ["softmax", "loss"])
input_to_grad = net.AddGradientOperators(["loss"])
print(input_to_grad)
self.assertTrue("x1" in input_to_grad)
self.assertEqual(input_to_grad["x1"], "x1_grad")
def testSubOpInMiddle(self):
# x1-->Relu--x2----------------->Sub-->x4
# | |
# -->Softmax-->x3-->
#
# Expected gradient graph:
#
# x1_g<--ReluG<--x2_g<--Sum<------------<-----------------------x4_g
# | |
# <--_x2_g_split_0<--SoftmaxG<--x3_g<--neg
net = core.Net("test_net")
net.Relu("x1", "x2")
net.Softmax("x2", "x3")
net.Sub(["x2", "x3"], "x4")
input_to_grad = net.AddGradientOperators({"x4": "x4_grad"})
print(str(net.Proto()))
sum_op = net.Proto().op[-2]
self.assertEqual(sum_op.input[0], "x2_grad")
self.assertEqual(sum_op.input[1], "x4_grad")
self.assertEqual(sum_op.output[0], "x2_grad")
self.assertEqual(input_to_grad["x1"], "x1_grad")
def testAddOpAtLeaf(self):
# x1
# \
# -->Add-->x4
# / \
# x2 -->DotProduct-->x6
# \ /
# -->Add-->x5
# /
# x3
#
# Expected gradient graph:
#
# x2_g<--Sum<--x4_g<--DotProductG<--x6_g
# | | |
# <---x5_g<-------
net = core.Net("test_net")
net.Add(["x1", "x2"], "x4")
net.Add(["x2", "x3"], "x5")
net.DotProduct(["x4", "x5"], "x6")
input_to_grad = net.AddGradientOperators({"x6": "x6_grad"})
sum_op = net.Proto().op[-1]
self.assertEqual(sum_op.input[0], "x5_grad")
self.assertEqual(sum_op.input[1], "x4_grad")
self.assertEqual(sum_op.output[0], "x2_grad")
self.assertEqual(input_to_grad["x1"], "x4_grad")
self.assertEqual(input_to_grad["x2"], "x2_grad")
self.assertEqual(input_to_grad["x3"], "x5_grad")
def testSubOpAtLeaf(self):
# x1
# \
# -->Sub-->x4
# / \
# x2 -->DotProduct-->x6
# \ /
# -->Sub-->x5
# /
# x3
#
# Expected gradient graph:
#
# x2_g<-------Sum<--x2_g_split_0<--neg<--x4_g<--DotProductG<--x6_g
# | |
# x3_g<--neg<--<--x5_g<--------------------------------
net = core.Net("test_net")
net.Sub(["x1", "x2"], "x4")
net.Sub(["x2", "x3"], "x5")
net.DotProduct(["x4", "x5"], "x6")
input_to_grad = net.AddGradientOperators({"x6": "x6_grad"})
sum_op = net.Proto().op[-1]
self.assertEqual(sum_op.input[0], "x2_grad")
self.assertEqual(sum_op.input[1], "x5_grad")
self.assertEqual(sum_op.output[0], "x2_grad")
self.assertEqual(input_to_grad["x1"], "x4_grad")
self.assertEqual(input_to_grad["x2"], "x2_grad")
self.assertEqual(input_to_grad["x3"], "x3_grad")
def testMultiLayerAddOps(self):
# x1
# \
# -->Add-->x4
# / \
# x2 -->Add-->x6
# \ /
# -->Add-->x5
# /
# x3
#
# Expected gradient graph:
#
# x2_g<--Sum<-----x6_g
# | |
# <--------
net = core.Net("test_net")
net.Add(["x1", "x2"], "x4")
net.Add(["x2", "x3"], "x5")
net.Add(["x4", "x5"], "x6")
input_to_grad = net.AddGradientOperators({"x6": "x6_grad"})
sum_op = net.Proto().op[-1]
self.assertEqual(sum_op.input[0], "x6_grad")
self.assertEqual(sum_op.input[1], "x6_grad")
self.assertEqual(sum_op.output[0], "x2_grad")
self.assertEqual(input_to_grad["x1"], "x6_grad")
self.assertEqual(input_to_grad["x2"], "x2_grad")
self.assertEqual(input_to_grad["x3"], "x6_grad")
def testMultiLayerSubOps(self):
# x1
# \
# -->Sub-->x4
# / \
# x2 -->Sub-->x6
# \ /
# -->Sub-->x5
# /
# x3
#
# Expected gradient graph:
#
# x2_g<--Sum<-----x6_g
# | |
# <--------
net = core.Net("test_net")
net.Sub(["x1", "x2"], "x4")
net.Sub(["x2", "x3"], "x5")
net.Sub(["x4", "x5"], "x6")
input_to_grad = net.AddGradientOperators({"x6": "x6_grad"})
sum_op = net.Proto().op[-1]
self.assertEqual(sum_op.input[0], "x2_grad")
self.assertEqual(sum_op.input[1], "x5_grad")
self.assertEqual(sum_op.output[0], "x2_grad")
self.assertEqual(input_to_grad["x1"], "x6_grad")
self.assertEqual(input_to_grad["x2"], "x2_grad")
self.assertEqual(input_to_grad["x3"], "x3_grad")
def testAccumulationRuns(self):
net = core.Net("test_net")
input, one, two, three = net.AddExternalInput(
"input", "one", "two", "three")
m1 = net.Mul([input, two], "mul_1")
m2 = net.Mul([input, three], "mul_2")
sub = net.Sub([m1, one])
grad_map = net.AddGradientOperators([m2, sub])
workspace.ResetWorkspace()
workspace.blobs[one] = np.array([1]).astype(np.float32)
workspace.blobs[input] = np.array([1]).astype(np.float32)
workspace.blobs[two] = np.array([2]).astype(np.float32)
workspace.blobs[three] = np.array([3]).astype(np.float32)
workspace.RunNetOnce(net)
print("Input grad: ", workspace.blobs[grad_map[str(input)]])
assert workspace.blobs[grad_map[str(input)]] == 5.0
def testIncorrectOperator(self):
net = core.Net("test_net")
a, b, one = net.AddExternalInput("a", "b", "one")
m1 = net.Mul(a, b) # does not have second output
sub = net.Sub([m1, one])
try:
net.AddGradientOperators([sub])
self.assertFalse(True, "Did not throw exception")
except Exception as e:
self.assertTrue("schema" in str(e))
if __name__ == '__main__':
unittest.main()
|
## @package model_helper
# Module caffe2.python.model_helper
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, scope, workspace, helpers
from caffe2.python.modeling import parameter_info
from caffe2.python.modeling.parameter_sharing import (
parameter_sharing_context,
)
from caffe2.python.optimizer_context import (
OptimizerContext,
DEFAULT_OPTIM,
)
from caffe2.python.regularizer_context import RegularizerContext
from future.utils import viewitems, viewkeys
from itertools import chain
import logging
import six
# _known_working_ops are operators that do not need special care.
_known_working_ops = [
"Accuracy",
"Adam",
"Add",
"Adagrad",
"SparseAdagrad",
"AveragedLoss",
"Cast",
"Checkpoint",
"ConstantFill",
"Copy",
"CopyGPUToCPU",
"CopyCPUToGPU",
"DequeueBlobs",
"EnsureCPUOutput",
"ExpandDims",
"Flatten",
"FlattenToVec",
"LabelCrossEntropy",
"LearningRate",
"MakeTwoClass",
"MatMul",
"NCCLAllreduce",
"NHWC2NCHW",
"PackSegments",
"Print",
"PRelu",
"ReduceFrontSum",
"Scale",
"ScatterWeightedSum",
"Sigmoid",
"SortedSegmentSum",
"Snapshot", # Note: snapshot is deprecated, use Checkpoint
"Softmax",
"SoftmaxWithLoss",
"SquaredL2Distance",
"Squeeze",
"StopGradient",
"Summarize",
"Tanh",
"Transpose",
"UnpackSegments",
"WeightedSum",
"YellowFin"
]
class ModelHelper(object):
"""A helper model so we can manange models more easily. It contains net def
and parameter storages. You can add an Operator yourself, e.g.
model = model_helper.ModelHelper(name="train_net")
# init your weight and bias as w and b
w = model.param_init_net.XavierFill(...)
b = model.param_init_net.ConstantFill(...)
fc1 = model.FC([input, w, b], output, **kwargs)
or you can use helper functions in brew module without manually
defining parameter initializations and operators.
model = model_helper.ModelHelper(name="train_net")
fc1 = brew.fc(model, input, output, dim_in, dim_out, **kwargs)
"""
def __init__(self, name=None, init_params=True, allow_not_known_ops=True,
skip_sparse_optim=False, param_model=None, arg_scope=None):
self.name = name or "model"
self.net = core.Net(self.name)
if param_model is not None:
self.param_init_net = param_model.param_init_net
self.param_to_grad = param_model.param_to_grad
self.params = param_model.params
self._parameters_info = param_model._parameters_info
self._computed_params = param_model._computed_params
else:
self.param_init_net = core.Net(self.name + '_init')
self.param_to_grad = {}
self.params = []
self._parameters_info = {}
self._computed_params = []
self._param_info_deprecated = []
self._devices = []
self.gradient_ops_added = False
self.init_params = init_params
self.allow_not_known_ops = allow_not_known_ops
self.skip_sparse_optim = skip_sparse_optim
self.weights = []
self.biases = []
self._arg_scope = {
'order': "NCHW",
'use_cudnn': True,
'cudnn_exhaustive_search': False,
}
if arg_scope is not None:
# Please notice value as None is not acceptable. We are not checking it
# here because we already have check in MakeArgument.
self._arg_scope.update(arg_scope)
@property
def arg_scope(self):
return self._arg_scope
def get_name(self):
return self.name
def _infer_param_shape(self, param):
for op in self.param_init_net.Proto().op:
if str(param) in op.output:
for arg in op.arg:
if arg.name == "shape":
return list(arg.ints)
return None
def _update_param_info_deprecated(self):
assert len(self._param_info_deprecated) <= len(self.params)
for param in self.params[len(self._param_info_deprecated):]:
if not isinstance(param, core.BlobReference):
raise ValueError(
"Param %s must be a BlobReference!" % str(param))
self._param_info_deprecated.append(parameter_info.ParameterInfo(
param_id=len(self._param_info_deprecated),
param=param,
shape=self._infer_param_shape(param)))
for info in self._param_info_deprecated:
info.grad = self.param_to_grad.get(info.name)
def _normalize_tags(self, tags):
tags = tags or []
return set(tags) if isinstance(tags, list) else set([tags])
def create_param(self, param_name, shape, initializer, tags=None):
"""
Creates parameter with a given name and initializer.
If param_name is instance of BlobRefernce - then this blob will be used
to store parameter (no any logic will affect it's location).
If param_name is instance of a string type, then the final blob will
be created in the CurrentNameScope with the respect of all parameter
sharing logic, i.e. 'resolved_name_scope/param_name'.
Parameter sharing logic is going to override CurrentNameScope accoring
to the rules that are specified through ParameterSharing contexts,
all ParameterSharing contexts are applied recursively until there are no
extra overrides present, where on each step the best match will be
applied first.
The following examples should clarify the way ParameterSharing logic
works:
As an example if this function is called with parameter 'w':
a. Call from some scope 'global_scope' with no Parameter sharing:
'global_scope/w'
b. Call from scope 'scope_b', with override {'scope_b': 'scope_a'}:
'scope_a/w'
c. Call from scope 'scope_a', with override {'scope_a': ''}:
'scope_a/w'
d. Call from scope 'scope_b/shared', with overrides
{'scope_b/shared': 'scope_b', 'scope_b': 'scope_a'}:
'scope_a/w'
d. Call from scope 'scope_b/unshared', with overrides
{'scope_b/shared': 'scope_b', 'scope_b': 'scope_a'}:
'scope_a/unshared/w'
"""
# ParameterSharing works only for case when param_name is instance of
# a string type. If param_name is a BlobReference - no attempt for
# ParameterSharing will be applied.
if isinstance(param_name, core.BlobReference):
param_name = str(param_name)
elif isinstance(param_name, six.string_types):
# Parameter name will be equal to current Namescope that got
# resolved with the respect of parameter sharing of the scopes.
param_name = parameter_sharing_context.get_parameter_name(
param_name)
else:
raise "Unsupported type for param_name"
if param_name in self._parameters_info:
assert self._parameters_info[param_name].shape == shape
return self._parameters_info[param_name].blob
param_info = initializer.create_param(
param_name=core.BlobReference(param_name),
init_net=self.param_init_net,
shape=shape,
)
optim_context = OptimizerContext.current()
for tag in self._normalize_tags(tags):
if optim_context.has_optimizer(tag):
# param_info will check optimizer has not been set
param_info.optimizer = optim_context.get_optimizer(tag)
if not param_info.optimizer and optim_context.has_optimizer(DEFAULT_OPTIM):
param_info.optimizer = optim_context.get_optimizer(DEFAULT_OPTIM)
reg_context = RegularizerContext.current()
param_info.regularizer = reg_context
self._parameters_info[param_name] = param_info
# Add param to legacy structs as well, so all other functions for
# parameters are still working.
self.AddParameter(param_info.blob, tags)
return param_info.blob
def get_param_info(self, param):
assert isinstance(param, core.BlobReference), \
"Param {} is not a BlobReference".format(param)
return self._parameters_info.get(param, None)
# This method is deprecated, use create_param method which
# also does parameter initialization when needed
def add_param_DEPRECATED(self, param, key=None, shape=None, length=None):
logging.warning("add_param method is DEPRECATED")
self._update_param_info_deprecated()
self.AddParameter(param)
if key is not None and self.net.input_record() is not None:
idx = self.net.input_record().field_blobs().index(key)
key = self.net.input_record().field_names()[idx]
shape = shape if shape is not None else self._infer_param_shape(param)
if not isinstance(param, core.BlobReference):
raise ValueError("Param %s must be a BlobReference!" % str(param))
self._param_info_deprecated.append(parameter_info.ParameterInfo(
param_id=len(self._param_info_deprecated),
param=param,
shape=shape,
key=key,
length=length,
))
return self._param_info_deprecated[-1]
# This method is deprecated, use get_param_info method
def param_info(self, grad_type=None, id=None):
logging.info("param_info method is DEPRECATED")
self._update_param_info_deprecated()
if id is not None:
assert grad_type is None
info = self._param_info_deprecated[id]
assert info.param_id == id
return info
elif grad_type is not None:
return [
info for info in self._param_info_deprecated
if info.grad_type() == grad_type]
else:
return self._param_info_deprecated
def AddParameter(self, param, tags=None):
assert isinstance(param, core.BlobReference)
tags = self._normalize_tags(tags)
if parameter_info.ParameterTags.COMPUTED_PARAM in tags:
self._computed_params.append(param)
else:
self.params.append(param)
if parameter_info.ParameterTags.WEIGHT in tags:
self.weights.append(param)
if parameter_info.ParameterTags.BIAS in tags:
self.biases.append(param)
@staticmethod
def _NormalizeNamescope(namescope):
if namescope is None:
return scope.CurrentNameScope()
elif namescope == '' or namescope.endswith(scope._NAMESCOPE_SEPARATOR):
return namescope
else:
return namescope + scope._NAMESCOPE_SEPARATOR
def GetParams(self, namescope=None, top_scope=False):
'''
Returns the params in current namescope
'''
namescope = ModelHelper._NormalizeNamescope(namescope)
if namescope == '':
return self.params[:]
elif top_scope:
return [
p for p in self.params
if p.GetNameScope().startswith(namescope)
]
else:
return [p for p in self.params if
p.GetNameScope().startswith(namescope)]
def Proto(self):
return self.net.Proto()
def InitProto(self):
return self.param_init_net.Proto()
def RunAllOnGPU(self, *args, **kwargs):
self.param_init_net.RunAllOnGPU(*args, **kwargs)
self.net.RunAllOnGPU(*args, **kwargs)
def CreateDB(self, blob_out, db, db_type, **kwargs):
dbreader = self.param_init_net.CreateDB(
[], blob_out, db=db, db_type=db_type, **kwargs)
return dbreader
def AddGradientOperators(self, *args, **kwargs):
if self.gradient_ops_added:
raise RuntimeError("You cannot run AddGradientOperators twice.")
self.Validate()
self.gradient_ops_added = True
self.grad_map = self.net.AddGradientOperators(*args, **kwargs)
self.param_to_grad = self.get_param_to_grad(self.params)
# Populate ParameterInfo for all parameters if missing
# and add gradient blob information. So optimizers can use it
for param, grad in self.param_to_grad.items():
param_info = self.get_param_info(param)
if param_info:
param_info.grad = grad
else:
self._parameters_info[param] = parameter_info.ParameterInfo(
param_id=None,
param=param,
grad=grad,
)
return self.grad_map
def get_param_to_grad(self, params):
'''
Given a list of parameters returns a dict from a parameter
to a corresponding gradient
'''
param_to_grad = {}
if not self.gradient_ops_added:
raise RuntimeError("You need to run AddGradientOperators first.")
# We need to use empty namescope when creating the gradients
# to prevent duplicating the namescope prefix for gradient blobs.
for p in params:
if str(p) in self.grad_map:
param_to_grad[p] = self.grad_map[str(p)]
return param_to_grad
def GetOptimizationParamInfo(self, params=None):
'''
Returns a map for param => grad.
If params is not specified, all parameters will be considered.
'''
if not self.gradient_ops_added:
raise RuntimeError("Need to call AddGradientOperators first")
param_to_grad = self.param_to_grad
if params:
param_to_grad = self.get_param_to_grad(params)
return [
self.get_param_info(param) for param, grad in viewitems(param_to_grad)
if (
not self.skip_sparse_optim or
not isinstance(grad, core.GradientSlice)
)
]
def _Validate(self):
'''
Check for duplicate params
'''
params_list = [str(p) for p in self.params]
params_set = set(params_list)
dupes = []
if len(params_set) != len(params_list):
params_list = sorted(params_list)
for j, p in enumerate(params_list):
if j > 0 and params_list[j - 1] == p:
if p not in dupes:
dupes.append(p)
return dupes
def Validate(self):
dupes = self._Validate()
assert dupes == [], "Duplicate params: {}".format(dupes)
def GetComputedParams(self, namescope=None):
'''
Returns the computed params in current namescope. 'Computed params'
are such parameters that are not optimized via gradient descent but are
directly computed from data, such as the running mean and variance
of Spatial Batch Normalization.
'''
namescope = ModelHelper._NormalizeNamescope(namescope)
if namescope == '':
return self._computed_params[:]
else:
return [p for p in self._computed_params
if p.GetNameScope().startswith(namescope)]
def GetAllParams(self, namescope=None):
return self.GetParams(namescope) + self.GetComputedParams(namescope)
def TensorProtosDBInput(
self, unused_blob_in, blob_out, batch_size, db, db_type, **kwargs
):
"""TensorProtosDBInput."""
assert len(unused_blob_in) == 0, \
"""You cannot pass reader to model_helper.TensorProtosDBInput.
Use model.net.TensorProtosDBInput instead to create the op."""
return helpers.db_input.db_input(
self, blob_out, batch_size, db, db_type, **kwargs)
def GetDevices(self):
assert len(self._devices) > 0, \
"Use data_parallel_model to run model on multiple GPUs."
return self._devices
def __getattr__(self, op_type):
"""Catch-all for all other operators, mostly those without params."""
if op_type.startswith('__'):
raise AttributeError(op_type)
if not core.IsOperator(op_type):
raise AttributeError(
'Method ' + op_type + ' is not a registered operator.' +
' Did you mean: [' +
','.join(workspace.C.nearby_opnames(op_type)) + ']'
)
if op_type not in _known_working_ops:
if not self.allow_not_known_ops:
raise AttributeError(
"Operator {} is not known to be safe".format(op_type))
logging.warning("You are creating an op that the ModelHelper "
"does not recognize: {}.".format(op_type))
return self.net.__getattr__(op_type)
def __dir__(self):
return sorted(set(chain(
dir(type(self)),
viewkeys(self.__dict__),
_known_working_ops
)))
def ExtractPredictorNet(
net_proto,
input_blobs,
output_blobs,
device=None,
renames=None,
disabled_inputs=None,
):
'''
Takes a model net for training and returns a net which can be
used for prediction. For example, all gradient operators and
input operators are removed.
@param net_proto protobuf of the net you want to process (net.Proto())
@param input_blobs list/set of blob names that are the inputs of predictor
@param output_blobs list/set of blob names that are outputs of predictor
@param device optional device option that is assigned
@param renames dictionary of blob name to a new name (optional)
@param disabled_inputs optional set of blobs that are 'switched off'. This
will cause branches with those blobs as inputs to be removed
'''
predict_net = core.Net(net_proto.name + "_predict")
predict_proto = predict_net.Proto()
orig_external_inputs = set(net_proto.external_input)
orig_external_outputs = set(net_proto.external_output)
input_blobs = {str(b) for b in input_blobs}
known_blobs = set(orig_external_inputs).union(input_blobs)
output_blobs = {str(b) for b in output_blobs}
external_inputs = set(input_blobs)
external_outputs = set(output_blobs)
if renames is None:
renames = {}
if disabled_inputs is not None:
known_blobs = known_blobs - set(disabled_inputs)
ops = list(net_proto.op)
# Find the range of ops that we should include
try:
first_op_with_input = min(
[
j for j in range(len(ops))
if input_blobs.intersection(ops[j].input) and ops[j].type !=
'StopGradient'
]
)
except ValueError:
raise Exception("No ops with input={}".format(input_blobs))
try:
last_op_with_output = max(
[
j for j in range(len(ops))
if output_blobs.intersection(ops[j].output)
]
)
except ValueError:
raise Exception("No ops with output={}".format(output_blobs))
def validate_op(op):
# Check that the op does not have is_test = 0 set. This is a common
# pitfall with SpatialBN op, at lest.
for arg in op.arg:
if arg.name == "is_test" and arg.i == 0:
raise Exception(
"An operator had is_test=0, did you try to extract a " +
"predictor from a train model (instead of test model)?" +
" Op was: {}".format(str(op))
)
def rename_list(proto_list):
# proto lists don't support assignments
new_list = proto_list[:]
for j, b in enumerate(new_list):
if b in renames:
new_list[j] = renames[b]
del proto_list[:]
proto_list.extend(new_list)
# Iterate through the ops and only include those whose inputs
# we can satisfy.
for op in ops[first_op_with_input:(last_op_with_output + 1)]:
if known_blobs.issuperset(op.input):
# Special handling for recurrent nets
# TODO: when standard argument type for "nets" is introduced,
# this can be more general
if op.type == 'RecurrentNetwork':
for arg in op.arg:
if arg.name == 'backward_step_net':
arg.ClearField(str('n'))
elif arg.name == 'step_net':
for step_op in arg.n.op:
rename_list(step_op.input)
rename_list(step_op.output)
if device is not None:
step_op.device_option.device_type = device.device_type
step_op.device_option.cuda_gpu_id = device.cuda_gpu_id
rename_list(arg.n.external_input)
rename_list(arg.n.external_output)
# Add additional external inputs
external_inputs.update(
set(arg.n.external_input).intersection(
orig_external_inputs
)
)
if device is not None:
op.device_option.device_type = device.device_type
op.device_option.cuda_gpu_id = device.cuda_gpu_id
validate_op(op)
predict_proto.op.extend([op])
known_blobs.update(op.output)
external_inputs.update(
set(op.input).intersection(orig_external_inputs)
)
external_outputs.update(
set(op.output).intersection(orig_external_outputs)
)
else:
logging.debug(
"Op {} had unknown inputs: {}".format(
op.type, set(op.input).difference(known_blobs)
)
)
# Predictor net's external inputs and outputs include only those
# that are part of this net.
predict_proto.external_input.extend(external_inputs)
predict_proto.external_output.extend(external_outputs)
rename_list(predict_proto.external_input)
rename_list(predict_proto.external_output)
renamed_input_blobs = []
for b in input_blobs:
if b in renames:
renamed_input_blobs.append(renames[b])
else:
renamed_input_blobs.append(b)
for op in predict_proto.op:
rename_list(op.input)
rename_list(op.output)
return predict_net, list(
set(predict_proto.external_input) - set(renamed_input_blobs)
)
|
## @package optimizer
# Module caffe2.python.optimizer
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple, defaultdict
from past.builtins import basestring
import numpy as np
from caffe2.python import core, scope, workspace
from caffe2.python.modeling import parameter_info
from caffe2.proto import caffe2_pb2
_OPTIMIZER_ITERATION_NAME = "optimizer_iteration"
_LEARNING_RATE_INJECTION = "lr_injection"
AuxOptimizerParams = namedtuple("AuxOptimizerParams", ["local", "shared"])
_optimizer_instance_count = defaultdict(int)
class Optimizer(object):
def __init__(self):
self._aux_params = AuxOptimizerParams(local=[], shared=[])
self._instance_num = _optimizer_instance_count[self.__class__.__name__]
_optimizer_instance_count[self.__class__.__name__] += 1
self._lr_multiplier = None
self._lr_multiplier_on_gpu = False
'''
Adds optimization operators to the net for given parameter and its gradient
Parameter is specified by either 'param' being a ParameterInfo object.
In this case param.grad has to be set
Or by 'param' being a BlobReference and 'grad' being a BlobReference for its
gradient.
'''
def __call__(self, net, param_init_net, param, grad=None):
if grad is None:
assert isinstance(param, parameter_info.ParameterInfo), (
"Expected parameter to be of type ParameterInfo, got {}".format(
param
))
assert param.grad is not None
else:
if isinstance(param, basestring):
param = core.BlobReference(param)
param = parameter_info.ParameterInfo(
param_id=None, param=param, grad=grad)
self._run(net, param_init_net, param)
def _run(self, net, param_init_net, param_info):
raise Exception("Not Implemented")
def get_cpu_blob_name(self, base_str, node_name=''):
classname = self.__class__.__name__
return '%s_%d_%s%s_cpu' % (classname, self._instance_num, base_str, node_name)
def get_gpu_blob_name(self, base_str, gpu_id, node_name):
classname = self.__class__.__name__
return '%s_%d_%s%s_gpu%d' % (
classname, self._instance_num, base_str, node_name, gpu_id,
)
def make_unique_blob_name(self, base_str):
"""
Returns a blob name that will be unique to the current device
and optimizer instance.
"""
current_scope = scope.CurrentDeviceScope()
if current_scope is None:
return self.get_cpu_blob_name(base_str)
if current_scope.device_type == caffe2_pb2.CUDA:
return self.get_gpu_blob_name(
base_str, current_scope.cuda_gpu_id, current_scope.node_name
)
else:
return self.get_cpu_blob_name(base_str, current_scope.node_name)
def build_lr(self, net, param_init_net, base_learning_rate,
learning_rate_blob=None, policy="fixed",
iter_val=0, **kwargs):
if learning_rate_blob is None:
learning_rate_blob = self.make_unique_blob_name('lr')
optimization_iter_blob = _OPTIMIZER_ITERATION_NAME
if not param_init_net.BlobIsDefined(optimization_iter_blob):
# Add training operators.
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
iteration = param_init_net.ConstantFill(
[], optimization_iter_blob, shape=[1],
value=iter_val,
dtype=core.DataType.INT64)
iter_mutex = param_init_net.CreateMutex(
[], ["iteration_mutex"]
)
net.AtomicIter([iter_mutex, iteration], [iteration])
else:
iteration = param_init_net.GetBlobRef(optimization_iter_blob)
if not net.BlobIsDefined(learning_rate_blob):
# There is one interesting thing here: since we are minimizing, we are
# doing "descent" so the learning rate is set to be negative.
lr = net.LearningRate(
[iteration],
learning_rate_blob,
base_lr=-base_learning_rate,
policy=policy,
**kwargs
)
else:
lr = net.GetBlobRef(learning_rate_blob)
if self._lr_multiplier is not None:
current_scope = scope.CurrentDeviceScope()
if (current_scope is not None
and current_scope.device_type == caffe2_pb2.CUDA
and not self._lr_multiplier_on_gpu):
lr_multiplier = net.CopyFromCPUInput(
self._lr_multiplier,
self.make_unique_blob_name('lr_multiplier')
)
else:
lr_multiplier = self._lr_multiplier
scaled_lr = net.Mul(
[lr, lr_multiplier],
self.make_unique_blob_name('scaled_lr'),
broadcast=1,
)
lr = scaled_lr
return lr, iteration
def add_lr_multiplier(self, lr_multiplier, is_gpu_blob=False):
self._lr_multiplier = lr_multiplier
self._lr_multiplier_on_gpu = is_gpu_blob
@staticmethod
def dedup(net, sparse_dedup_aggregator, grad):
assert isinstance(grad, core.GradientSlice), (
"Dedup only works for sparse gradient, got {}".format(grad))
if sparse_dedup_aggregator:
return net.DeduplicateGradientSlices(
grad, aggregator=sparse_dedup_aggregator)
else:
return grad
def get_auxiliary_parameters(self):
"""Returns a list of auxiliary parameters.
Returns:
aux_params: A namedtuple, AuxParams.
aux_params.local stores a list of blobs. Each blob is a local
auxiliary parameter. A local auxiliary parameter is a parameter in
parallel to a learning rate parameter. Take adagrad as an example,
the local auxiliary parameter is the squared sum parameter, because
every learning rate has a squared sum associated with it.
aux_params.shared also stores a list of blobs. Each blob is a shared
auxiliary parameter. A shared auxiliary parameter is a parameter
that is shared across all the learning rate parameters. Take adam as
an example, the iteration parameter is a shared parameter, because
all the learning rates share the same iteration parameter.
"""
return self._aux_params
# TODO(xlwang): In transfer learning, parameter initialized from pretrained
# model might require a different learning rate than otherwise initialized.
# To this end, here we implement a python solution where
# `base_learning_rate` is scaled by `scale`, by calling
# `scale_learning_rate`; Alternatively, we can achieve same effect by
# rewriting the LearningRate operator in C++
# Note that it is the responsibility of specific optimizer to decide what
# logic should be used for `scale_learning_rate`
def scale_learning_rate(self, *args, **kwargs):
raise NotImplementedError(
"Optimizer Need to Implement `scale_learning_rate` method.")
class SgdOptimizer(Optimizer):
def __init__(self, base_learning_rate=0.01, policy='fixed',
momentum=0.0, nesterov=1, sparse_dedup_aggregator=None,
lars=None, **kwargs):
super(SgdOptimizer, self).__init__()
self.base_learning_rate = base_learning_rate
self.policy = policy
self.momentum = momentum
self.nesterov = nesterov
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.lars = lars
self.init_kwargs = kwargs
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
if self.base_learning_rate == 0:
return
assert self.base_learning_rate > 0, (
"Expect positive base learning rate, got {}".format(
self.base_learning_rate))
# TODO(zqq): support LARS for sparse parameters
if self.lars is not None and not isinstance(grad, core.GradientSlice):
assert self.lars >= 0, (
'Lars offset must be nonnegative, got {}'.format(self.lars))
lr_lars_multiplier = net.Lars(
[param, grad],
self.make_unique_blob_name(str(param) + "_lars"),
offset=self.lars)
current_scope = scope.CurrentDeviceScope()
self.add_lr_multiplier(
lr_lars_multiplier,
is_gpu_blob=(current_scope is not None
and current_scope.device_type == caffe2_pb2.CUDA),
)
# We need negative sign for LR when used directly with WeightedSum
# below.
lr_sign = -1 if self.momentum else 1
lr, _ = self.build_lr(
net, param_init_net,
base_learning_rate=self.base_learning_rate * lr_sign,
policy=self.policy,
**(self.init_kwargs)
)
dev = scope.CurrentDeviceScope()
if dev is None:
dev = core.DeviceOption(caffe2_pb2.CPU)
# Each GPU/CPU must have its own ONE blob, thus modify the name
# to include device information.
ONE = param_init_net.ConstantFill(
[],
"ONE_{}_{}{}".format(dev.device_type, dev.cuda_gpu_id, dev.node_name),
shape=[1],
value=1.0
)
self._aux_params.shared.append(ONE)
if self.momentum > 0:
momentum_data = param_init_net.ConstantFill(
param, str(param) + "_momentum", value=0.)
self._aux_params.local.append(momentum_data)
if isinstance(grad, core.GradientSlice):
grad = self.dedup(net, self.sparse_dedup_aggregator, grad)
if self.momentum > 0.:
net.SparseMomentumSGDUpdate(
[grad.values, momentum_data, lr, param, grad.indices],
[grad.values, momentum_data, param],
momentum=self.momentum,
nesterov=self.nesterov)
else:
net.ScatterWeightedSum(
[param, ONE, grad.indices, grad.values, lr],
param
)
else:
if self.momentum > 0.:
net.MomentumSGDUpdate(
[grad, momentum_data, lr, param],
[grad, momentum_data, param],
momentum=self.momentum,
nesterov=self.nesterov)
else:
coeff = lr
net.WeightedSum(
[param, ONE, grad, coeff],
param
)
def scale_learning_rate(self, scale):
self.base_learning_rate *= scale
return
class MultiPrecisionSgdOptimizer(SgdOptimizer):
def __init__(self, base_learning_rate=0.1, momentum=0.0,
policy="fixed", nesterov=1, sparse_dedup_aggregator=None,
**kwargs):
super(MultiPrecisionSgdOptimizer, self).__init__(
base_learning_rate=base_learning_rate,
policy=policy,
momentum=momentum,
nesterov=nesterov,
sparse_dedup_aggregator=sparse_dedup_aggregator,
**kwargs
)
def _run(self, net, param_init_net, param_info):
param = param_info.blob
param_fp32 = param_info.blob_copy[core.DataType.FLOAT] \
if param_info.blob_copy is not None else None
# If we have a straight fp32 parameter, run the base class
if param_fp32 is None:
return SgdOptimizer._run(self, net, param_init_net, param_info)
grad = param_info.grad
if self.base_learning_rate == 0:
return
assert self.base_learning_rate > 0, (
"Expect positive base learning rate, got {}".format(
self.base_learning_rate))
lr, _ = self.build_lr(
net, param_init_net,
base_learning_rate=-self.base_learning_rate,
policy=self.policy,
**(self.init_kwargs)
)
momentum_data = param_init_net.ConstantFill(
param_fp32, str(param) + "_momentum", value=0.)
self._aux_params.local.append(momentum_data)
assert not isinstance(grad, core.GradientSlice), (
"MultiPrecisionSgd does not support sparse gradients")
# Copy gradient to fp32
grad_fp32 = net.HalfToFloat(grad, grad + "_fp32")
# update (fused) in fp32
net.MomentumSGDUpdate(
[grad_fp32, momentum_data, lr, param_fp32],
[grad_fp32, momentum_data, param_fp32],
momentum=self.momentum,
nesterov=self.nesterov)
# Copy updated param back to fp16
net.FloatToHalf(param_fp32, param)
class FP16SgdOptimizer(SgdOptimizer):
def __init__(self, base_learning_rate=0.1, momentum=0.0,
policy="fixed", nesterov=1, weight_decay=0.0001,
sparse_dedup_aggregator=None,
**kwargs):
super(FP16SgdOptimizer, self).__init__(
base_learning_rate=base_learning_rate,
policy=policy,
momentum=momentum,
nesterov=nesterov,
sparse_dedup_aggregator=sparse_dedup_aggregator,
**kwargs
)
self.weight_decay = weight_decay
def _run(self, net, param_init_net, param_info, fp32_update=False):
fp32_update_flag = 0
param_name = str(param_info.blob)
# should only be triggered in FP16 training by SpatialBN, which
# requires FP32 params in CuDNN.
if param_name.find("spatbn") != -1:
fp32_update = True
if fp32_update:
# doing a 32bit update
# Have to assume param_info.blob is FP32 as there is no way
# (that i currently know of) to query a blob's type in python
fp32_update_flag = 1
param = param_info.blob
param_fp32 = param_info.blob
else:
if param_info.blob_copy is None:
# doing a 32bit update
# Have to assume param_info.blob is FP32 as there is no way
# (that i currently know of) to query a blob's type in python
fp32_update_flag = 1
param = param_info.blob
param_fp32 = param_info.blob
else:
if core.DataType.FLOAT in param_info.blob_copy:
param = param_info.blob
param_fp32 = param_info.blob_copy[core.DataType.FLOAT]
elif core.DataType.FLOAT16 in param_info.blob_copy:
param = param_info.blob_copy[core.DataType.FLOAT16]
param_fp32 = param_info.blob
else:
assert (False), (
"Unrecognized parameter format to be updated "
"by FP16 Optimizer. Parameter: {}".format(param_info.name)
)
grad = param_info.grad
if self.base_learning_rate == 0:
return
assert self.base_learning_rate > 0, (
"Expect positive base learning rate, got {}".format(
self.base_learning_rate))
lr, _ = self.build_lr(
net, param_init_net,
base_learning_rate=-self.base_learning_rate,
policy=self.policy,
**(self.init_kwargs)
)
momentum_data_fp32 = param_init_net.ConstantFill(
param_fp32, str(param) + "_momentum_fp32", value=0.)
momentum_data = param_init_net.FloatToHalf(
momentum_data_fp32, str(param) + "_momentum")
self._aux_params.local.append(momentum_data)
assert not isinstance(grad, core.GradientSlice), (
"FP16Sgd does not support sparse gradients")
if fp32_update_flag == 0:
net.FP16MomentumSGDUpdate(
[grad, momentum_data, lr, param],
[grad, momentum_data, param],
momentum=self.momentum,
nesterov=self.nesterov,
weight_decay=self.weight_decay)
else:
# flag set to 1, therefore doing FP32 update
net.FP32MomentumSGDUpdate(
[grad, momentum_data_fp32, lr, param],
[grad, momentum_data_fp32, param],
momentum=self.momentum,
nesterov=self.nesterov,
weight_decay=self.weight_decay)
class WeightDecayBuilder(Optimizer):
def __init__(self, weight_decay):
self.weight_decay = weight_decay
def _run(self, net, param_init_net, param_info):
dev = scope.CurrentDeviceScope()
if dev is None:
dev = core.DeviceOption(caffe2_pb2.CPU)
ONE = param_init_net.ConstantFill(
[],
"ONE_{}_{}".format(dev.device_type, dev.cuda_gpu_id),
shape=[1],
value=1.0
)
WD = param_init_net.ConstantFill(
[], "wd_{}_{}".format(dev.device_type, dev.cuda_gpu_id),
shape=[1], value=self.weight_decay
)
if isinstance(param_info.grad, core.GradientSlice):
raise ValueError(
"Weight decay does not yet support sparse gradients")
else:
net.WeightedSum(
[param_info.grad, ONE, param_info.blob, WD],
param_info.grad,
)
class AdagradOptimizer(Optimizer):
def __init__(self, alpha=0.01, epsilon=1e-4, decay=1, policy="fixed",
sparse_dedup_aggregator=None, rowWise=False, engine='',
lars=None, **kwargs):
super(AdagradOptimizer, self).__init__()
self.alpha = alpha
self.epsilon = epsilon
self.decay = decay
self.policy = policy
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.rowWise = rowWise
self.engine = engine
self.lars = lars
self.init_kwargs = kwargs
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
if self.alpha <= 0:
return
if self.lars is not None and not isinstance(grad, core.GradientSlice):
assert self.lars >= 0, (
'Lars offset must be nonnegative, got {}'.format(self.lars))
lr_lars_multiplier = net.Lars(
[param, grad],
self.make_unique_blob_name(str(param) + "_lars"),
offset=self.lars)
current_scope = scope.CurrentDeviceScope()
self.add_lr_multiplier(
lr_lars_multiplier,
is_gpu_blob=(current_scope is not None
and current_scope.device_type == caffe2_pb2.CUDA),
)
lr, _ = self.build_lr(
net, param_init_net,
base_learning_rate=self.alpha,
policy=self.policy,
**(self.init_kwargs)
)
if self.rowWise:
shapes, types = workspace.InferShapesAndTypes([param_init_net])
if str(param) not in shapes:
# Type/shape inference is not available for this param, fallback
# on Shape/Slice logic
shape = param_init_net.Shape(param, str(param) + "_shape")
num_rows = param_init_net.Slice(
[shape],
str(shape) + "_numrows",
starts=[0], ends=[1]
)
param_squared_sum = param_init_net.ConstantFill(
num_rows,
str(param) + "_avg_squared_sum",
input_as_shape=1,
value=0.0
)
else:
param_squared_sum = param_init_net.ConstantFill(
[],
str(param) + "_avg_squared_sum",
shape=[shapes[str(param)][0]],
value=0.0
)
else:
param_squared_sum = param_init_net.ConstantFill(
[param],
str(param) + "_squared_sum",
value=0.0
)
self._aux_params.local.append(param_squared_sum)
if self.rowWise:
assert isinstance(grad, core.GradientSlice),\
'If SparseAdagrad with rowWise=True, gradient must be '\
'a gradientslice. PLease ensure that rowWise is not enabled '\
'for the dense Adagrad optimizer, as it is not supported.'
if isinstance(grad, core.GradientSlice):
assert self.decay == 1.,\
'Decay is not implemented for SparseAdagrad and must be set to 1'
grad = self.dedup(net, self.sparse_dedup_aggregator, grad)
if self.rowWise:
op = 'RowWiseSparseAdagrad'
else:
op = 'SparseAdagrad'
net.__getattr__(op)(
[param, param_squared_sum, grad.indices, grad.values, lr],
[param, param_squared_sum],
epsilon=self.epsilon,
engine=self.engine
)
else:
net.Adagrad(
[param, param_squared_sum, grad, lr],
[param, param_squared_sum],
epsilon=self.epsilon,
decay=float(self.decay),
engine=self.engine
)
def scale_learning_rate(self, scale):
self.alpha *= scale
return
class FtrlOptimizer(Optimizer):
def __init__(self, alpha=0.01, beta=1e-4, lambda1=0, lambda2=0,
sparse_dedup_aggregator=None, engine=''):
super(FtrlOptimizer, self).__init__()
self.alpha = alpha
self.beta = beta
self.lambda1 = lambda1
self.lambda2 = lambda2
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.engine = engine
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
if self.alpha <= 0:
return
nz = param_init_net.ConstantFill(
[param],
str(param) + "_ftrl_nz",
extra_shape=[2],
value=0.0
)
self._aux_params.local.append(nz)
if isinstance(grad, core.GradientSlice):
grad = self.dedup(net, self.sparse_dedup_aggregator, grad)
net.SparseFtrl(
[param, nz, grad.indices, grad.values],
[param, nz],
engine=self.engine,
alpha=self.alpha,
beta=self.beta,
lambda1=self.lambda1,
lambda2=self.lambda2
)
else:
net.Ftrl(
[param, nz, grad],
[param, nz],
engine=self.engine,
alpha=self.alpha,
beta=self.beta,
lambda1=self.lambda1,
lambda2=self.lambda2
)
def scale_learning_rate(self, scale):
self.alpha *= scale
return
class AdamOptimizer(Optimizer):
def __init__(self, alpha=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8,
policy='fixed', sparse_dedup_aggregator=None, rowWise=False,
engine='', **kwargs):
super(AdamOptimizer, self).__init__()
self.alpha = alpha
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.policy = policy
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.rowWise = rowWise
self.engine = engine
self.init_kwargs = kwargs
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
if self.alpha <= 0:
return
lr, iteration = self.build_lr(
net, param_init_net,
base_learning_rate=self.alpha,
policy=self.policy,
**(self.init_kwargs)
)
m1 = param_init_net.ConstantFill(
[param],
param + "_first_moment",
value=0.0
)
if self.rowWise:
shapes, types = workspace.InferShapesAndTypes([param_init_net])
m2 = param_init_net.ConstantFill(
[],
param + "_avg_second_moment",
shape=[shapes[param][0]],
value=0.0
)
else:
m2 = param_init_net.ConstantFill(
[param],
param + "_second_moment",
value=0.0
)
self._aux_params.shared.append(iteration)
self._aux_params.local.append(m1)
self._aux_params.local.append(m2)
if self.rowWise:
assert isinstance(grad, core.GradientSlice),\
'If SparseAdam with rowWise=True, gradient must be '\
'a gradientslice. PLease ensure that rowWise is not enabled '\
'for the dense Adam optimizer, as it is not supported.'
if isinstance(grad, core.GradientSlice):
grad = self.dedup(net, self.sparse_dedup_aggregator, grad)
if self.rowWise:
op = 'RowWiseSparseAdam'
else:
op = 'SparseAdam'
net.__getattr__(op)(
[param, m1, m2, grad.indices, grad.values, lr, iteration],
[param, m1, m2],
beta1=self.beta1,
beta2=self.beta2,
epsilon=self.epsilon
)
else:
net.Adam(
[param, m1, m2, grad, lr, iteration],
[param, m1, m2],
beta1=self.beta1,
beta2=self.beta2,
epsilon=self.epsilon)
def scale_learning_rate(self, scale):
self.alpha *= scale
return
class YellowFinOptimizer(Optimizer):
"""YellowFin: An automatic tuner for momentum SGD
See https://arxiv.org/abs/1706.03471 for more details. This implementation
has separate learning rate and momentum per each parameter."""
def __init__(self,
alpha=0.1,
mu=0.0,
beta=0.999,
curv_win_width=20,
zero_debias=True,
epsilon=0.1**6,
policy='fixed',
sparse_dedup_aggregator=None,
**kwargs):
super(YellowFinOptimizer, self).__init__()
self.alpha = alpha
self.mu = mu
self.beta = beta
self.curv_win_width = curv_win_width
self.zero_debias = zero_debias
self.epsilon = epsilon
self.policy = policy
self.sparse_dedup_aggregator = sparse_dedup_aggregator
self.init_kwargs = kwargs
def _run(self, net, param_init_net, param_info):
# Note: This is number of persistent scalars in YellowFin optimizer.
# It should always be the number of scalars being used. The same
# number should be used in class for the operation.
SCALARS_MEMORY_SIZE = 5
param = param_info.blob
grad = param_info.grad
moment = param_init_net.ConstantFill(
[param],
param + "_moment",
value=0.0
)
curv_win = param_init_net.ConstantFill(
[],
param + "_curv_win",
shape=[self.curv_win_width],
value=0.0
)
g_avg = param_init_net.ConstantFill(
[param],
param + "_g_avg",
value=0.0
)
g2_avg = param_init_net.ConstantFill(
[param],
param + "_g2_avg",
value=0.0
)
lr_avg = param_init_net.ConstantFill(
[],
param + "_lr_avg",
shape=[1],
value=self.alpha
)
mu_avg = param_init_net.ConstantFill(
[],
param + "_mu_avg",
shape=[1],
value=self.mu
)
scalars_memory = param_init_net.ConstantFill(
[],
param + "_scalars_memory",
shape=[SCALARS_MEMORY_SIZE],
value=0.0
)
assert self.alpha > 0
assert not isinstance(grad, core.GradientSlice), \
"YellowFin does not support sparse gradients"
if not param_init_net.BlobIsDefined(_OPTIMIZER_ITERATION_NAME):
# Add training operators.
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
iteration = param_init_net.ConstantFill(
[],
_OPTIMIZER_ITERATION_NAME,
shape=[1],
value=0,
dtype=core.DataType.INT64)
iter_mutex = param_init_net.CreateMutex([],
["iteration_mutex"])
net.AtomicIter([iter_mutex, iteration], [iteration])
else:
iteration = param_init_net.GetBlobRef(_OPTIMIZER_ITERATION_NAME)
self._aux_params.shared.append(iteration)
self._aux_params.local.append(moment)
self._aux_params.local.append(lr_avg)
self._aux_params.local.append(mu_avg)
self._aux_params.local.append(curv_win)
self._aux_params.local.append(g_avg)
self._aux_params.local.append(g2_avg)
self._aux_params.local.append(scalars_memory)
yf_in_out_args = [
param,
moment,
lr_avg,
mu_avg,
curv_win,
g_avg,
g2_avg,
scalars_memory
]
net.YellowFin(
yf_in_out_args + [grad, iteration],
yf_in_out_args,
beta=self.beta,
epsilon=self.epsilon,
curv_win_width=self.curv_win_width,
zero_debias=self.zero_debias)
def scale_learning_rate(self, scale):
self.alpha *= scale
return
class RmsPropOptimizer(Optimizer):
def __init__(
self,
alpha=0.01,
decay=0.9,
momentum=0.0,
epsilon=1e-5,
policy='fixed',
engine='',
**kwargs
):
super(RmsPropOptimizer, self).__init__()
self.alpha = alpha
self.decay = decay
self.momentum = momentum
self.epsilon = epsilon
self.policy = policy
self.engine = engine
self.init_kwargs = kwargs
def _run(self, net, param_init_net, param_info):
param = param_info.blob
grad = param_info.grad
assert self.alpha > 0
assert not isinstance(grad, core.GradientSlice), \
"RmsPropOptimizer doesn't support sparse gradients"
dev = scope.CurrentDeviceScope()
if dev is None:
dev = core.DeviceOption(caffe2_pb2.CPU)
ONE = param_init_net.ConstantFill(
[],
"ONE_{}_{}".format(dev.device_type, dev.cuda_gpu_id),
shape=[1],
value=1.0
)
lr, _ = self.build_lr(
net,
param_init_net,
base_learning_rate=-self.alpha,
policy=self.policy,
**(self.init_kwargs)
)
grad_o = param_init_net.ConstantFill(
[param],
str(param) + "_grad_o",
values=0.0,
)
ms = param_init_net.ConstantFill(
[param],
str(param) + "_mean_squares",
values=0.0,
)
mom = param_init_net.ConstantFill(
[param],
str(param) + "_momentum",
values=0.0,
)
self._aux_params.local.append(ms)
self._aux_params.local.append(mom)
net.RmsProp(
[grad, ms, mom, ONE],
[grad_o, ms, mom],
decay=self.decay,
momentum=self.momentum,
epsilon=self.epsilon,
engine=self.engine,
)
net.MomentumSGDUpdate(
[grad_o, mom, lr, param],
[grad_o, mom, param],
)
def scale_learning_rate(self, scale):
self.alpha *= scale
return
def _get_param_to_device(model):
# Infer blob devices by going through the net and param_init_net
# ops and observing the device used to create or use the blob.
param_to_device = core.InferBlobDevices(model.net)
param_to_device.update(core.InferBlobDevices(model.param_init_net))
return param_to_device
def get_param_device(param_name, grad, param_to_device=None, default_device=None):
device = default_device
param_to_device = param_to_device or {}
# We first check if parameter's device has been inferred. If not,
# we check the gradient. This can happen if parameter is not output
# by any blob but created by a FetchBlob.
if param_name in param_to_device:
device = param_to_device[param_name]
else:
if isinstance(grad, core.GradientSlice):
grad = grad
if str(grad.values) in param_to_device:
device = param_to_device[str(grad.values)]
elif str(grad.indices) in param_to_device:
device = param_to_device[str(grad.indices)]
else:
grad_name = str(grad)
if grad_name in param_to_device:
device = param_to_device[grad_name]
assert device is not None,\
"Cannot infer device for {}: no op creates it".format(param_name)
return device
def get_lr_injection():
"""
Gets current value for lr_injection, a multiplier for all base
learning rates.
Must set allow_lr_injection=True when building optimizer, as it
relies on synchronization over CPU.
"""
return workspace.FetchBlob(_LEARNING_RATE_INJECTION)
def set_lr_injection(lr_injection_value):
"""
Sets lr_injection, a multiplier for all base learning rates.
Must set allow_lr_injection=True when building optimizer, as it
relies on synchronization over CPU.
"""
workspace.FeedBlob(
_LEARNING_RATE_INJECTION,
np.array(
[float(lr_injection_value)],
dtype=np.float32,
),
)
def _calc_norm_ratio(
model, params, name_scope, param_to_device, max_gradient_norm
):
with core.NameScope(name_scope):
grad_squared_sums = []
for i, param in enumerate(params):
device = get_param_device(
str(param.blob), param.grad, param_to_device
)
with core.DeviceScope(device):
grad = (
param.grad
if not isinstance(
param.grad,
core.GradientSlice,
) else param.grad.values
)
grad_squared_sum_name = 'grad_{}_squared_sum'.format(i)
grad_squared_sum = model.net.SumSqrElements(
grad,
grad_squared_sum_name,
)
grad_squared_sum_cpu = model.net.EnsureCPUOutput(
grad_squared_sum
)
grad_squared_sums.append(grad_squared_sum_cpu)
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
grad_squared_full_sum = model.net.Sum(
grad_squared_sums,
'grad_squared_full_sum',
)
global_norm = model.net.Pow(
grad_squared_full_sum,
'global_norm',
exponent=0.5,
)
clip_norm = model.param_init_net.ConstantFill(
[],
'clip_norm',
shape=[],
value=float(max_gradient_norm),
)
max_norm = model.net.Max(
[global_norm, clip_norm],
'max_norm',
)
norm_ratio = model.net.Div(
[clip_norm, max_norm],
'norm_ratio',
)
return norm_ratio
def _build(
model,
optimizer,
weights_only=False,
use_param_info_optim=True,
max_gradient_norm=None,
allow_lr_injection=False,
):
param_to_device = _get_param_to_device(model)
# Validate there are no duplicate params
model.Validate()
params = []
for param_info in model.GetOptimizationParamInfo():
if weights_only and param_info.blob not in model.weights:
continue
params.append(param_info)
lr_multiplier = None
if max_gradient_norm is not None:
lr_multiplier = _calc_norm_ratio(
model,
params,
'norm_clipped_grad_update',
param_to_device,
max_gradient_norm,
)
if allow_lr_injection:
if not model.net.BlobIsDefined(_LEARNING_RATE_INJECTION):
lr_injection = model.param_init_net.ConstantFill(
[],
_LEARNING_RATE_INJECTION,
shape=[1],
value=1.0,
)
else:
lr_injection = _LEARNING_RATE_INJECTION
if lr_multiplier is None:
lr_multiplier = lr_injection
else:
lr_multiplier = model.net.Mul(
[lr_multiplier, lr_injection],
'lr_multiplier',
broadcast=1,
)
optimizer.add_lr_multiplier(lr_multiplier)
for param_info in params:
param_name = str(param_info.blob)
device = get_param_device(param_name, param_info.grad, param_to_device)
with core.DeviceScope(device):
if param_info.optimizer and use_param_info_optim:
param_info.optimizer(model.net, model.param_init_net, param_info)
else:
optimizer(model.net, model.param_init_net, param_info)
return optimizer
def add_weight_decay(model, weight_decay):
"""Adds a decay to weights in the model.
This is a form of L2 regularization.
Args:
weight_decay: strength of the regularization
"""
_build(
model,
WeightDecayBuilder(weight_decay=weight_decay),
weights_only=True,
use_param_info_optim=False,
)
def build_sgd(
model,
base_learning_rate,
max_gradient_norm=None,
allow_lr_injection=False,
**kwargs
):
sgd_optimizer = SgdOptimizer(base_learning_rate, **kwargs)
return _build(
model,
sgd_optimizer,
max_gradient_norm=max_gradient_norm,
allow_lr_injection=allow_lr_injection,
)
def build_multi_precision_sgd(
model,
base_learning_rate,
max_gradient_norm=None,
allow_lr_injection=False,
**kwargs
):
multi_prec_sgd_optimizer = MultiPrecisionSgdOptimizer(
base_learning_rate, **kwargs
)
return _build(
model,
multi_prec_sgd_optimizer,
max_gradient_norm=max_gradient_norm,
allow_lr_injection=allow_lr_injection,
)
def build_fp16_sgd(model, base_learning_rate, **kwargs):
fp16_sgd_optimizer = FP16SgdOptimizer(
base_learning_rate, **kwargs
)
return _build(model, fp16_sgd_optimizer)
def build_ftrl(model, engine="SIMD", **kwargs):
if engine == "SIMD":
assert core.IsOperator('Ftrl_ENGINE_SIMD')
assert core.IsOperator('SparseFtrl_ENGINE_SIMD')
ftrl_optimizer = FtrlOptimizer(engine=engine, **kwargs)
return _build(model, ftrl_optimizer)
def build_adagrad(
model,
base_learning_rate,
parameters=None,
max_gradient_norm=None,
allow_lr_injection=False,
**kwargs
):
adagrad_optimizer = AdagradOptimizer(alpha=base_learning_rate, **kwargs)
return _build(
model,
adagrad_optimizer,
max_gradient_norm=max_gradient_norm,
allow_lr_injection=allow_lr_injection,
)
def build_adam(
model,
base_learning_rate,
max_gradient_norm=None,
allow_lr_injection=False,
**kwargs
):
adam_optimizer = AdamOptimizer(alpha=base_learning_rate, **kwargs)
return _build(
model,
adam_optimizer,
max_gradient_norm=max_gradient_norm,
allow_lr_injection=allow_lr_injection,
)
def build_yellowfin(model, base_learning_rate=0.1, **kwargs):
yellowfin_optimizer = YellowFinOptimizer(
alpha=base_learning_rate,
**kwargs)
return _build(model, yellowfin_optimizer)
def build_rms_prop(
model,
base_learning_rate,
max_gradient_norm=None,
allow_lr_injection=False,
**kwargs
):
rms_prop_optimizer = RmsPropOptimizer(alpha=base_learning_rate, **kwargs)
return _build(
model,
rms_prop_optimizer,
max_gradient_norm=max_gradient_norm,
allow_lr_injection=allow_lr_injection,
)
|
# @package optimizer
# Module caffe2.python.optimizer
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
class Regularizer(object):
def __init__(self):
self.apply_after_optimizer = False
'''
Adds regularization to train_net for given parameter. Its factor ahead of
regularization is given when initialization.
The param should be a BlobReference.
'''
def __call__(self, net, param_init_net, param, grad=None):
assert isinstance(param, core.BlobReference)
return self._run(net, param_init_net, param, grad)
def _run(self, net, param_init_net, param, grad):
raise Exception("Not Impelemented")
class L1Norm(Regularizer):
def __init__(self, reg_lambda):
super(L1Norm, self).__init__()
assert reg_lambda >= 0,\
'factor ahead of regularization should be 0 or positive'
self.reg_lambda = reg_lambda
def _run(self, net, param_init_net, param, grad=None):
output_blob = net.NextScopedBlob(param + '_l1_regularization')
net.LpNorm([param], [output_blob], p=1)
net.Scale([output_blob], [output_blob], scale=self.reg_lambda)
return output_blob
class L2Norm(Regularizer):
def __init__(self, reg_lambda):
super(L2Norm, self).__init__()
assert reg_lambda >= 0,\
'factor ahead of regularization should be 0 or positive'
self.reg_lambda = reg_lambda
def _run(self, net, param_init_net, param, grad=None):
output_blob = net.NextScopedBlob(param + '_l2_regularization')
net.LpNorm([param], [output_blob], p=2)
net.Scale([output_blob], [output_blob], scale=self.reg_lambda)
return output_blob
class MaxNorm(Regularizer):
def __init__(self, norm=1.0):
super(MaxNorm, self).__init__()
self.norm = norm
self.apply_after_optimizer = True
def _run(self, net, param_init_net, param, grad):
assert self.norm > 0, 'norm should be bigger than 0.'
if isinstance(grad, core.GradientSlice):
net.SparseNormalize(
[param, grad.indices, grad.values],
[param],
use_max_norm=True,
norm=self.norm,
)
else:
raise NotImplementedError(
"MaxNorm is not supported for dense parameters"
)
class ConstantNorm(Regularizer):
def __init__(self, norm=1.0):
super(ConstantNorm, self).__init__()
self.norm = norm
self.apply_after_optimizer = True
def _run(self, net, param_init_net, param, grad):
assert self.norm > 0, 'norm should be bigger than 0.'
if isinstance(grad, core.GradientSlice):
net.SparseNormalize(
[param, grad.indices, grad.values],
[param],
use_max_norm=False,
norm=self.norm,
)
else:
raise NotImplementedError(
"ConstantNorm is not supported for dense parameters"
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import context, test_util
from threading import Thread
@context.define_context()
class MyContext(object):
pass
class TestContext(test_util.TestCase):
def use_my_context(self):
try:
for _ in range(100):
with MyContext() as a:
for _ in range(100):
self.assertTrue(MyContext.current() == a)
except Exception as e:
self._exceptions.append(e)
def testMultiThreaded(self):
threads = []
self._exceptions = []
for _ in range(8):
thread = Thread(target=self.use_my_context)
thread.start()
threads.append(thread)
for t in threads:
t.join()
for e in self._exceptions:
raise e
@MyContext()
def testDecorator(self):
self.assertIsNotNone(MyContext.current())
|
## @package layer_model_helper
# Module caffe2.python.layer_model_helper
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, model_helper, schema, scope, utils
from caffe2.python.modeling.parameter_info import (
ParameterInfo,
)
from caffe2.python.modeling.parameter_sharing import (
parameter_sharing_context,
)
from caffe2.python.modeling.net_modifier import NetModifier
from caffe2.python.optimizer import get_param_device
from caffe2.python.regularizer import Regularizer
from caffe2.python.layers import layers
from caffe2.proto import caffe2_pb2
from future.utils import viewitems, viewvalues
import logging
import numpy as np
import six
import copy
logger = logging.getLogger(__name__)
class LayerModelHelper(model_helper.ModelHelper):
"""
Model helper for building models on top of layers abstractions.
Each layer is the abstraction that is higher level than Operator. Layer
is responsible for ownership of it's own parameters and can easily be
instantiated in multiple nets possible with different sets of ops.
As an example: one can easily instantiate predict and train nets from
the same set of layers, where predict net will have subset of the
operators from train net.
"""
def __init__(self, name, input_feature_schema, trainer_extra_schema,
keep_blobs=False):
''' TODO(amalevich): more documnetation on input args
'''
super(LayerModelHelper, self).__init__(name=name)
self._layer_names = set()
self._layers = []
self._param_to_shape = {}
# seed default
self._seed = None
self._sequence_seed = True
# optimizer bookkeeping
self.param_to_optim = {}
self.param_to_reg = {}
self._default_optimizer = None
self._loss = None
self._output_schema = None
self._post_grad_net_modifiers = []
self._final_net_modifiers = []
# breakdown map; breakdown features are categorical (like dense) but not
# necessarily used to represent data for training
self._breakdown_map = None
# Connect Schema to self.net. That particular instance of schmea will be
# use for generation of the Layers accross the network and would be used
# for connection with Readers.
self._input_feature_schema = schema.NewRecord(
self.net,
input_feature_schema
) if not keep_blobs else input_feature_schema.clone()
self._trainer_extra_schema = schema.NewRecord(
self.net,
trainer_extra_schema
) if not keep_blobs else trainer_extra_schema.clone()
self._metrics_schema = schema.Struct()
self._preproc_output_schema = None
self._init_global_constants()
self.param_init_net = self.create_init_net('param_init_net')
self._initialize_params = True
def clear_output_schema(self):
self._output_schema = None
def set_initialize_params(self, initialize_params):
self._initialize_params = initialize_params
def add_metric_field(self, name, value):
assert name not in self._metrics_schema.fields, (
"Try to add metric field twice: {}".format(name))
self._metrics_schema = self._metrics_schema + schema.Struct(
(name, value)
)
@staticmethod
def _get_global_constant_initializer_op(
blob_name, array=None, dtype=None, initializer=None
):
# to add a global constant to model, one first need to get the
# initializer
if array is not None:
assert initializer is None,\
"Only one from array and initializer should be specified"
if dtype is None:
array = np.array(array)
else:
array = np.array(array, dtype=dtype)
# TODO: make GivenTensor generic
op_name = None
if array.dtype == np.int32:
op_name = 'GivenTensorIntFill'
elif array.dtype == np.int64:
op_name = 'GivenTensorInt64Fill'
elif array.dtype == np.str:
op_name = 'GivenTensorStringFill'
elif array.dtype == np.bool:
op_name = 'GivenTensorBoolFill'
else:
op_name = 'GivenTensorFill'
def initializer(blob_name):
return core.CreateOperator(
op_name, [],
blob_name,
shape=array.shape,
values=array.flatten().tolist()
)
else:
assert initializer is not None
initializer_op = initializer(blob_name)
return initializer_op
def add_global_constant(
self, name, array=None, dtype=None, initializer=None
):
assert isinstance(name, six.string_types), (
'name should be a string as we are using it as map key')
# This is global namescope for constants. They will be created in all
# init_nets and there should be very few of them.
assert name not in self.global_constants, \
"%s already added in global_constants" % name
blob_name = self.net.NextBlob(name)
self.global_constants[name] = blob_name
initializer_op = LayerModelHelper._get_global_constant_initializer_op(
blob_name, array, dtype, initializer
)
assert blob_name not in self.global_constant_initializers, \
"there is already a initializer op associated with blob %s" % \
blob_name
self.global_constant_initializers[blob_name] = initializer_op
return blob_name
def maybe_add_global_constant(self, name, *args, **kwargs):
# To ad hoc add new global constants without duplication
# if the name was already registered in global_constants, it will not be
# added even if the intended value is different from its original value
if name in self.global_constants:
blob_name = self.global_constants[name]
initializer_op = \
LayerModelHelper._get_global_constant_initializer_op(
blob_name, *args, **kwargs
)
# check if the original initializer is the same as the one intended
# now
assert utils.OpAlmostEqual(
initializer_op,
self.global_constant_initializers[blob_name],
'debug_info'
), \
"conflict initializers for global constant %s, " \
"previous %s, now %s" % (
blob_name, str(initializer_op),
str(self.global_constant_initializers[blob_name]))
return blob_name
return self.add_global_constant(name, *args, **kwargs)
def _init_global_constants(self):
self.global_constants = {}
self.global_constant_initializers = {}
self.add_global_constant('ONE', 1.0)
self.add_global_constant('ZERO', 0.0)
self.add_global_constant('ZERO_RANGE', [0, 0], dtype='int32')
def _add_global_constants(self, init_net):
for initializer_op in viewvalues(self.global_constant_initializers):
init_net._net.op.extend([initializer_op])
def create_init_net(self, name):
init_net = core.Net(name)
self._add_global_constants(init_net)
return init_net
def _validate_param_shape(self, param_name, shape):
if param_name not in self._param_to_shape:
return
ref_shape = self._param_to_shape[param_name]
if shape != ref_shape:
raise ValueError(
"Got inconsistent shapes between shared parameters "
"when trying to map a blob in scope {0} to {1}. ref_shape : "
" {2}, shape : {3}".format(
scope.CurrentNameScope(), param_name, ref_shape, shape)
)
def create_param(self, param_name, shape, initializer, optimizer=None,
ps_param=None, regularizer=None):
if isinstance(param_name, core.BlobReference):
param_name = str(param_name)
elif isinstance(param_name, six.string_types):
# Parameter name will be equal to current Namescope that got
# resolved with the respect of parameter sharing of the scopes.
param_name = parameter_sharing_context.get_parameter_name(
param_name)
else:
raise "Unsupported type for param_name"
param_blob = core.BlobReference(param_name)
if len(initializer) == 1:
init_op_args = {}
else:
assert len(initializer) == 2
init_op_args = copy.deepcopy(initializer[1])
if shape is not None:
assert 'shape' not in init_op_args
init_op_args.update({'shape': shape})
initializer_op = None
if self._initialize_params:
initializer_op = core.CreateOperator(
initializer[0],
[],
param_blob,
**init_op_args
)
param = layers.LayerParameter(
parameter=param_blob,
initializer=initializer_op,
optimizer=optimizer,
ps_param=ps_param,
regularizer=regularizer
)
self._validate_param_shape(param_name, shape)
self._param_to_shape[param_name] = shape
return param
def next_layer_name(self, prefix):
base_name = core.ScopedName(prefix)
name = base_name
index = 0
while name in self._layer_names:
name = base_name + '_auto_' + str(index)
index += 1
self._layer_names.add(name)
return name
def add_layer(self, layer):
self._layers.append(layer)
for param in layer.get_parameters():
assert isinstance(param.parameter, core.BlobReference)
self.param_to_optim[str(param.parameter)] = \
param.optimizer or self.default_optimizer
self.params.append(param.parameter)
if isinstance(param, layers.LayerParameter):
self.param_to_reg[param.parameter] = param.regularizer
elif isinstance(param, ParameterInfo):
# TODO:
# Currently, LSTM and RNNcells, which use ModelHelper instead of
# LayerModelHelper as super class, are called in pooling_methods
# In ModelHelper, regularization is not supported in create_param
# We will unify the way of create_param of ModelHelper and
# LayerModelHelper in the future.
logger.info('regularization is unsupported for ParameterInfo object')
else:
raise ValueError(
'unknown object type besides ParameterInfo and LayerParameter: {}'
.format(param)
)
# The primary value of adding everything to self.net - generation of the
# operators right away, i.e. if error happens it'll be detected
# immediately. Other than this - create_x_net should be called.
layer.add_operators(self.net, self.param_init_net)
return layer.output_schema
def get_parameter_blobs(self):
param_blobs = []
for layer in self._layers:
for param in layer.get_parameters():
param_blobs.append(param.parameter)
return param_blobs
def add_post_grad_net_modifiers(self, modifier):
assert modifier not in self._post_grad_net_modifiers,\
"{0} is already in {1}".format(modifier, self._post_grad_net_modifiers)
assert isinstance(modifier, NetModifier),\
"{} has to be a NetModifier instance".format(modifier)
self._post_grad_net_modifiers.append(modifier)
def add_final_net_modifiers(self, modifier):
assert modifier not in self._final_net_modifiers,\
"{0} is already in {1}".format(modifier, self._final_net_modifiers)
assert isinstance(modifier, NetModifier),\
"{} has to be a NetModifier instance".format(modifier)
self._final_net_modifiers.append(modifier)
@property
def seed(self):
return self._seed
@property
def sequence_seed(self):
return self._sequence_seed
def store_seed(self, seed, sequence_seed=True):
# Store seed config that will be applied to each op in the net.
self._seed = seed
# If sequence_seed is True, the i-th op has rand_seed=`seed + i`
self._sequence_seed = sequence_seed
def apply_seed(self, net):
if self._seed:
net.set_rand_seed(self._seed, self._sequence_seed)
@property
def default_optimizer(self):
return self._default_optimizer
@default_optimizer.setter
def default_optimizer(self, optimizer):
self._default_optimizer = optimizer
@property
def input_feature_schema(self):
return self._input_feature_schema
@property
def trainer_extra_schema(self):
return self._trainer_extra_schema
@property
def metrics_schema(self):
"""
Returns the schema that represents model output that should be used for
metric reporting.
During the training/evaluation this schema will be appended to the
schema that represents model output.
"""
return self._metrics_schema
@property
def output_schema(self):
assert self._output_schema is not None
return self._output_schema
@output_schema.setter
def output_schema(self, schema):
assert self._output_schema is None
self._output_schema = schema
@property
def preproc_output_schema(self):
assert self._preproc_output_schema is not None
return self._preproc_output_schema
@preproc_output_schema.setter
def preproc_output_schema(self, schema):
assert self._preproc_output_schema is None
self._preproc_output_schema = schema
@property
def loss(self):
assert self._loss is not None
return self._loss
@loss.setter
def loss(self, loss):
assert self._loss is None
self._loss = loss
def has_loss(self):
return self._loss is not None
def add_loss(self, loss, name='unnamed'):
assert loss is not None, "Added loss should not be None"
assert isinstance(loss, schema.Scalar) or isinstance(
loss, schema.Struct
), "Added loss should be a scalar or a struct"
if self._loss is None:
self._loss = schema.Struct((name, loss))
else:
prefix_base = name + '_auto_'
index = 0
prefix = name
while prefix in self._loss:
prefix = prefix_base + str(index)
index += 1
loss_struct = schema.Struct((prefix, loss))
self._loss = self._loss + loss_struct
def add_output_schema(self, name, value):
assert value is not None, \
'Added output schema {} should not be None'.format(name)
assert isinstance(value, schema.Scalar) or \
isinstance(value, schema.Struct), \
'Added output schema {} should be a scalar or a struct.\n\
Now it is {}.'.format(name, type(value))
if self._output_schema is None: # be the first field
self._output_schema = schema.Struct((name, value))
else: # merge with other fields
assert name not in self._output_schema.fields, \
'Output Schema Field {} already exists'.format(name)
self._output_schema = \
self._output_schema + schema.Struct((name, value))
def add_trainer_extra_schema(self, trainer_extra_schema):
trainer_extra_record = schema.NewRecord(self.net, trainer_extra_schema)
self._trainer_extra_schema += trainer_extra_record
def __getattr__(self, layer):
def is_functional_layer(layer):
if core.IsOperator(layer):
return True
elif layer.startswith('FunctionalLayer'):
return True
else:
return False
def resolve_functional_layer(layer):
if core.IsOperator(layer):
return layer
elif layer.startswith('FunctionalLayer'):
return layer[len('FunctionalLayer'):]
else:
raise ValueError(
'%s cannot be resolved as functional layer' % layer
)
if layer.startswith('__'):
raise AttributeError(layer)
# TODO(amalevich): Add add support for ifbpy inline documentation
if layers.layer_exists(layer):
def wrapper(*args, **kwargs):
new_layer = layers.create_layer(layer, self, *args, **kwargs)
if kwargs.get("output_to_metrics", False):
new_layer.export_output_for_metrics()
if kwargs.get("params_to_metrics", False):
new_layer.export_params_for_metrics()
return self.add_layer(new_layer)
return wrapper
elif is_functional_layer(layer):
# TODO(xlwang): Desginated layer shadows the usage of an op as a
# single layer. To enforce using an op (e.g. Split) as functional
# layer, one can call 'model.FunctionalLayerSplit'
layer = resolve_functional_layer(layer)
def wrapper(*args, **kwargs):
def apply_operator(net, in_record, out_record, **kwargs):
# TODO(amalevich): Switch to net.operator as soon as it gets
# landed
net.__getattr__(layer)(in_record.field_blobs(),
out_record.field_blobs(),
**kwargs)
if 'name' not in kwargs:
kwargs['name'] = layer
new_layer = layers.create_layer(
'Functional',
self, *args, function=apply_operator,
**kwargs
)
if kwargs.get("output_to_metrics", False):
new_layer.export_output_for_metrics()
if kwargs.get("params_to_metrics", False):
new_layer.export_params_for_metrics()
return self.add_layer(new_layer)
return wrapper
else:
raise ValueError(
"Trying to create non-registered layer: {}".format(layer))
@property
def layers(self):
return self._layers
def apply_regularizers_on_loss(
self,
train_net,
train_init_net,
blob_to_device=None,
):
for param, regularizer in viewitems(self.param_to_reg):
if regularizer is None or regularizer.apply_after_optimizer:
continue
assert isinstance(regularizer, Regularizer)
added_loss_blob = regularizer(train_net, train_init_net, param)
self.add_loss(
schema.Scalar(blob=added_loss_blob),
str(added_loss_blob)
)
def apply_regularizers_after_optimizer(
self,
train_net,
train_init_net,
grad_map,
blob_to_device=None,
):
for param, regularizer in viewitems(self.param_to_reg):
if regularizer is None or not regularizer.apply_after_optimizer:
continue
assert isinstance(regularizer, Regularizer)
regularizer(
train_net, train_init_net, param, grad_map.get(str(param)))
def apply_post_grad_net_modifiers(
self,
trainer_net,
trainer_init_net,
grad_map,
blob_to_device=None,
):
param_grad_map = {param: grad_map[param]
for param in self.param_to_optim.keys() if param in grad_map}
for modifier in self._post_grad_net_modifiers:
modifier(trainer_net, trainer_init_net, param_grad_map,
blob_to_device=blob_to_device)
def apply_final_net_modifiers(
self,
trainer_net,
trainer_init_net,
grad_map,
blob_to_device=None,
):
for modifier in self._final_net_modifiers:
modifier(trainer_net, trainer_init_net, grad_map,
blob_to_device=blob_to_device)
def apply_optimizers(
self,
train_net,
train_init_net,
grad_map,
blob_to_device=None,
):
CPU = core.DeviceOption(caffe2_pb2.CPU)
# if given, blob_to_device is a map from blob to device_option
blob_to_device = blob_to_device or {}
for param, optimizer in viewitems(self.param_to_optim):
assert optimizer is not None, \
"default optimizer must have been set in add_layer"
# note that not all params has gradient and thus we sent None if
# gradient does not exists
device = get_param_device(
param,
grad_map.get(str(param)),
param_to_device=blob_to_device,
default_device=CPU,
)
with core.DeviceScope(device):
optimizer(
train_net, train_init_net, param, grad_map.get(str(param)))
def _GetOne(self):
return self.global_constants['ONE']
# An optimizer which allows us to do NO optimization
def NoOptim(self, *args, **kwargs):
pass
@property
def breakdown_map(self):
return self._breakdown_map
@breakdown_map.setter
def breakdown_map(self, breakdown_map):
# TODO(xlwang): provide more rich feature information in breakdown_map;
# and change the assertion accordingly
assert isinstance(breakdown_map, dict)
assert all(isinstance(k, six.string_types) for k in breakdown_map)
assert sorted(list(breakdown_map.values())) == range(len(breakdown_map))
self._breakdown_map = breakdown_map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.