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

safe softmax #83

Merged
merged 1 commit into from
Aug 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
safe softmax
  • Loading branch information
siboehm committed Aug 3, 2024
commit e50798e9280b861df199399ddb9d9d2ba3afc7a5
20 changes: 13 additions & 7 deletions lleaves/compiler/codegen/codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,14 +367,20 @@ def _populate_sigmoid(alpha):
result = args[0]
elif objective == "multiclass":
assert len(args)
# TODO Might profit from vectorization, needs testing
result = [builder.call(llvm_exp, [arg]) for arg in args]

# stable softmax
max_val = args[0]
for arg in args[1:]:
max_val = builder.select(
builder.fcmp_ordered(">", arg, max_val), arg, max_val
)
exp_vals = [
builder.call(llvm_exp, [builder.fsub(arg, max_val)]) for arg in args
]
denominator = get_fdtype_const(0.0, use_fp64)
for r in result:
denominator = builder.fadd(r, denominator)

result = [builder.fdiv(r, denominator) for r in result]
for exp_val in exp_vals:
denominator = builder.fadd(exp_val, denominator)
denominator = builder.fadd(denominator, get_fdtype_const(1e-15, use_fp64))
result = [builder.fdiv(exp_val, denominator) for exp_val in exp_vals]
else:
raise ValueError(
f"Objective '{objective}' not yet implemented. {ISSUE_ERROR_MSG}"
Expand Down
Loading