MCPcopy Create free account
hub / github.com/pytorch/tutorials / gen_batch

Function gen_batch

intermediate_source/transformer_building_blocks.py:313–350  ·  view source on GitHub ↗
(N, E_q, E_k, E_v, device, dtype=torch.float32, query_seq_len_1=False)

Source from the content-addressed store, hash-verified

311# Generate a batch of semi-realistic data using Zipf distribution for sentence lengths
312# in the form of nested tensors with the jagged layout.
313def gen_batch(N, E_q, E_k, E_v, device, dtype=torch.float32, query_seq_len_1=False):
314 # generate semi-realistic data using Zipf distribution for sentence lengths
315 sentence_lengths = zipf_sentence_lengths(alpha=1.2, batch_size=N)
316
317 # Note: the torch.jagged layout is a nested tensor layout that supports a single ragged
318 # dimension and works with torch.compile. The batch items each have shape (B, S*, D)
319 # where B = batch size, S* = ragged sequence length, and D = embedding dimension.
320 if query_seq_len_1:
321 query = torch.nested.nested_tensor(
322 [torch.randn(1, E_q, dtype=dtype, device=device) for l in sentence_lengths],
323 layout=torch.jagged,
324 )
325 else:
326 query = torch.nested.nested_tensor(
327 [
328 torch.randn(l.item(), E_q, dtype=dtype, device=device)
329 for l in sentence_lengths
330 ],
331 layout=torch.jagged,
332 )
333
334 key = torch.nested.nested_tensor(
335 [
336 torch.randn(s.item(), E_k, dtype=dtype, device=device)
337 for s in sentence_lengths
338 ],
339 layout=torch.jagged,
340 )
341
342 value = torch.nested.nested_tensor(
343 [
344 torch.randn(s.item(), E_v, dtype=dtype, device=device)
345 for s in sentence_lengths
346 ],
347 layout=torch.jagged,
348 )
349
350 return query, key, value, sentence_lengths
351
352
353import math

Callers 1

Calls 1

zipf_sentence_lengthsFunction · 0.70

Tested by

no test coverage detected