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

Remove num_traits dependency #3373

Merged
merged 2 commits into from
Apr 24, 2023
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions components/segmenter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ zerovec = { version = "0.9.4", path = "../../utils/zerovec", features = ["yoke"]
databake = { version = "0.1.3", path = "../../utils/databake", optional = true, features = ["derive"] }
serde = { version = "1.0", default-features = false, features = ["derive", "alloc"], optional = true }

num-traits = { version = "0.2", default-features = false, features = ["libm"], optional = true }
libm = { version = "0.2", default-features = false, optional = true }

[dev-dependencies]
criterion = "0.4"
Expand All @@ -56,7 +56,7 @@ default = ["auto"]
std = ["icu_collections/std", "icu_locid/std", "icu_provider/std"]
serde = ["dep:serde", "zerovec/serde", "icu_collections/serde", "icu_provider/serde"]
datagen = ["serde", "dep:databake", "zerovec/databake", "icu_collections/databake"]
lstm = ["dep:num-traits"]
lstm = ["dep:libm"]
auto = ["lstm"] # Enabled try_new_auto_unstable constructors

[lib]
Expand Down
45 changes: 26 additions & 19 deletions components/segmenter/src/complex/lstm/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@ use core::ops::Range;
use zerovec::ule::AsULE;
use zerovec::ZeroSlice;

// Polyfill float operations with libm in case we're no_std.
#[allow(unused_imports)]
use num_traits::Float;

/// `tanh` computes the tanh function for a scalar value.
#[inline]
fn tanh(x: f32) -> f32 {
x.tanh()
// This will be used in #[no_std] as f32::exp/f32::tanh are not in core.
trait CoreFloat {
fn exp(self) -> Self;
fn tanh(self) -> Self;
}

/// `sigmoid` computes the sigmoid function for a scalar value.
#[inline]
fn sigmoid(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
// TODO: Find a way to do this without libm. There's an intrinsic
// that produces `llvm.exp.f32`, but that's not exposed through
// f32. Another option would be to declare `extern "Rust"` and
// let clients provide these functions.
impl CoreFloat for f32 {
fn exp(self) -> Self {
libm::expf(self)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: before we introduced libm via num-traits, we had been using the f32::exp function. Now we're unconditionally using the libm version. Explain?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we? In std mode this would fall back to f32.exp(), no?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before we were either using the inherent f32::exp, or num_traits::Float::f32, which is backed by libm. This is doing the exact same thing.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before we introduced num_traits we weren't no_std. With std, function resolution will use f32::exp, without it will use CoreFloat::exp.

}

fn tanh(self) -> Self {
libm::tanhf(self)
}
}

/// A `D`-dimensional, heap-allocated matrix.
Expand Down Expand Up @@ -209,21 +213,24 @@ impl<'a, const D: usize> MatrixBorrowedMut<'a, D> {

/// Mutates this matrix by applying a softmax transformation.
pub(super) fn softmax_transform(&mut self) {
let sm = self.data.iter().map(|v| v.exp()).sum::<f32>();
self.data.iter_mut().for_each(|v| {
*v = v.exp() / sm;
});
for v in self.data.iter_mut() {
*v = v.exp();
}
let sm = 1.0 / self.data.iter().sum::<f32>();
for v in self.data.iter_mut() {
*v *= sm;
}
}

pub(super) fn sigmoid_transform(&mut self) {
for x in &mut self.data.iter_mut() {
*x = sigmoid(*x);
*x = 1.0 / (1.0 + (-*x).exp());
}
}

pub(super) fn tanh_transform(&mut self) {
for x in &mut self.data.iter_mut() {
*x = tanh(*x);
*x = x.tanh();
}
}

Expand Down Expand Up @@ -262,7 +269,7 @@ impl<'a, const D: usize> MatrixBorrowedMut<'a, D> {
// Safety: The lengths are all the same (checked above)
unsafe {
*self.data.get_unchecked_mut(idx) =
o.get_unchecked(idx) * tanh(*c.get_unchecked(idx));
o.get_unchecked(idx) * c.get_unchecked(idx).tanh();
}
}
}
Expand Down
18 changes: 1 addition & 17 deletions ffi/gn/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions ffi/gn/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ rustflags = []
[gn.package.syn."1.0.109"]
rustflags = ["--cfg=syn_disable_nightly_tests"]

[gn.package.num-traits."0.2.15"]
rustflags = ["--cfg=has_i128"]

[gn.package.libm."0.2.6"]
rustflags = []

Expand Down
25 changes: 1 addition & 24 deletions ffi/gn/icu4x/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ rust_library("icu_segmenter-v1_2_1") {
deps += [ ":icu_collections-v1_2_0" ]
deps += [ ":icu_locid-v1_2_0" ]
deps += [ ":icu_provider-v1_2_0" ]
deps += [ ":num-traits-v0_2_15" ]
deps += [ ":libm-v0_2_6" ]
deps += [ ":utf8_iter-v1_0_3" ]
deps += [ ":zerovec-v0_9_4" ]

Expand Down Expand Up @@ -752,7 +752,6 @@ rust_library("libm-v0_2_6") {
"--edition=2018",
"-Cmetadata=6b5214f2031c6f9e",
"-Cextra-filename=-6b5214f2031c6f9e",
"--cfg=feature=\"default\"",
]

visibility = [ ":*" ]
Expand Down Expand Up @@ -820,28 +819,6 @@ rust_library("memchr-v2_5_0") {
visibility = [ ":*" ]
}

rust_library("num-traits-v0_2_15") {
crate_name = "num_traits"
crate_root = "//ffi/gn/vendor/num-traits/src/lib.rs"
output_name = "num_traits-64c0e09f0f13aa66"

deps = []
deps += [ ":libm-v0_2_6" ]

rustenv = []

rustflags = [
"--cap-lints=allow",
"--edition=2015",
"-Cmetadata=64c0e09f0f13aa66",
"-Cextra-filename=-64c0e09f0f13aa66",
"--cfg=feature=\"libm\"",
"--cfg=has_i128",
]

visibility = [ ":*" ]
}

rust_library("proc-macro2-v1_0_56") {
crate_name = "proc_macro2"
crate_root = "//ffi/gn/vendor/proc-macro2/src/lib.rs"
Expand Down
3 changes: 2 additions & 1 deletion tools/depcheck/src/allowlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub const EXTRA_EXPERIMENTAL_DEPS: &[&str] = &[
];

/// Dependencies allowed when opting in to LSTM segmenter
pub const EXTRA_LSTM_DEPS: &[&str] = &["libm", "num-traits"];
pub const EXTRA_LSTM_DEPS: &[&str] = &["libm"];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

praise: thanks for updating this.

(I have plans to make this file complain if an allowlisted dep goes completely unused after all of the checks, but it's not priority)


/// Dependencies allowed when opting in to fixed_decimal's `ryu` backend
/// This should never change
Expand Down Expand Up @@ -122,6 +122,7 @@ pub const EXTRA_DATAGEN_DEPS: &[&str] = &[
"ndarray",
"num-complex",
"num-integer",
"num-traits",
"rawpointer",
"regex-syntax",
"rust-format",
Expand Down