22 * Copyright (c) Microsoft Corporation.
33 * Licensed under the MIT license.
44 */
5- use std:: num:: { NonZero , NonZeroUsize } ;
5+ use std:: num:: NonZero ;
66
77use crate :: inputs:: {
88 as_input, exhaustive,
@@ -211,6 +211,54 @@ fn bftree_parameters_from(
211211 }
212212}
213213
214+ /// Supported bit widths for spherical quantization.
215+ #[ derive( Debug , Clone , Copy , PartialEq , Eq , Serialize ) ]
216+ pub ( crate ) enum SphericalBits {
217+ #[ serde( rename = "1" ) ]
218+ One = 1 ,
219+ #[ serde( rename = "2" ) ]
220+ Two = 2 ,
221+ #[ serde( rename = "4" ) ]
222+ Four = 4 ,
223+ }
224+
225+ impl SphericalBits {
226+ pub ( crate ) const fn get ( self ) -> usize {
227+ self as usize
228+ }
229+ }
230+
231+ impl std:: fmt:: Display for SphericalBits {
232+ fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
233+ write ! ( f, "{}" , self . get( ) )
234+ }
235+ }
236+
237+ impl TryFrom < usize > for SphericalBits {
238+ type Error = String ;
239+
240+ fn try_from ( value : usize ) -> Result < Self , Self :: Error > {
241+ match value {
242+ 1 => Ok ( Self :: One ) ,
243+ 2 => Ok ( Self :: Two ) ,
244+ 4 => Ok ( Self :: Four ) ,
245+ n => Err ( format ! (
246+ "{n} bits not supported for spherical quantization; expected 1, 2, or 4"
247+ ) ) ,
248+ }
249+ }
250+ }
251+
252+ impl < ' de > Deserialize < ' de > for SphericalBits {
253+ fn deserialize < D > ( deserializer : D ) -> Result < Self , D :: Error >
254+ where
255+ D : serde:: Deserializer < ' de > ,
256+ {
257+ let n = usize:: deserialize ( deserializer) ?;
258+ SphericalBits :: try_from ( n) . map_err ( serde:: de:: Error :: custom)
259+ }
260+ }
261+
214262#[ derive( Debug , Clone , Serialize , Deserialize ) ]
215263#[ serde( tag = "kind" ) ]
216264pub ( crate ) enum QuantConfig {
@@ -220,7 +268,7 @@ pub(crate) enum QuantConfig {
220268 Spherical {
221269 seed : u64 ,
222270 transform_kind : exhaustive:: TransformKind ,
223- num_bits : NonZeroUsize ,
271+ num_bits : SphericalBits ,
224272 #[ serde( deserialize_with = "Deserialize::deserialize" ) ]
225273 pre_scale : Option < exhaustive:: PreScale > ,
226274 #[ serde( deserialize_with = "Deserialize::deserialize" ) ]
@@ -233,14 +281,8 @@ impl QuantConfig {
233281 match self {
234282 Self :: None => Ok ( ( ) ) ,
235283 Self :: Spherical {
236- num_bits,
237- quant_store_config,
238- ..
284+ quant_store_config, ..
239285 } => {
240- match num_bits. get ( ) {
241- 1 | 2 | 4 => { }
242- n => anyhow:: bail!( "{n} bits are not supported for spherical quantization" ) ,
243- }
244286 if let Some ( cfg) = quant_store_config {
245287 cfg. fill_defaults ( ) ;
246288 cfg. validate ( ) ?;
0 commit comments