Tracking access patterns during training

username: jmalinza
cooked: <p>Hello everyone, this is my first post on the Pytorch forums - I hope you are keeping well!<br>
I understand that what I am going to ask is detailed and/or advanced. But please bare with me - I am willing to go all the way <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>
<p><strong>I want to track <em>what</em> (layer module) accessed my tensor and <em>when</em> my tensor was accessed.</strong></p>
<p>For example - when training:</p>
<ol>
<li>A tensor is used in the forward computation of a layer.<br>
1a) The output produced by that layer is then saved for autograd on the later backwards pass.</li>
<li>Then during the backpass of the autograd, that same tensor is used to calculate gradients for the layer that produced it.</li>
</ol>
<p>By recording when steps 1) and 2) are started, a tensor access pattern can be observed. The goal of this is to identify the time difference between the 1st and 2nd accesses. (I am a grad student - please feel free to ask more about my work)</p>
<p>Please understand that I have spent some time learning the Pytorch internals (i recommend <a href="http://blog.ezyang.com/2019/05/pytorch-internals/" rel="nofollow noopener">here</a> or <a href="https://blog.christianperone.com/2018/03/pytorch-internal-architecture-tour/" rel="nofollow noopener">here</a>) and have thought of some methods of implementation.</p>
<p>I am posting here just to hear from some other voices who are more knowledgable and experienced in Pytorch.</p>
<p>Thank you for your time.</p>

username: albanD
cooked: <p>Hi,</p>
<blockquote>
<p>1a) The output produced by that layer is then saved for autograd on the later backwards pass.</p>
</blockquote>
<p>This is not strictly true I think. In particular it depends what you call a “layer”.<br>
But the layers in torch.nn and neural nets are completely independent of the autograd. So this statement would be wrong in that case.<br>
The autograd works at a lower level where we have a set of specific “elementary ops” for which we do (only when needed, not all the time!) save input and/or outputs.</p>
<p>Are you interested in the first or second in your case?</p>
<p>I can’t really think of an easy way to hack this in though. Maybe you can use <a href="https://github.com/pytorch/pytorch/blob/e57a08119bc01b7d06ee6ba8042cc0885ebb6276/torch/csrc/autograd/saved_variable.h#L19">this</a> construct that is used to store Tensors to be used in the backward. This is created at the same time (sometimes before, sometimes after) as the forward function and the unpack is called during the backward pass when the Tensor is needed.</p>
<p>Hope this helps!</p>

username: jmalinza
cooked: <p>Hello, thank you for your reply.</p>
<p>I have wrongly used “autograd” to refer to the general backwards propogation pass (error and gradient). The autograd is something rather mysterious to me; something that will require much more attention.</p>
<blockquote>
<p>Are you interested in the first or second in your case?</p>
</blockquote>
<p>I am interested in the second case.</p>
<p>When refering to GPU memory usage, we generally have the problem where memory is full of “intermediate” tensors and a OOM event occurs. This is closely linked to which tensors are generated by forward propogation, stored in memory and then reused for error and gradient calculation.</p>
<p>That construct looks somewhat promising - I will take a look over the next week.<br>
I was also thinking about potentially using a tensor’s <a href="https://github.com/pytorch/pytorch/blob/e57a08119bc01b7d06ee6ba8042cc0885ebb6276/c10/core/TensorImpl.h#L218" rel="noopener nofollow ugc">version counter</a>. Each access could trigger a function call here that may be able to record some metadata for my use.</p>

username: albanD
cooked: <p>The version counter is only ever bumped when inplace operations happen. So that might not cover all the cases you want.</p>
<p>If you have an example or idea of what exactly you want to get for a given sample code, that might help us guide you more <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

username: jmalinza
cooked: <p>Ok, it is rather late here now, so I will reply tomorrow with a code snippet.</p>

username: jmalinza
cooked: <p>Ok, I put together a quick toy network.<br>
Its a simple model, with the forward function fully expanded for the discussion.</p>
<pre><code class="lang-auto">#include &lt;torch/torch.h&gt;

struct ToyImpl : torch::nn::Module {
	ToyImpl(int64_t input_size, int64_t output_size) : 
		linear1(register_module("linear1", torch::nn::Linear(input_size,64))),
		linear2(register_module("linear2", torch::nn::Linear(64, output_size))) {}

	torch::Tensor forward(torch::Tensor input){
		torch::Tensor p = linear1(input);
		torch::Tensor q = torch::relu(p);
		torch::Tensor r = linear2(q);
		return r;
	}
	torch::nn::Linear linear1, linear2;
};

TORCH_MODULE(Toy);

const int64_t input_size  = 16;
const int64_t output_size = 2;
const int64_t N  = 256; // batch size

int main()
{
	Toy toyNet(input_size,output_size);
	toyNet-&gt;to(torch::kCUDA);
	// input tensor &amp; desired output
	torch::Tensor input        = torch::rand({N, input_size }).to(torch::kCUDA);
	torch::Tensor output_truth = torch::rand({N, output_size}).to(torch::kCUDA);

	float learning_rate = 1e-4;
 	 torch::optim::SGD optimizer(
      toyNet-&gt;parameters(), torch::optim::SGDOptions(learning_rate));

 	// a single epoch
	optimizer.zero_grad();
	auto output_pred = toyNet-&gt;forward(input);
	auto loss = torch::mse_loss(output_pred, output_truth.detach());
	loss.backward();
	optimizer.step();

	return 0;
}
</code></pre>
<p>So, during <code>toyNet-&gt;forward(input)</code> I want to track when tensors <em>p, q, r</em> are accessed and when their computation is finished. It would also be useful to know which of them are saved for backwards.</p>
<p>Then, during <code>loss.backwards()</code> I want to again track when the saved tensors (amoungst <em>p, q ,r</em>) are accessed and when their computation is complete.</p>

username: albanD
cooked: <p>Things like linear and relu are at the level of nn. The linear function in particular is composed of subfunctions that may save their input/output as well. Do you explicitly want to only track p q r?</p>
<p>Otherwise, the SavedVariable seem to be the right place to hook in. But it is going to be a big hack and quite fragile <img src="https://discuss.pytorch.org/images/emoji/apple/confused.png?v=9" title=":confused:" class="emoji" alt=":confused:"></p>

username: jmalinza
cooked: <p>Ideally, it would be for all tensors, implicitly and explicitly created by the user. That means p, q, r and all the other tensors produced by subfuctions.</p>
<p>Originally, I thought I would be able to augment the TensorImpl structure, so that each unique tensor could track its own access pattern (access count and timestep). But I couldn’t imagine a way where a <code>TensorImpl::function</code> could be run when a tensor is accessed. I also wondered if tensor accessors could possibly provide similar functionality…</p>
<p>One more question: what is Pytorch’s unit for enqueuing computations to the CUDA stream?</p>

username: albanD
cooked: <blockquote>
<p>One more question: what is Pytorch’s unit for enqueuing computations to the CUDA stream?</p>
</blockquote>
<p>Not sure what you mean by unit. But usually each op corresponds to a single kernel. With few complex ones launching few kernels.<br>
It will depend on the op I’m afraid.</p>
<blockquote>
<p>But I couldn’t imagine a way where a <code>TensorImpl::function</code> could be run when a tensor is accessed.</p>
</blockquote>
<p>There is no check for “accessing” a Tensor.<br>
That is why I recommended to attach to the autograd construct that save/unpack the Tensors for the backward pass.</p>