Skip to content

Commit 4c44ca0

Browse files
Huanyu Hefacebook-github-bot
authored andcommitted
implementation of fbgemm op - permute_multi_embedding (pytorch#2120)
Summary: X-link: pytorch/FBGEMM#2738 Pull Request resolved: pytorch#2120 # context * current we have a working function `permute_pooled_embs_auto_grad` to do a full permute of KTs, including forward and backward * it has several limitations: a) it has to be a full permute, duplicates are not supported; b) in the main [use case](https://fburl.com/code/89od0rqm) there has to be a torch.concat on the input KTs, which is not very efficient; c) the function output a single KT which requires a split operation * there is some attempt to support duplicated outputs, but the backward doesn't work * this diff is trying to create a new kernel (named `permute_multi_embedding`) to support a multiple-KT to multiple-KT mapping operation with backward support # notes * this diff focuses on the implemenation and test of the operator * performance analysis and benchmark are in the next diff # operator example usage * used in python ``` # test inputs: 3 KTs with batch_size=2048 batch_size = 2048 keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]] lengths = [[96, 256], [512, 128, 768], [1024]] values = [ torch.randn(batch_size, sum(lens), device="cuda", requires_grad=True) for lens in lengths ] # target outputs: 4 KTs with re-arranged keys (features), duplicates are allowed groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]] # accessorial arguments to the op/kernel permutes, in_lengths, out_lengths = _multi_remap_to_groups( keys, lengths, groups ) # arguments outputs = torch.ops.fbgemm.permute_multi_embedding( values, permutes, in_lengths, out_lengths ) ``` * permutes ``` # [input_tensor_idx, output_tensor_idx, input_key_idx, output_key_idx, key_length, magic_jump] permutes = tensor( [ [0, 0, 0, 0, 3, 4], # f1 [1, 0, 0, 3, 5, 0], # f3 [0, 1, 3, 0, 4, 0], # f2 [1, 2, 5, 0, 6, 0], # f4 [0, 2, 0, 6, 3, -6], # f1 [2, 2, 0, 9, 8, 0], # f6 [0, 3, 0, 0, 3, -8], # f1 [1, 3, 11, 3, 7, 0], # f5 ] ) ``` # details 1. from the above example usage, we can clearly see that the operatior takes in the following: a) values: List[torch.Tensor], which represents the input KTs b) permutes: torch.Tensor, which contains the permute information, will be explained later c) output_lengths_list: List[int], the lengths of the output tensors (KTs), which is needed to allocate memory on device ahead d) in_lengths: torch.Tensor, lengths of input tensors, which is on device e) out_lengths: torch.Tensor, lengths of output tensors, which is on device 2. the operator returns a list of tensors, which represents the permuted KTs 3. `permute` is the most critical argument in this operator: a) 2-D tensor b) each row represents a key (feature) permute move c) a permute move = [input_tensor_id, output_tensor_id, input_start_idx, output_start_idx, feature_length, jump] d) jump is used in backward when a key (feature) from the input tensor is mapped to multiple places in the output tensors Differential Revision: D57055616
1 parent 001396b commit 4c44ca0

File tree

2 files changed

+295
-2
lines changed

2 files changed

+295
-2
lines changed

torchrec/sparse/jagged_tensor.py

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@
3636
torch.ops.load_library(
3737
"//deeplearning/fbgemm/fbgemm_gpu:permute_pooled_embedding_ops_cpu"
3838
)
39+
torch.ops.load_library(
40+
"//deeplearning/fbgemm/fbgemm_gpu:permute_multi_embedding_ops_cpu"
41+
)
42+
torch.ops.load_library(
43+
"//deeplearning/fbgemm/fbgemm_gpu:permute_multi_embedding_ops_gpu"
44+
)
3945
except OSError:
4046
pass
4147

@@ -164,6 +170,24 @@ def _all_keys_used_once(
164170
return len(key_set) == len(group_set) == len(flat_keys) == len(flat_groups)
165171

166172

173+
@torch.fx.wrap
174+
def permute_multi_embedding(
175+
keyed_tensors: List["KeyedTensor"], groups: List[List["str"]]
176+
) -> List[torch.Tensor]:
177+
keys, lengths, values = _desugar_keyed_tensors(keyed_tensors)
178+
permutes, in_shape, out_shape, out_lengths = _kt_regroup_permutes(
179+
values[0], keys, lengths, groups
180+
)
181+
permuted_values = torch.ops.fbgemm.permute_multi_embedding(
182+
values,
183+
permutes,
184+
in_shape,
185+
out_shape,
186+
out_lengths,
187+
)
188+
return permuted_values
189+
190+
167191
@torch.fx.wrap
168192
def _fbgemm_permute_pooled_embs(
169193
keyed_tensors: List["KeyedTensor"], groups: List[List["str"]]
@@ -240,6 +264,90 @@ def _remap_to_groups(
240264
return permute, inv_permute, offsets, inv_offsets, splits
241265

242266

267+
def _kt_regroup_permutes(
268+
value: torch.Tensor,
269+
keys: List[List[str]],
270+
key_lengths: List[List[int]],
271+
groups: List[List[str]],
272+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, List[int]]:
273+
"""
274+
returns: permutes, in_shapes, out_shapes, out_lengths
275+
"""
276+
# key => (tensor_idx, key_index)
277+
key_map: Dict[str, Tuple[int, int]] = {
278+
key: (tensor_idx, key_idx)
279+
for tensor_idx, tensor in enumerate(keys)
280+
for key_idx, key in enumerate(tensor)
281+
}
282+
283+
# [offsets per tensor]
284+
in_offsets: List[List[int]] = [[] for _ in key_lengths]
285+
for i, tensor in enumerate(key_lengths):
286+
in_offsets[i] = _cumsum(tensor)
287+
in_lengths: List[int] = [sum(lengths) for lengths in key_lengths]
288+
289+
# set total_permutes as the jump stop sign
290+
total_permutes: int = sum(len(tensor) for tensor in groups)
291+
out_lengths: List[int] = [0] * len(groups)
292+
293+
# [input_tensor_idx, output_tensor_idx, input_start, output_start, length, jump]
294+
permute_param = 6
295+
permutes: List[List[int]] = [[0] * permute_param for _ in range(total_permutes)]
296+
297+
# record the last seen index, so that can make the jump from last_seen to current
298+
last_seen: Dict[str, int] = {}
299+
permute_idx = 0
300+
for output_tensor_idx, output_tenser in enumerate(groups):
301+
output_start = 0
302+
for output_key in output_tenser:
303+
input_tensor_idx, input_key_idx = key_map[output_key]
304+
input_start = in_offsets[input_tensor_idx][input_key_idx]
305+
length = key_lengths[input_tensor_idx][input_key_idx]
306+
307+
# add jump data
308+
if output_key not in last_seen:
309+
jump = 0 # don't need to jump yet
310+
# positive as a potential jump start
311+
last_seen[output_key] = permute_idx
312+
else:
313+
prev = last_seen[output_key]
314+
if prev >= 0: # positive ==> it's a jump start
315+
# jump to current idx, positive as the jump start
316+
permutes[prev][5] = permute_idx
317+
else: # it's already in a jump sequence, mark as negative
318+
permutes[-prev][5] = -permute_idx
319+
# mark last_seen negative since it's already in jump
320+
last_seen[output_key] = -permute_idx
321+
# it's a potential jump stop
322+
jump = -total_permutes
323+
324+
permutes[permute_idx][:] = [
325+
input_tensor_idx,
326+
output_tensor_idx,
327+
input_start,
328+
output_start,
329+
length,
330+
jump,
331+
]
332+
permute_idx += 1
333+
output_start += length
334+
out_lengths[output_tensor_idx] = output_start
335+
336+
permute_tensor = torch.tensor(permutes, dtype=torch.int32)
337+
in_shapes = torch.tensor(in_lengths, dtype=torch.int32)
338+
out_shapes = torch.tensor(out_lengths, dtype=torch.int32)
339+
device = value.device
340+
permute_tensor = _pin_and_move(permute_tensor, device)
341+
in_shapes = _pin_and_move(in_shapes, device)
342+
out_shapes = _pin_and_move(out_shapes, device)
343+
return (
344+
permute_tensor,
345+
in_shapes,
346+
out_shapes,
347+
out_lengths,
348+
)
349+
350+
243351
def _values_string(values: torch.Tensor, start: int, end: int) -> str:
244352
size = values.size()
245353
if len(size) == 1:

torchrec/sparse/tests/test_jagged_tensor.py

Lines changed: 187 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from torch.testing import FileCheck
1717
from torchrec.fx import symbolic_trace
1818
from torchrec.sparse.jagged_tensor import (
19+
_kt_regroup_permutes,
1920
_regroup_keyed_tensors,
2021
ComputeJTDictToKJT,
2122
ComputeKJTToJTDict,
@@ -1374,6 +1375,192 @@ def test_permute_vb(self) -> None:
13741375
)
13751376
self.assertEqual(permuted_jag_tensor.weights_or_none(), None)
13761377

1378+
def test_kt_regroup_permutes(self) -> None:
1379+
keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]]
1380+
lengths = [[3, 4], [5, 6, 7], [8]]
1381+
groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]]
1382+
for device in ["cpu", "meta", "cuda"]:
1383+
if device == "cuda" and not torch.cuda.is_available():
1384+
continue
1385+
device = torch.device(device)
1386+
permutes, in_shapes, out_shapes, out_lengths = _kt_regroup_permutes(
1387+
torch.empty(0, device=device), keys, lengths, groups
1388+
)
1389+
ref_permutes = [
1390+
[0, 0, 0, 0, 3, 4], # f1, jump to 4, as a start
1391+
[1, 0, 0, 3, 5, 0], # f3
1392+
[0, 1, 3, 0, 4, 0], # f2
1393+
[1, 2, 5, 0, 6, 0], # f4
1394+
[0, 2, 0, 6, 3, -6], # f1 jump to 6, as in a jump sequence
1395+
[2, 2, 0, 9, 8, 0], # f6
1396+
[0, 3, 0, 0, 3, -8], # f1 jump stop, as out of boundary
1397+
[1, 3, 11, 3, 7, 0], # f5
1398+
]
1399+
if device.type == "meta":
1400+
self.assertEqual(
1401+
permutes.shape, (len(ref_permutes), len(ref_permutes[0]))
1402+
)
1403+
self.assertEqual(in_shapes.shape, (3,))
1404+
self.assertEqual(out_shapes.shape, (4,))
1405+
else:
1406+
self.assertTrue(
1407+
torch.equal(
1408+
permutes,
1409+
torch.tensor(ref_permutes, dtype=torch.int32, device=device),
1410+
)
1411+
)
1412+
self.assertEqual(in_shapes.tolist(), [7, 18, 8])
1413+
self.assertEqual(out_shapes.tolist(), [8, 4, 17, 10])
1414+
self.assertEqual(out_lengths, [8, 4, 17, 10])
1415+
1416+
def test_multi_permute_forward_cpu(self) -> None:
1417+
batch_size = 32
1418+
keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]]
1419+
lengths = [[3, 4], [5, 6, 7], [8]]
1420+
groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]]
1421+
values = [
1422+
torch.randn(batch_size, sum(lens), device="cpu", requires_grad=True)
1423+
for lens in lengths
1424+
]
1425+
permutes, in_shapes, out_shapes, out_lengths = _kt_regroup_permutes(
1426+
values[0], keys, lengths, groups
1427+
)
1428+
refs = [[] for _ in groups]
1429+
for i in range(permutes.size(0)):
1430+
in_idx, out_idx, in_start, _, length, _ = permutes[i].tolist()
1431+
refs[out_idx].append(values[in_idx][:, in_start : (in_start + length)])
1432+
refs = [torch.cat(ref, dim=1) for ref in refs]
1433+
outputs = torch.ops.fbgemm.permute_multi_embedding(
1434+
values, permutes, in_shapes, out_shapes, out_lengths
1435+
)
1436+
for out, ref in zip(outputs, refs):
1437+
self.assertTrue(torch.allclose(out, ref))
1438+
1439+
def test_multi_permute_forward_meta(self) -> None:
1440+
batch_size = 32
1441+
keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]]
1442+
lengths = [[3, 4], [5, 6, 7], [8]]
1443+
groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]]
1444+
values = [
1445+
torch.randn(batch_size, sum(lens), device="meta", requires_grad=True)
1446+
for lens in lengths
1447+
]
1448+
permutes, in_shapes, out_shapes, out_lengths = _kt_regroup_permutes(
1449+
values[0], keys, lengths, groups
1450+
)
1451+
outputs = torch.ops.fbgemm.permute_multi_embedding(
1452+
values, permutes, in_shapes, out_shapes, out_lengths
1453+
)
1454+
for out, ref in zip(outputs, out_lengths):
1455+
self.assertEqual(out.shape, (batch_size, ref))
1456+
1457+
# pyre-ignore[56]
1458+
@unittest.skipIf(
1459+
torch.cuda.device_count() <= 0,
1460+
"CUDA is not available",
1461+
)
1462+
def test_multi_permute_forward_gpu(self) -> None:
1463+
batch_size = 1024
1464+
keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]]
1465+
lengths = [[96, 256], [512, 128, 768], [1024]]
1466+
groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]]
1467+
values = [
1468+
torch.randn(batch_size, sum(lens), device="cuda", requires_grad=True)
1469+
for lens in lengths
1470+
]
1471+
permutes, in_shapes, out_shapes, out_lengths = _kt_regroup_permutes(
1472+
values[0], keys, lengths, groups
1473+
)
1474+
refs = [[] for _ in groups]
1475+
for i in range(permutes.size(0)):
1476+
in_idx, out_idx, in_start, _, length, _ = permutes[i].tolist()
1477+
refs[out_idx].append(values[in_idx][:, in_start : (in_start + length)])
1478+
refs = [torch.cat(ref, dim=1) for ref in refs]
1479+
outputs = torch.ops.fbgemm.permute_multi_embedding(
1480+
values, permutes, in_shapes, out_shapes, out_lengths
1481+
)
1482+
for out, ref in zip(outputs, refs):
1483+
self.assertTrue(torch.allclose(out, ref))
1484+
1485+
def test_multi_permute_backward_cpu(self) -> None:
1486+
batch_size = 32
1487+
keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]]
1488+
lengths = [[3, 4], [5, 6, 7], [8]]
1489+
groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]]
1490+
values = [
1491+
torch.randn(batch_size, sum(lens), device="cpu", requires_grad=True)
1492+
for lens in lengths
1493+
]
1494+
ref_values = [v.detach() for v in values]
1495+
for v in ref_values:
1496+
v.requires_grad = True
1497+
permutes, in_shapes, out_shapes, out_lengths = _kt_regroup_permutes(
1498+
values[0], keys, lengths, groups
1499+
)
1500+
refs = [[] for _ in groups]
1501+
for i in range(permutes.size(0)):
1502+
in_idx, out_idx, in_start, _, length, _ = permutes[i].tolist()
1503+
refs[out_idx].append(ref_values[in_idx][:, in_start : (in_start + length)])
1504+
refs = [torch.cat(ref, dim=1) for ref in refs]
1505+
outputs = torch.ops.fbgemm.permute_multi_embedding(
1506+
values, permutes, in_shapes, out_shapes, out_lengths
1507+
)
1508+
for out, ref in zip(outputs, refs):
1509+
self.assertTrue(torch.allclose(out, ref))
1510+
1511+
ref_loss, loss = refs[0].sum(), outputs[0].sum()
1512+
for i in range(1, len(refs)):
1513+
ref_loss += (i + 1.1) * refs[i].sum()
1514+
loss += (i + 1.1) * outputs[i].sum()
1515+
ref_loss.backward()
1516+
loss.backward()
1517+
for val, ref in zip(values, ref_values):
1518+
val_grad, ref_grad = val.grad, ref.grad
1519+
assert isinstance(val_grad, torch.Tensor)
1520+
self.assertTrue(torch.allclose(val_grad, ref_grad))
1521+
1522+
# pyre-ignore[56]
1523+
@unittest.skipIf(
1524+
torch.cuda.device_count() <= 0,
1525+
"CUDA is not available",
1526+
)
1527+
def test_multi_permute_backward_gpu(self) -> None:
1528+
batch_size = 2048
1529+
keys = [["f1", "f2"], ["f3", "f4", "f5"], ["f6"]]
1530+
lengths = [[96, 256], [512, 128, 768], [1024]]
1531+
groups = [["f1", "f3"], ["f2"], ["f4", "f1", "f6"], ["f1", "f5"]]
1532+
values = [
1533+
torch.randn(batch_size, sum(lens), device="cuda", requires_grad=True)
1534+
for lens in lengths
1535+
]
1536+
ref_values = [v.detach() for v in values]
1537+
for v in ref_values:
1538+
v.requires_grad = True
1539+
permutes, in_shapes, out_shapes, out_lengths = _kt_regroup_permutes(
1540+
values[0], keys, lengths, groups
1541+
)
1542+
refs = [[] for _ in groups]
1543+
for i in range(permutes.size(0)):
1544+
in_idx, out_idx, in_start, _, length, _ = permutes[i].tolist()
1545+
refs[out_idx].append(ref_values[in_idx][:, in_start : (in_start + length)])
1546+
refs = [torch.cat(ref, dim=1) for ref in refs]
1547+
outputs = torch.ops.fbgemm.permute_multi_embedding(
1548+
values, permutes, in_shapes, out_shapes, out_lengths
1549+
)
1550+
for out, ref in zip(outputs, refs):
1551+
self.assertTrue(torch.allclose(out, ref))
1552+
1553+
ref_loss, loss = refs[0].sum(), outputs[0].sum()
1554+
for i in range(1, len(refs)):
1555+
ref_loss += (i + 1.1) * refs[i].sum()
1556+
loss += (i + 1.1) * outputs[i].sum()
1557+
ref_loss.backward()
1558+
loss.backward()
1559+
for val, ref in zip(values, ref_values):
1560+
val_grad, ref_grad = val.grad, ref.grad
1561+
assert isinstance(val_grad, torch.Tensor)
1562+
self.assertTrue(torch.allclose(val_grad, ref_grad))
1563+
13771564
def test_permute_duplicates(self) -> None:
13781565
values = torch.Tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
13791566
lengths = torch.IntTensor([0, 2, 0, 1, 1, 1, 0, 3, 0])
@@ -1650,8 +1837,6 @@ def test_string_vb(self) -> None:
16501837
stride_per_key_per_rank=stride_per_key_per_rank,
16511838
)
16521839

1653-
print(str(jag_tensor))
1654-
16551840
self.assertEqual(
16561841
str(jag_tensor),
16571842
"""\

0 commit comments

Comments
 (0)