Skip to content
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

Please do not talk too much about the broadcast mechanism. #2639

Open
a358003542 opened this issue Mar 21, 2025 · 0 comments
Open

Please do not talk too much about the broadcast mechanism. #2639

a358003542 opened this issue Mar 21, 2025 · 0 comments

Comments

@a358003542
Copy link

a358003542 commented Mar 21, 2025

About Chapter 2.1.4 and 2.3.7, there is too much talk about the broadcast mechanism. It's like the implicit type conversion rule, which is not a good programming style.

About 2.3.7, a good programming style is to call the functions supplied by torch.nn.functional:

import torch
import torch.nn.functional as F

# 创建示例张量
data = torch.arange(20, dtype=torch.float32).reshape(5, 4)

# 使用 torch.nn.functional.normalize 进行 L2 归一化
normalized_data_l2 = F.normalize(data, p=2, dim=1)

# 使用 torch.nn.functional.normalize 进行 L1 归一化
normalized_data_l1 = F.normalize(data, p=1, dim=1)

print("Original data:")
print(data)
print("Normalized data (L2 norm):")
print(normalized_data_l2)
print("Normalized data (L1 norm):")
print(normalized_data_l1)

If there is really a need to use the broadcast mechanism, recommend first checkout the broadcast output:

np.broadcast_arrays(x, y)
torch.broadcast_tensors(x, y)

This helps to check what the internal broadcast mechanism will output. The broadcast mechanism is an internal mechanism in NumPy designed for speeding up computations. However, encouraging the use of this style of code is not a good idea.

@a358003542 a358003542 changed the title Please do not talk too much about the boardcast mechnism. Please do not talk too much about the broadcast mechanism. Mar 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant