MCPcopy Index your code
hub / github.com/pytorch/tutorials / _run_trainer

Function _run_trainer

advanced_source/rpc_ddp_tutorial/main.py:39–109  ·  view source on GitHub ↗

r""" Each trainer runs a forward pass which involves an embedding lookup on the parameter server and running nn.Linear locally. During the backward pass, DDP is responsible for aggregating the gradients for the dense part (nn.Linear) and distributed autograd ensures gradients updates

(remote_emb_module, rank)

Source from the content-addressed store, hash-verified

37
38# BEGIN setup_trainer
39def _run_trainer(remote_emb_module, rank):
40 r"""
41 Each trainer runs a forward pass which involves an embedding lookup on the
42 parameter server and running nn.Linear locally. During the backward pass,
43 DDP is responsible for aggregating the gradients for the dense part
44 (nn.Linear) and distributed autograd ensures gradients updates are
45 propagated to the parameter server.
46 """
47
48 # Setup the model.
49 model = HybridModel(remote_emb_module, rank)
50
51 # Retrieve all model parameters as rrefs for DistributedOptimizer.
52
53 # Retrieve parameters for embedding table.
54 model_parameter_rrefs = model.remote_emb_module.remote_parameters()
55
56 # model.fc.parameters() only includes local parameters.
57 # NOTE: Cannot call model.parameters() here,
58 # because this will call remote_emb_module.parameters(),
59 # which supports remote_parameters() but not parameters().
60 for param in model.fc.parameters():
61 model_parameter_rrefs.append(RRef(param))
62
63 # Setup distributed optimizer
64 opt = DistributedOptimizer(
65 optim.SGD,
66 model_parameter_rrefs,
67 lr=0.05,
68 )
69
70 criterion = torch.nn.CrossEntropyLoss()
71 # END setup_trainer
72
73 # BEGIN run_trainer
74 def get_next_batch(rank):
75 for _ in range(10):
76 num_indices = random.randint(20, 50)
77 indices = torch.LongTensor(num_indices).random_(0, NUM_EMBEDDINGS)
78
79 # Generate offsets.
80 offsets = []
81 start = 0
82 batch_size = 0
83 while start < num_indices:
84 offsets.append(start)
85 start += random.randint(1, 10)
86 batch_size += 1
87
88 offsets_tensor = torch.LongTensor(offsets)
89 target = torch.LongTensor(batch_size).random_(8).cuda(rank)
90 yield indices, offsets_tensor, target
91
92 # Train for 100 epochs
93 for epoch in range(100):
94 # create distributed autograd context
95 for indices, offsets, target in get_next_batch(rank):
96 with dist_autograd.context() as context_id:

Callers

nothing calls this directly

Calls 5

HybridModelClass · 0.85
get_next_batchFunction · 0.85
stepMethod · 0.80
modelFunction · 0.50
backwardMethod · 0.45

Tested by

no test coverage detected