-
Notifications
You must be signed in to change notification settings - Fork 635
feat: support bf16 from pytorch dataset #6342
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
60e8da4
support bf16 from torch
eddyxu 0d48a7c
m;
eddyxu d3996c9
only opportunitically not copy data
eddyxu 0c155a6
reduce number of memory cpies
eddyxu 0123dea
fix ruff
eddyxu 595e7d4
Merge branch 'main' into lei/torch_bf16
eddyxu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -52,6 +52,52 @@ def __call__( | |
| ) -> Union[dict[str, torch.Tensor], torch.Tensor]: ... | ||
|
|
||
|
|
||
| def _is_bfloat16_type(t: pa.DataType) -> bool: | ||
| """Check if a PyArrow type is the lance bfloat16 extension type.""" | ||
| return isinstance(t, pa.ExtensionType) and t.extension_name == "lance.bfloat16" | ||
|
|
||
|
|
||
| def _bf16_to_tensor(arr: pa.Array) -> torch.Tensor: | ||
| """Convert a bfloat16 extension array to a torch.bfloat16 tensor. | ||
|
|
||
| Reinterprets the raw bytes as uint16 and views as bfloat16, | ||
| since they share the same 2-byte memory layout. | ||
| Null values are replaced with NaN. | ||
| """ | ||
| storage = arr.storage if isinstance(arr.type, pa.ExtensionType) else arr | ||
| buf = storage.buffers()[1] | ||
| offset = storage.offset * 2 # 2 bytes per bf16 value | ||
| try: | ||
| with warnings.catch_warnings(): | ||
| warnings.filterwarnings( | ||
| "ignore", | ||
| message="The given buffer is not writable", | ||
| category=UserWarning, | ||
| ) | ||
| tensor = torch.frombuffer( | ||
| memoryview(buf), | ||
| dtype=torch.uint16, | ||
| count=len(storage), | ||
| offset=offset, | ||
| ).view(torch.bfloat16) | ||
| except (AttributeError, RuntimeError, TypeError): | ||
| np_uint16 = np.frombuffer( | ||
| buf, dtype=np.uint16, count=len(storage), offset=offset | ||
| ) | ||
| with warnings.catch_warnings(): | ||
| warnings.filterwarnings( | ||
| "ignore", | ||
| message="The given NumPy array is not writable", | ||
| category=UserWarning, | ||
| ) | ||
| tensor = torch.from_numpy(np_uint16).view(torch.bfloat16) | ||
| if arr.null_count > 0: | ||
| tensor = tensor.clone() | ||
| null_mask = torch.from_numpy(arr.is_null().to_numpy(zero_copy_only=False)) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems like there should be a way to do this without a copy but maybe not.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. asked claude / codex to do double checks, to make this opportunist |
||
| tensor[null_mask] = float("nan") | ||
| return tensor | ||
|
|
||
|
|
||
| # Convert an Arrow FSL array into a 2D torch tensor | ||
| def _fsl_to_tensor(arr: pa.FixedSizeListArray, dimension: int) -> torch.Tensor: | ||
| # Note: FixedSizeListArray.values does not take offset/len into account and | ||
|
|
@@ -104,6 +150,14 @@ def _to_tensor( | |
| or pa.types.is_integer(arr.type.value_type) | ||
| ): | ||
| tensor = _fsl_to_tensor(arr, arr.type.list_size) | ||
| elif pa.types.is_fixed_size_list(arr.type) and _is_bfloat16_type( | ||
| arr.type.value_type | ||
| ): | ||
| values = arr.values | ||
| start = arr.offset * arr.type.list_size | ||
| num_vals = len(arr) * arr.type.list_size | ||
| values = values.slice(start, num_vals) | ||
| tensor = _bf16_to_tensor(values).view(-1, arr.type.list_size) | ||
| elif ( | ||
| pa.types.is_integer(arr.type) | ||
| or pa.types.is_floating(arr.type) | ||
|
|
@@ -113,13 +167,15 @@ def _to_tensor( | |
|
|
||
| if uint64_as_int64 and tensor.dtype == torch.uint64: | ||
| tensor = tensor.to(torch.int64) | ||
| elif _is_bfloat16_type(arr.type): | ||
| tensor = _bf16_to_tensor(arr) | ||
| elif hf_converter is not None: | ||
| tensor = hf_converter.to_pytorch(col, arr) | ||
|
|
||
| if tensor is None: | ||
| raise ValueError( | ||
| "Only support FixedSizeList<f16/f32/f64> or " | ||
| + f"numeric values, got: {arr.type}" | ||
| "Only support FixedSizeList<f16/bf16/f32/f64> or " | ||
| + f"numeric/bfloat16 values, got: {arr.type}" | ||
| ) | ||
|
|
||
| del arr | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we do a sanity check that the data type of storage is a 16-bit type at this point?