You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@solr.apache.org by "liangkaiwen (via GitHub)" <gi...@apache.org> on 2025/06/11 21:13:07 UTC

[PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

liangkaiwen opened a new pull request, #3385:
URL: https://github.com/apache/solr/pull/3385

   https://issues.apache.org/jira/browse/SOLR-17780
   
   <!--
   _(If you are a project committer then you may remove some/all of the following template.)_
   
   Before creating a pull request, please file an issue in the ASF Jira system for Solr:
   
   * https://issues.apache.org/jira/projects/SOLR
   
   For something minor (i.e. that wouldn't be worth putting in release notes), you can skip JIRA. 
   To create a Jira issue, you will need to create an account there first.
   
   The title of the PR should reference the Jira issue number in the form:
   
   * SOLR-####: <short description of problem or changes>
   
   SOLR must be fully capitalized. A short description helps people scanning pull requests for items they can work on.
   
   Properly referencing the issue in the title ensures that Jira is correctly updated with code review comments and commits. -->
   
   
   # Description
   
   Lucene 9.9 codec includes an implementation of scalar quantized dense vectors. This is not yet supported in Solr.
   
   # Solution
   
   * Add a new schema type ScalarQuantizedDenseVectorField
   * Add usage of Lucene99ScalarQuantizedVectorsFormat / Lucene99HnswScalarQuantizedVectorsFormat in SchemaCodecFactory. This incorporates the respective index reader/writers
   
   # Tests
   
   TODO
   
   # Checklist
   
   Please review the following and check all that apply:
   
   - [X] I have reviewed the guidelines for [How to Contribute](https://github.com/apache/solr/blob/main/CONTRIBUTING.md) and my code conforms to the standards described there to the best of my ability.
   - [X] I have created a Jira issue and added the issue ID to my pull request title.
   - [ ] I have given Solr maintainers [access](https://help.github.com/en/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork) to contribute to my PR branch. (optional but recommended, not available for branches on forks living under an organisation)
   - [X] I have developed this patch against the `main` branch.
   - [ ] I have run `./gradlew check`.
   - [ ] I have added tests for my changes.
   - [ ] I have added documentation for the [Reference Guide](https://github.com/apache/solr/tree/main/solr/solr-ref-guide)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2162651193


##########
solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java:
##########
@@ -126,16 +131,41 @@ public DocValuesFormat getDocValuesFormatForField(String field) {
           public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
             final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
             FieldType fieldType = (schemaField == null ? null : schemaField.getType());
-            if (fieldType instanceof DenseVectorField vectorType) {
+            KnnVectorsFormat delegate;

Review Comment:
   I'm not quite sure I follow. You mean the ScalarQuantizedDenseVectorField init() or the SchemaCodecFactory init()?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2161880154


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.get(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+        args.remove(BITS);
+
+        this.compress = ofNullable(args.get(COMPRESS))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(COMPRESS);
+
+        boolean useDynamicConfidenceInterval = ofNullable(args.get(DYNAMIC_CONFIDENCE_INTERVAL))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(DYNAMIC_CONFIDENCE_INTERVAL);
+
+        if (useDynamicConfidenceInterval) {
+            this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+        }
+
+        this.confidenceInterval = ofNullable(args.get(CONFIDENCE_INTERVAL))

Review Comment:
   good catch. I was hoping to make any explicit confidence interval override the dynamic behavior, however with both absence of arg and the default being null I think I will flip the behavior (use dynamic if specified otherwise confidence interval if specified otherwise default confidence interval if none provided)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3249436008

   Checks and tests are still failing @liangkaiwen , I'll give it a try now, If I fix them in 1 hour I'll merge, if not I'll ask you to give a double check, keep you posted!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2164242176


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.get(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+        args.remove(BITS);
+
+        this.compress = ofNullable(args.get(COMPRESS))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(COMPRESS);
+
+        boolean useDynamicConfidenceInterval = ofNullable(args.get(DYNAMIC_CONFIDENCE_INTERVAL))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(DYNAMIC_CONFIDENCE_INTERVAL);
+
+        if (useDynamicConfidenceInterval) {
+            this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+        }
+
+        this.confidenceInterval = ofNullable(args.get(CONFIDENCE_INTERVAL))

Review Comment:
   If neither are set, it should default to the default behavior (scaled confidence interval) - which according to lucene spec is passing a null confidence interval



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2252655453


##########
solr/solr-ref-guide/modules/query-guide/pages/dense-vector-search.adoc:
##########
@@ -240,6 +240,66 @@ client.add(Arrays.asList(d1, d2));
 ====
 ======
 
+=== ScalarQuantizedDenseVectorField
+Because dense vectors can have a costly storage footprint, it may be worthwhile to use a technique called "quantization"
+to reduce the stored representation size at the cost of some precision.
+
+This dense vector type uses a conversion that projects a 32 bit float precision feature down to an 8 bit int (or smaller)
+by linearly mapping the float range down to evenly sized "buckets" of values that fit into an int. A more detailed explanation
+can be found in this https://www.elastic.co/search-labs/blog/scalar-quantization-101[blog post].
+
+As a specific type of DenseVectorField, this field type supports all the same configurable properties outlined above as well
+as some additional ones.
+
+Here is how a ScalarQuantizedDenseVectorField can be defined in the schema:
+
+[source,xml]
+<fieldType name="scalar_quantized_vector" class="solr.ScalarQuantizedDenseVectorField" vectorDimension="4" similarityFunction="cosine"/>
+<field name="vector" type="scalar_quantized_vector" indexed="true" stored="true"/>
+
+`bits`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `7`
+|===
++
+The number of bits to use for each quantized dimension value
++
+Accepted values: 4 (half byte) or 7 (unsigned byte).
+
+`confidenceInterval`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `dimension-scaled`
+|===
++
+Statistically, outlier values are rarely meaningfully relevant to searches, so to increase the size of each bucket for
+quantization (and therefore information gain) we can scale the quantization intervals to the middle n % of values and place the remaining
+outliers in the outermost intervals.
++
+For example: 0.9 means scale interval sizes to the middle 90% of values
++
+If this param is omitted a default is used; scaled to the number of dimensions according to `1-1/(vector_dimensions + 1)`
++
+If `0` is provided, confidence intervals will be dynamically adjusted (at segment merge time) optimized by sampling values
++
+Accepted values: `FLOAT32`  (within 0.9 and 1.0) or 0 for dynamically adjusted confidence interval
+
+`compress`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `false`
+|===
++
+If set to true, this will further pack multiple dimension values within a one byte alignment. This further decreases the storage size by 50% at some decode penalty.

Review Comment:
   I believe this is on disk packing. Will add clarification



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3237105369

   Just a quick comment: next time please don't rebase a PR; simply merge main into it.  I've found rebasing PRs to be a bad practice as it resets the GitHub review state, making it impossible to be certain what incremental changes happened (if any).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2252668526


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  // lucene does not expose these so we are duplicating them here
+  static final Float MINIMUM_CONFIDENCE_INTERVAL = 0.9f;
+  static final Float MAXIMUM_CONFIDENCE_INTERVAL = 1f;
+
+  /**
+   * Number of bits to use for storage Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec
+   * spec
+   */
+  private int bits;
+
+  /**
+   * Confidence interval to use for scalar quantization Default is calculated as
+   * `1-1/(vector_dimensions + 1)`
+   */
+  private Float confidenceInterval;
+
+  /**
+   * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50%
+   * reduction in memory usage (comes at the cost of some decode speed penalty)
+   */
+  private boolean compress;
+
+  public ScalarQuantizedDenseVectorField() {
+    super();
+  }
+
+  public ScalarQuantizedDenseVectorField(
+      int dimension,
+      VectorSimilarityFunction similarityFunction,
+      VectorEncoding vectorEncoding,
+      int bits,
+      Float confidenceInterval,
+      boolean compress) {
+    super(dimension, similarityFunction, vectorEncoding);
+    this.bits = bits;
+    this.confidenceInterval = confidenceInterval;
+    this.compress = compress;
+  }
+
+  @Override
+  public void init(IndexSchema schema, Map<String, String> args) {
+    this.bits = ofNullable(args.remove(BITS_PARAM)).map(Integer::parseInt).orElse(DEFAULT_BITS);
+
+    this.compress =
+        ofNullable(args.remove(COMPRESS_PARAM)).map(Boolean::parseBoolean).orElse(false);
+
+    this.confidenceInterval =
+        ofNullable(args.remove(CONFIDENCE_INTERVAL_PARAM))
+            .map(Float::parseFloat)
+            .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+    if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL_PARAM))
+        .map(Boolean::parseBoolean)
+        .orElse(false)) {
+      this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+    }
+
+    super.init(schema, args);
+  }
+
+  @Override
+  public KnnVectorsFormat buildKnnVectorsFormat() {
+    return new Lucene99HnswScalarQuantizedVectorsFormat(
+        getHnswMaxConn(),
+        getHnswBeamWidth(),
+        DEFAULT_NUM_MERGE_WORKER,
+        getBits(),
+        useCompression(),
+        getConfidenceInterval(),
+        null);
+  }
+
+  @Override
+  public void checkSchemaField(final SchemaField field) throws SolrException {
+    super.checkSchemaField(field);
+
+    if (confidenceInterval != null
+        && confidenceInterval != Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL
+        && (confidenceInterval < MINIMUM_CONFIDENCE_INTERVAL
+            || confidenceInterval > MAXIMUM_CONFIDENCE_INTERVAL)) {
+      throw new SolrException(
+          SolrException.ErrorCode.SERVER_ERROR,
+          getClass().getSimpleName()
+              + " fields must have non-dynamic confidence interval between 0.9 and 1.0 "
+              + field.getName());
+    }
+    if (getBits() != 4 && getBits() != 7) {

Review Comment:
   I agree, it's bad practice to duplicate validation code. The lucene implementation doesn't expose any validation function, but I updated the code to just simply call the format constructor and not store the created object. Exception must be a SolrException to match the inherited interface, so I wrapped the IllegalArgumentException. Let me know if this meets your expectation?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2277429620


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  /**
+   * Number of bits to use for storage Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec
+   * spec
+   */
+  private int bits;
+
+  /**
+   * Confidence interval to use for scalar quantization Default is calculated as
+   * `1-1/(vector_dimensions + 1)`
+   */
+  private Float confidenceInterval;
+
+  /**
+   * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50%
+   * reduction in memory usage (comes at the cost of some decode speed penalty)
+   */
+  private boolean compress;
+
+  public ScalarQuantizedDenseVectorField() {
+    super();
+  }
+
+  public ScalarQuantizedDenseVectorField(
+      int dimension,
+      VectorSimilarityFunction similarityFunction,
+      VectorEncoding vectorEncoding,
+      int bits,
+      Float confidenceInterval,
+      boolean compress) {
+    super(dimension, similarityFunction, vectorEncoding);
+    this.bits = bits;
+    this.confidenceInterval = confidenceInterval;
+    this.compress = compress;
+  }
+
+  @Override
+  public void init(IndexSchema schema, Map<String, String> args) {
+    this.bits = ofNullable(args.remove(BITS_PARAM)).map(Integer::parseInt).orElse(DEFAULT_BITS);
+
+    this.compress =
+        ofNullable(args.remove(COMPRESS_PARAM)).map(Boolean::parseBoolean).orElse(false);
+
+    this.confidenceInterval =
+        ofNullable(args.remove(CONFIDENCE_INTERVAL_PARAM))
+            .map(Float::parseFloat)
+            .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+    if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL_PARAM))
+        .map(Boolean::parseBoolean)
+        .orElse(false)) {
+      this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+    }
+
+    super.init(schema, args);
+  }
+
+  @Override
+  public KnnVectorsFormat buildKnnVectorsFormat() {
+    return new Lucene99HnswScalarQuantizedVectorsFormat(
+        getHnswMaxConn(),
+        getHnswBeamWidth(),
+        DEFAULT_NUM_MERGE_WORKER,
+        getBits(),
+        useCompression(),
+        getConfidenceInterval(),
+        null);
+  }
+
+  @Override
+  public void checkSchemaField(final SchemaField field) throws SolrException {
+    super.checkSchemaField(field);
+
+    try {
+      // format does not expose any validation, however by constructing
+      // we will run lucene level argument validation
+      buildKnnVectorsFormat();
+    } catch (Exception e) {

Review Comment:
   changed type to IllegalArgumentException



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2161978585


##########
solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java:
##########
@@ -126,16 +131,41 @@ public DocValuesFormat getDocValuesFormatForField(String field) {
           public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
             final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
             FieldType fieldType = (schemaField == null ? null : schemaField.getType());
-            if (fieldType instanceof DenseVectorField vectorType) {
+            KnnVectorsFormat delegate;

Review Comment:
   reworked it. Let me know if this is along the lines of what you were thinking



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2162930217


##########
solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java:
##########
@@ -126,16 +131,41 @@ public DocValuesFormat getDocValuesFormatForField(String field) {
           public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
             final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
             FieldType fieldType = (schemaField == null ? null : schemaField.getType());
-            if (fieldType instanceof DenseVectorField vectorType) {
+            KnnVectorsFormat delegate;

Review Comment:
   `ScalarQuantizedDenseVectorField.init()` (and its subclass, DenseVectorField) creating a `KnnVectorsFormat` that later can simply be returned.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2179755734


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec

Review Comment:
   these first four lines are param names if I'm not mistaken.
   
   Maybe we can call them '<name>_PARAM' e.g. 'BITS_PARAM'
   
   Or add a comment line at the beginning that clearly group them as param names,
   it's a minor though, but can increase code readability



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.remove(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+
+        this.compress = ofNullable(args.remove(COMPRESS))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+
+        this.confidenceInterval = ofNullable(args.remove(CONFIDENCE_INTERVAL))
+                .map(Float::parseFloat)
+                .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+        if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL))
+                .map(Boolean::parseBoolean)
+                .orElse(false)) {
+            this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+        }
+    }
+
+    @Override
+    public KnnVectorsFormat buildKnnVectorsFormat() {
+        final String knnAlgorithm = getKnnAlgorithm();
+        if (KNN_ALGORITHM.equals(knnAlgorithm)) {

Review Comment:
   From an initial review the ScalarQuantizedDenseVectorField should always return the Lucene99HnswScalarQuantizedVectorsFormat.
   
   The traditional DenseVectorField, should always return Lucene99HnswVectorsFormat



##########
solr/core/src/java/org/apache/solr/schema/DenseVectorField.java:
##########
@@ -64,6 +65,7 @@
 public class DenseVectorField extends FloatPointField {
   private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
   public static final String HNSW_ALGORITHM = "hnsw";
+  public static final String FLAT_ALGORITHM = "flat";

Review Comment:
   'VECTOR_STORAGE_ALGORITHM' maybe?
   Is it used somewhere?



##########
solr/core/src/java/org/apache/solr/schema/DenseVectorField.java:
##########
@@ -64,6 +65,7 @@
 public class DenseVectorField extends FloatPointField {
   private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
   public static final String HNSW_ALGORITHM = "hnsw";
+  public static final String FLAT_ALGORITHM = "flat";

Review Comment:
   reading it more we are mixing up the 'knn' algorithm (only HNSW supported right now), with the 'vector storage' (flat, scalarQuantised and binaryQuantised



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.remove(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+
+        this.compress = ofNullable(args.remove(COMPRESS))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+
+        this.confidenceInterval = ofNullable(args.remove(CONFIDENCE_INTERVAL))
+                .map(Float::parseFloat)
+                .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+        if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL))
+                .map(Boolean::parseBoolean)
+                .orElse(false)) {
+            this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+        }
+    }
+
+    @Override
+    public KnnVectorsFormat buildKnnVectorsFormat() {
+        final String knnAlgorithm = getKnnAlgorithm();
+        if (KNN_ALGORITHM.equals(knnAlgorithm)) {

Review Comment:
   mmmm not sure about this part:
   
   The only knn algorithm supported right now is 'HNSW'.
   While for vector storage, there's flat (what currently supported), scalar quantised and binary quantised.
   Effectively in Lucene HNSW vector formats define how to build and read the HNSW graph (where each vector ID is a node). 
   Vector storage formats define how to store the vectors themselves.
   
   The vector storage format is directly (and only) used by a the graph format parent ( I had in my to-do list to re-organise the package to easily differentiate graph from storage formats)
   
   **Lucene99HnswVectorsFormat** uses **Lucene99FlatVectorsFormat**.
   • Store for each field the vector metadata (.vemf) and vector data (vec).
   • It has a dedicated writer and reader, dependent on the vector encoding (BYTE or
   FLOAT32).
   • It has its scorer (that just uses the supplied similarity).
   
   **Lucene99HnswScalarQuantizedVectorsFormat** uses **Lucene99ScalarQuantizedVectorsFormat** (for scalar quantisation).
   • Lossy compression from float32 to a number of bits (4 or 7)
   • Raw disk increases (raw + quantized vectors).
   • Off-heap memory decreases as quantised vectors are loaded.
   • Search is faster.
   • It has a dedicated writer and reader, dependent on the bits to use for quantisation.
   
   Given that, I suspect with this contribution we want to differentiate between:
   Lucene99HnswVectorsFormat and Lucene99HnswScalarQuantizedVectorsFormat (without manipulating directly the vector storage).
   
   -> the if then else should be changed I suspect, I don't understand it as it is right now as we are mixing a graph format (Lucene99HnswScalarQuantizedVectorsFormat already using the scalar quantised storage format) and a vectore storage format (Lucene99ScalarQuantizedVectorsFormat)
   
   



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec

Review Comment:
   to be fair, checking the original DenseVectorField, the same renaming could help there as well I suspect



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3236501756

   Hi @liangkaiwen , I rebased, added CHANGES.txt, and now tests are broken. I don't have bandwidth now to investigate, can you? Let me know under the comments, I'm happy to finalise this and merge it soon!
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2162361836


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.get(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+        args.remove(BITS);
+
+        this.compress = ofNullable(args.get(COMPRESS))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(COMPRESS);
+
+        boolean useDynamicConfidenceInterval = ofNullable(args.get(DYNAMIC_CONFIDENCE_INTERVAL))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(DYNAMIC_CONFIDENCE_INTERVAL);
+
+        if (useDynamicConfidenceInterval) {
+            this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+        }
+
+        this.confidenceInterval = ofNullable(args.get(CONFIDENCE_INTERVAL))

Review Comment:
   Okay but then let's check if both are set and throw an exception.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2164268484


##########
solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java:
##########
@@ -126,16 +131,41 @@ public DocValuesFormat getDocValuesFormatForField(String field) {
           public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
             final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
             FieldType fieldType = (schemaField == null ? null : schemaField.getType());
-            if (fieldType instanceof DenseVectorField vectorType) {
+            KnnVectorsFormat delegate;

Review Comment:
   That's probably true. However it does look like the getters are used in the DenseVectorField tests as KnnVectorsFormat doesn't expose the internal setting values. Personally I think it's ok to leave patterned as-is and having getters affords some level of flexibility and transparency.
   
   But I can make this change if you feel strongly about it



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2147416267


##########
solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java:
##########
@@ -126,16 +131,41 @@ public DocValuesFormat getDocValuesFormatForField(String field) {
           public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
             final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
             FieldType fieldType = (schemaField == null ? null : schemaField.getType());
-            if (fieldType instanceof DenseVectorField vectorType) {
+            KnnVectorsFormat delegate;

Review Comment:
   The instanceof checks can be a code smell.  I look at all this and wonder: wouldn't it make sense for a method DenseVectorField.buildKnnVectorsFormat() to exist?  Or just a getter if it's built in the field type's init()... which would also mean no need to have each of those fields (e.g. no bits, ...) with their getters either.



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.get(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+        args.remove(BITS);
+
+        this.compress = ofNullable(args.get(COMPRESS))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(COMPRESS);
+
+        boolean useDynamicConfidenceInterval = ofNullable(args.get(DYNAMIC_CONFIDENCE_INTERVAL))
+                .map(Boolean::parseBoolean)
+                .orElse(false);
+        args.remove(DYNAMIC_CONFIDENCE_INTERVAL);
+
+        if (useDynamicConfidenceInterval) {
+            this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+        }
+
+        this.confidenceInterval = ofNullable(args.get(CONFIDENCE_INTERVAL))

Review Comment:
   this overwrites the confidenceInterval set when useDynamicConfidenceInterval==true above



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+
+import java.util.Map;
+
+import static java.util.Optional.ofNullable;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+    public static final String BITS = "bits"; //
+    public static final String CONFIDENCE_INTERVAL = "confidenceInterval";
+    public static final String DYNAMIC_CONFIDENCE_INTERVAL = "dynamicConfidenceInterval";
+    public static final String COMPRESS = "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+    private static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+    private static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+    /**
+     * Number of bits to use for storage
+     * Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec spec
+     */
+    private int bits;
+
+    /**
+     * Confidence interval to use for scalar quantization
+     * Default is calculated as `1-1/(vector_dimensions + 1)`
+     */
+    private Float confidenceInterval;
+
+    /**
+     * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50% reduction in memory usage
+     * (comes at the cost of some decode speed penalty)
+     */
+    private boolean compress;
+
+    public ScalarQuantizedDenseVectorField(int dimension,
+                                           VectorSimilarityFunction similarityFunction,
+                                           VectorEncoding vectorEncoding,
+                                           int bits,
+                                           Float confidenceInterval,
+                                           boolean compress) {
+        super(dimension, similarityFunction, vectorEncoding);
+        this.bits = bits;
+        this.confidenceInterval = confidenceInterval;
+        this.compress = compress;
+    }
+
+    @Override
+    public void init(IndexSchema schema, Map<String, String> args) {
+        super.init(schema, args);
+
+        this.bits = ofNullable(args.get(BITS))
+                .map(Integer::parseInt)
+                .orElse(DEFAULT_BITS);
+        args.remove(BITS);

Review Comment:
   instead of "args.get" a few lines above, you should use this "remove", as it returns it.  Ditto for other args below.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2252640594


##########
solr/solr-ref-guide/modules/query-guide/pages/dense-vector-search.adoc:
##########
@@ -240,6 +240,66 @@ client.add(Arrays.asList(d1, d2));
 ====
 ======
 
+=== ScalarQuantizedDenseVectorField
+Because dense vectors can have a costly storage footprint, it may be worthwhile to use a technique called "quantization"
+to reduce the stored representation size at the cost of some precision.
+
+This dense vector type uses a conversion that projects a 32 bit float precision feature down to an 8 bit int (or smaller)
+by linearly mapping the float range down to evenly sized "buckets" of values that fit into an int. A more detailed explanation
+can be found in this https://www.elastic.co/search-labs/blog/scalar-quantization-101[blog post].
+
+As a specific type of DenseVectorField, this field type supports all the same configurable properties outlined above as well
+as some additional ones.
+
+Here is how a ScalarQuantizedDenseVectorField can be defined in the schema:
+
+[source,xml]
+<fieldType name="scalar_quantized_vector" class="solr.ScalarQuantizedDenseVectorField" vectorDimension="4" similarityFunction="cosine"/>
+<field name="vector" type="scalar_quantized_vector" indexed="true" stored="true"/>
+
+`bits`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `7`
+|===
++
+The number of bits to use for each quantized dimension value
++
+Accepted values: 4 (half byte) or 7 (unsigned byte).
+
+`confidenceInterval`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `dimension-scaled`
+|===
++
+Statistically, outlier values are rarely meaningfully relevant to searches, so to increase the size of each bucket for
+quantization (and therefore information gain) we can scale the quantization intervals to the middle n % of values and place the remaining
+outliers in the outermost intervals.
++
+For example: 0.9 means scale interval sizes to the middle 90% of values
++
+If this param is omitted a default is used; scaled to the number of dimensions according to `1-1/(vector_dimensions + 1)`
++
+If `0` is provided, confidence intervals will be dynamically adjusted (at segment merge time) optimized by sampling values
++
+Accepted values: `FLOAT32`  (within 0.9 and 1.0) or 0 for dynamically adjusted confidence interval

Review Comment:
   This accepted values section was copied and I forgot to update. For this param, it's simply a bool



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2276775788


##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  /**
+   * Number of bits to use for storage Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec
+   * spec
+   */
+  private int bits;
+
+  /**
+   * Confidence interval to use for scalar quantization Default is calculated as
+   * `1-1/(vector_dimensions + 1)`
+   */
+  private Float confidenceInterval;
+
+  /**
+   * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50%
+   * reduction in memory usage (comes at the cost of some decode speed penalty)
+   */
+  private boolean compress;
+
+  public ScalarQuantizedDenseVectorField() {
+    super();
+  }
+
+  public ScalarQuantizedDenseVectorField(
+      int dimension,
+      VectorSimilarityFunction similarityFunction,
+      VectorEncoding vectorEncoding,
+      int bits,
+      Float confidenceInterval,
+      boolean compress) {
+    super(dimension, similarityFunction, vectorEncoding);
+    this.bits = bits;
+    this.confidenceInterval = confidenceInterval;
+    this.compress = compress;
+  }
+
+  @Override
+  public void init(IndexSchema schema, Map<String, String> args) {
+    this.bits = ofNullable(args.remove(BITS_PARAM)).map(Integer::parseInt).orElse(DEFAULT_BITS);
+
+    this.compress =
+        ofNullable(args.remove(COMPRESS_PARAM)).map(Boolean::parseBoolean).orElse(false);
+
+    this.confidenceInterval =
+        ofNullable(args.remove(CONFIDENCE_INTERVAL_PARAM))
+            .map(Float::parseFloat)
+            .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+    if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL_PARAM))
+        .map(Boolean::parseBoolean)
+        .orElse(false)) {
+      this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+    }
+
+    super.init(schema, args);
+  }
+
+  @Override
+  public KnnVectorsFormat buildKnnVectorsFormat() {
+    return new Lucene99HnswScalarQuantizedVectorsFormat(
+        getHnswMaxConn(),
+        getHnswBeamWidth(),
+        DEFAULT_NUM_MERGE_WORKER,
+        getBits(),
+        useCompression(),
+        getConfidenceInterval(),
+        null);
+  }
+
+  @Override
+  public void checkSchemaField(final SchemaField field) throws SolrException {
+    super.checkSchemaField(field);
+
+    try {
+      // format does not expose any validation, however by constructing
+      // we will run lucene level argument validation
+      buildKnnVectorsFormat();
+    } catch (Exception e) {

Review Comment:
   Isn't there any more specific exception to catch?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-2964368023

   I still need to add tests and update documentation


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2244949751


##########
solr/solr-ref-guide/modules/query-guide/pages/dense-vector-search.adoc:
##########
@@ -240,6 +240,66 @@ client.add(Arrays.asList(d1, d2));
 ====
 ======
 
+=== ScalarQuantizedDenseVectorField
+Because dense vectors can have a costly storage footprint, it may be worthwhile to use a technique called "quantization"
+to reduce the stored representation size at the cost of some precision.
+
+This dense vector type uses a conversion that projects a 32 bit float precision feature down to an 8 bit int (or smaller)
+by linearly mapping the float range down to evenly sized "buckets" of values that fit into an int. A more detailed explanation
+can be found in this https://www.elastic.co/search-labs/blog/scalar-quantization-101[blog post].

Review Comment:
   I would encourage linking a resource that's not Elastic. I  don't think we want Elasticsearch reference in the Solr documentation, it would feel weird



##########
solr/solr-ref-guide/modules/query-guide/pages/dense-vector-search.adoc:
##########
@@ -240,6 +240,66 @@ client.add(Arrays.asList(d1, d2));
 ====
 ======
 
+=== ScalarQuantizedDenseVectorField
+Because dense vectors can have a costly storage footprint, it may be worthwhile to use a technique called "quantization"

Review Comment:
   I would specify that's not only strictly storage (because actually the storage footprint on disk increases with quantisation).
   
   I would stress memory/latency benefits above all.



##########
solr/solr-ref-guide/modules/query-guide/pages/dense-vector-search.adoc:
##########
@@ -240,6 +240,66 @@ client.add(Arrays.asList(d1, d2));
 ====
 ======
 
+=== ScalarQuantizedDenseVectorField
+Because dense vectors can have a costly storage footprint, it may be worthwhile to use a technique called "quantization"
+to reduce the stored representation size at the cost of some precision.
+
+This dense vector type uses a conversion that projects a 32 bit float precision feature down to an 8 bit int (or smaller)
+by linearly mapping the float range down to evenly sized "buckets" of values that fit into an int. A more detailed explanation
+can be found in this https://www.elastic.co/search-labs/blog/scalar-quantization-101[blog post].
+
+As a specific type of DenseVectorField, this field type supports all the same configurable properties outlined above as well
+as some additional ones.
+
+Here is how a ScalarQuantizedDenseVectorField can be defined in the schema:
+
+[source,xml]
+<fieldType name="scalar_quantized_vector" class="solr.ScalarQuantizedDenseVectorField" vectorDimension="4" similarityFunction="cosine"/>
+<field name="vector" type="scalar_quantized_vector" indexed="true" stored="true"/>
+
+`bits`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `7`
+|===
++
+The number of bits to use for each quantized dimension value
++
+Accepted values: 4 (half byte) or 7 (unsigned byte).
+
+`confidenceInterval`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `dimension-scaled`
+|===
++
+Statistically, outlier values are rarely meaningfully relevant to searches, so to increase the size of each bucket for
+quantization (and therefore information gain) we can scale the quantization intervals to the middle n % of values and place the remaining
+outliers in the outermost intervals.
++
+For example: 0.9 means scale interval sizes to the middle 90% of values
++
+If this param is omitted a default is used; scaled to the number of dimensions according to `1-1/(vector_dimensions + 1)`
++
+If `0` is provided, confidence intervals will be dynamically adjusted (at segment merge time) optimized by sampling values
++
+Accepted values: `FLOAT32`  (within 0.9 and 1.0) or 0 for dynamically adjusted confidence interval
+
+`compress`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `false`
+|===
++
+If set to true, this will further pack multiple dimension values within a one byte alignment. This further decreases the storage size by 50% at some decode penalty.

Review Comment:
   is it related to the quantised vector storage (both memory and disk)?
   or only memory?
   Maybe we should clarify that on disk we still store also the full vector



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  // lucene does not expose these so we are duplicating them here
+  static final Float MINIMUM_CONFIDENCE_INTERVAL = 0.9f;
+  static final Float MAXIMUM_CONFIDENCE_INTERVAL = 1f;
+
+  /**
+   * Number of bits to use for storage Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec
+   * spec
+   */
+  private int bits;
+
+  /**
+   * Confidence interval to use for scalar quantization Default is calculated as
+   * `1-1/(vector_dimensions + 1)`
+   */
+  private Float confidenceInterval;
+
+  /**
+   * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50%
+   * reduction in memory usage (comes at the cost of some decode speed penalty)
+   */
+  private boolean compress;
+
+  public ScalarQuantizedDenseVectorField() {
+    super();
+  }
+
+  public ScalarQuantizedDenseVectorField(
+      int dimension,
+      VectorSimilarityFunction similarityFunction,
+      VectorEncoding vectorEncoding,
+      int bits,
+      Float confidenceInterval,
+      boolean compress) {
+    super(dimension, similarityFunction, vectorEncoding);
+    this.bits = bits;
+    this.confidenceInterval = confidenceInterval;
+    this.compress = compress;
+  }
+
+  @Override
+  public void init(IndexSchema schema, Map<String, String> args) {
+    this.bits = ofNullable(args.remove(BITS_PARAM)).map(Integer::parseInt).orElse(DEFAULT_BITS);
+
+    this.compress =
+        ofNullable(args.remove(COMPRESS_PARAM)).map(Boolean::parseBoolean).orElse(false);
+
+    this.confidenceInterval =
+        ofNullable(args.remove(CONFIDENCE_INTERVAL_PARAM))
+            .map(Float::parseFloat)
+            .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+    if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL_PARAM))
+        .map(Boolean::parseBoolean)
+        .orElse(false)) {
+      this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+    }
+
+    super.init(schema, args);
+  }
+
+  @Override
+  public KnnVectorsFormat buildKnnVectorsFormat() {
+    return new Lucene99HnswScalarQuantizedVectorsFormat(
+        getHnswMaxConn(),
+        getHnswBeamWidth(),
+        DEFAULT_NUM_MERGE_WORKER,
+        getBits(),
+        useCompression(),
+        getConfidenceInterval(),
+        null);
+  }
+
+  @Override
+  public void checkSchemaField(final SchemaField field) throws SolrException {
+    super.checkSchemaField(field);
+
+    if (confidenceInterval != null
+        && confidenceInterval != Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL
+        && (confidenceInterval < MINIMUM_CONFIDENCE_INTERVAL
+            || confidenceInterval > MAXIMUM_CONFIDENCE_INTERVAL)) {
+      throw new SolrException(
+          SolrException.ErrorCode.SERVER_ERROR,
+          getClass().getSimpleName()
+              + " fields must have non-dynamic confidence interval between 0.9 and 1.0 "
+              + field.getName());
+    }
+    if (getBits() != 4 && getBits() != 7) {

Review Comment:
   can't we rely on Lucene checks that throw the "if (bits < 1 || bits > 8 || (ALLOWED_BITS & (1 << bits)) == 0) {
         throw new IllegalArgumentException("bits must be one of: 4, 7; bits=" + bits);
       }"



##########
solr/core/src/test-files/solr/collection1/conf/schema-densevector.xml:
##########
@@ -25,7 +25,7 @@
   <fieldType name="high_dimensional_float_knn_vector" class="solr.DenseVectorField" vectorDimension="2048" similarityFunction="cosine" vectorEncoding="FLOAT32"/>
   <fieldType name="high_dimensional_byte_knn_vector" class="solr.DenseVectorField" vectorDimension="2048" similarityFunction="cosine" vectorEncoding="BYTE"/>
   <fieldType name="plong" class="solr.LongPointField" useDocValuesAsStored="false"/>
-  
+

Review Comment:
   I guess this is unwanted



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  // lucene does not expose these so we are duplicating them here
+  static final Float MINIMUM_CONFIDENCE_INTERVAL = 0.9f;

Review Comment:
   I'm not sure we need this here, looking at Lucene code, in case we go off the values we get an "llegalArgumentException(
             "confidenceInterval must be between "
                 + MINIMUM_CONFIDENCE_INTERVAL
                 + " and "
                 + MAXIMUM_CONFIDENCE_INTERVAL
                 + " or 0"
                 + "; confidenceInterval="
                 + confidenceInterval);"
                 
                 Can't we catch this exception and handle it rather than duplicating the constants?



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  // lucene does not expose these so we are duplicating them here
+  static final Float MINIMUM_CONFIDENCE_INTERVAL = 0.9f;
+  static final Float MAXIMUM_CONFIDENCE_INTERVAL = 1f;
+
+  /**
+   * Number of bits to use for storage Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec
+   * spec
+   */
+  private int bits;
+
+  /**
+   * Confidence interval to use for scalar quantization Default is calculated as
+   * `1-1/(vector_dimensions + 1)`
+   */
+  private Float confidenceInterval;
+
+  /**
+   * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50%
+   * reduction in memory usage (comes at the cost of some decode speed penalty)
+   */
+  private boolean compress;
+
+  public ScalarQuantizedDenseVectorField() {
+    super();
+  }
+
+  public ScalarQuantizedDenseVectorField(
+      int dimension,
+      VectorSimilarityFunction similarityFunction,
+      VectorEncoding vectorEncoding,
+      int bits,
+      Float confidenceInterval,
+      boolean compress) {
+    super(dimension, similarityFunction, vectorEncoding);
+    this.bits = bits;
+    this.confidenceInterval = confidenceInterval;
+    this.compress = compress;
+  }
+
+  @Override
+  public void init(IndexSchema schema, Map<String, String> args) {
+    this.bits = ofNullable(args.remove(BITS_PARAM)).map(Integer::parseInt).orElse(DEFAULT_BITS);
+
+    this.compress =
+        ofNullable(args.remove(COMPRESS_PARAM)).map(Boolean::parseBoolean).orElse(false);
+
+    this.confidenceInterval =
+        ofNullable(args.remove(CONFIDENCE_INTERVAL_PARAM))
+            .map(Float::parseFloat)
+            .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+    if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL_PARAM))
+        .map(Boolean::parseBoolean)
+        .orElse(false)) {
+      this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+    }
+
+    super.init(schema, args);
+  }
+
+  @Override
+  public KnnVectorsFormat buildKnnVectorsFormat() {
+    return new Lucene99HnswScalarQuantizedVectorsFormat(
+        getHnswMaxConn(),
+        getHnswBeamWidth(),
+        DEFAULT_NUM_MERGE_WORKER,
+        getBits(),
+        useCompression(),
+        getConfidenceInterval(),
+        null);
+  }
+
+  @Override
+  public void checkSchemaField(final SchemaField field) throws SolrException {
+    super.checkSchemaField(field);
+
+    if (confidenceInterval != null
+        && confidenceInterval != Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL
+        && (confidenceInterval < MINIMUM_CONFIDENCE_INTERVAL
+            || confidenceInterval > MAXIMUM_CONFIDENCE_INTERVAL)) {
+      throw new SolrException(
+          SolrException.ErrorCode.SERVER_ERROR,
+          getClass().getSimpleName()
+              + " fields must have non-dynamic confidence interval between 0.9 and 1.0 "
+              + field.getName());

Review Comment:
   as commented above, I'm wondering if we can use the Lucene exceptions here



##########
solr/core/src/java/org/apache/solr/schema/ScalarQuantizedDenseVectorField.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.schema;
+
+import static java.util.Optional.ofNullable;
+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;
+
+import java.util.Map;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.solr.common.SolrException;
+
+public class ScalarQuantizedDenseVectorField extends DenseVectorField {
+  public static final String BITS_PARAM = "bits"; //
+  public static final String CONFIDENCE_INTERVAL_PARAM = "confidenceInterval";
+  public static final String DYNAMIC_CONFIDENCE_INTERVAL_PARAM = "dynamicConfidenceInterval";
+  public static final String COMPRESS_PARAM =
+      "compress"; // can only be enabled when bits = 4 per Lucene codec spec
+
+  static final int DEFAULT_BITS = 7; // use signed byte as default when unspecified
+  static final Float DEFAULT_CONFIDENCE_INTERVAL = null; // use dimension scaled confidence interval
+
+  // lucene does not expose these so we are duplicating them here
+  static final Float MINIMUM_CONFIDENCE_INTERVAL = 0.9f;
+  static final Float MAXIMUM_CONFIDENCE_INTERVAL = 1f;
+
+  /**
+   * Number of bits to use for storage Must be 4 (half-byte) or 7 (signed-byte) per Lucene codec
+   * spec
+   */
+  private int bits;
+
+  /**
+   * Confidence interval to use for scalar quantization Default is calculated as
+   * `1-1/(vector_dimensions + 1)`
+   */
+  private Float confidenceInterval;
+
+  /**
+   * When enabled, in conjunction with 4 bit size, will pair values into single bytes for 50%
+   * reduction in memory usage (comes at the cost of some decode speed penalty)
+   */
+  private boolean compress;
+
+  public ScalarQuantizedDenseVectorField() {
+    super();
+  }
+
+  public ScalarQuantizedDenseVectorField(
+      int dimension,
+      VectorSimilarityFunction similarityFunction,
+      VectorEncoding vectorEncoding,
+      int bits,
+      Float confidenceInterval,
+      boolean compress) {
+    super(dimension, similarityFunction, vectorEncoding);
+    this.bits = bits;
+    this.confidenceInterval = confidenceInterval;
+    this.compress = compress;
+  }
+
+  @Override
+  public void init(IndexSchema schema, Map<String, String> args) {
+    this.bits = ofNullable(args.remove(BITS_PARAM)).map(Integer::parseInt).orElse(DEFAULT_BITS);
+
+    this.compress =
+        ofNullable(args.remove(COMPRESS_PARAM)).map(Boolean::parseBoolean).orElse(false);
+
+    this.confidenceInterval =
+        ofNullable(args.remove(CONFIDENCE_INTERVAL_PARAM))
+            .map(Float::parseFloat)
+            .orElse(DEFAULT_CONFIDENCE_INTERVAL);
+
+    if (ofNullable(args.remove(DYNAMIC_CONFIDENCE_INTERVAL_PARAM))
+        .map(Boolean::parseBoolean)
+        .orElse(false)) {
+      this.confidenceInterval = Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL;
+    }
+
+    super.init(schema, args);
+  }
+
+  @Override
+  public KnnVectorsFormat buildKnnVectorsFormat() {
+    return new Lucene99HnswScalarQuantizedVectorsFormat(
+        getHnswMaxConn(),
+        getHnswBeamWidth(),
+        DEFAULT_NUM_MERGE_WORKER,
+        getBits(),
+        useCompression(),
+        getConfidenceInterval(),
+        null);
+  }
+
+  @Override
+  public void checkSchemaField(final SchemaField field) throws SolrException {
+    super.checkSchemaField(field);
+
+    if (confidenceInterval != null
+        && confidenceInterval != Lucene99ScalarQuantizedVectorsFormat.DYNAMIC_CONFIDENCE_INTERVAL
+        && (confidenceInterval < MINIMUM_CONFIDENCE_INTERVAL
+            || confidenceInterval > MAXIMUM_CONFIDENCE_INTERVAL)) {
+      throw new SolrException(
+          SolrException.ErrorCode.SERVER_ERROR,
+          getClass().getSimpleName()
+              + " fields must have non-dynamic confidence interval between 0.9 and 1.0 "
+              + field.getName());
+    }
+    if (getBits() != 4 && getBits() != 7) {
+      throw new SolrException(
+          SolrException.ErrorCode.SERVER_ERROR,
+          getClass().getSimpleName()
+              + " fields must have bit size of 4 (half-byte) or 7 (signed-byte) "
+              + field.getName());
+    }
+
+    if (useCompression() && getBits() != 4) {

Review Comment:
   Can't we rely on "if (bits > 4 && compress) {
         // compress=true otherwise silently does nothing when bits=7?
         throw new IllegalArgumentException("compress=true only applies when bits=4");
       }" Lucene side?
       
       



##########
solr/core/src/test-files/solr/collection1/conf/schema-densevector-quantized.xml:
##########
@@ -0,0 +1,86 @@
+<?xml version="1.0" ?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements.  See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License.  You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Test schema file for DenseVectorField types -->
+
+<schema name="schema-densevector-quantized" version="1.0">
+  <fieldType name="string" class="solr.StrField" multiValued="true"/>  
+  <fieldType name="knn_vector" class="solr.DenseVectorField" vectorDimension="4" similarityFunction="cosine" />
+  <fieldType name="knn_vector_byte_encoding" class="solr.DenseVectorField" vectorDimension="4" similarityFunction="cosine" vectorEncoding="BYTE"/>
+  <fieldType name="high_dimensional_float_knn_vector" class="solr.DenseVectorField" vectorDimension="2048" similarityFunction="cosine" vectorEncoding="FLOAT32"/>
+  <fieldType name="high_dimensional_byte_knn_vector" class="solr.DenseVectorField" vectorDimension="2048" similarityFunction="cosine" vectorEncoding="BYTE"/>
+  <fieldType name="plong" class="solr.LongPointField" useDocValuesAsStored="false"/>
+
+  <!-- Scalar Quantized vectors -->
+  <fieldType name="knn_vector_scalar_quantized_default" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+  />
+  <fieldType name="knn_vector_scalar_quantized_half_byte" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             bits="4"/>
+  <fieldType name="knn_vector_scalar_quantized_compressed" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             bits="4"
+            compress="true"/>
+  <fieldType name="knn_vector_scalar_quantized_confidence_interval" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             confidenceInterval="0.91"/>
+  <fieldType name="knn_vector_scalar_quantized_confidence_dynamic" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             dynamicConfidenceInterval="true"/>
+
+
+  <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="false"/>
+  <field name="vector" type="knn_vector" indexed="true" stored="true"/>
+  <field name="vector2" type="knn_vector" indexed="true" stored="true"/>
+  <field name="vector_byte_encoding" type="knn_vector_byte_encoding" indexed="true" stored="true" />
+  <field name="2048_byte_vector" type="high_dimensional_byte_knn_vector" indexed="true" stored="true" />
+  <field name="2048_float_vector" type="high_dimensional_float_knn_vector" indexed="true" stored="true" />
+
+  <field name="v_scalar_default" type="knn_vector_scalar_quantized_default" indexed="true" stored="true" />
+  <field name="v_scalar_half_byte" type="knn_vector_scalar_quantized_half_byte" indexed="true" stored="true" />
+  <field name="v_scalar_compressed" type="knn_vector_scalar_quantized_compressed" indexed="true" stored="true" />
+  <field name="v_scalar_confidence" type="knn_vector_scalar_quantized_confidence_interval" indexed="true" stored="true" />
+  <field name="v_scalar_dynamic" type="knn_vector_scalar_quantized_confidence_dynamic" indexed="true" stored="true" />
+
+  <field name="string_field" type="string" indexed="true" stored="true" multiValued="false" required="false"/>
+
+  <field name="_version_" type="plong" indexed="true" stored="true" multiValued="false" />
+  <field name="_text_" type="text_general" indexed="true" stored="false" multiValued="true"/>
+  <copyField source="*" dest="_text_"/>
+  <fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true">
+    <analyzer type="index">
+      <tokenizer class="solr.StandardTokenizerFactory"/>

Review Comment:
   can't we use one single schema file, where you add the different fields and field types with the ad hoc incorrect parameters?



##########
solr/solr-ref-guide/modules/query-guide/pages/dense-vector-search.adoc:
##########
@@ -240,6 +240,66 @@ client.add(Arrays.asList(d1, d2));
 ====
 ======
 
+=== ScalarQuantizedDenseVectorField
+Because dense vectors can have a costly storage footprint, it may be worthwhile to use a technique called "quantization"
+to reduce the stored representation size at the cost of some precision.
+
+This dense vector type uses a conversion that projects a 32 bit float precision feature down to an 8 bit int (or smaller)
+by linearly mapping the float range down to evenly sized "buckets" of values that fit into an int. A more detailed explanation
+can be found in this https://www.elastic.co/search-labs/blog/scalar-quantization-101[blog post].
+
+As a specific type of DenseVectorField, this field type supports all the same configurable properties outlined above as well
+as some additional ones.
+
+Here is how a ScalarQuantizedDenseVectorField can be defined in the schema:
+
+[source,xml]
+<fieldType name="scalar_quantized_vector" class="solr.ScalarQuantizedDenseVectorField" vectorDimension="4" similarityFunction="cosine"/>
+<field name="vector" type="scalar_quantized_vector" indexed="true" stored="true"/>
+
+`bits`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `7`
+|===
++
+The number of bits to use for each quantized dimension value
++
+Accepted values: 4 (half byte) or 7 (unsigned byte).
+
+`confidenceInterval`::
++
+[%autowidth,frame=none]
+|===
+s|Optional |Default: `dimension-scaled`
+|===
++
+Statistically, outlier values are rarely meaningfully relevant to searches, so to increase the size of each bucket for
+quantization (and therefore information gain) we can scale the quantization intervals to the middle n % of values and place the remaining
+outliers in the outermost intervals.
++
+For example: 0.9 means scale interval sizes to the middle 90% of values
++
+If this param is omitted a default is used; scaled to the number of dimensions according to `1-1/(vector_dimensions + 1)`
++
+If `0` is provided, confidence intervals will be dynamically adjusted (at segment merge time) optimized by sampling values
++
+Accepted values: `FLOAT32`  (within 0.9 and 1.0) or 0 for dynamically adjusted confidence interval

Review Comment:
   I'm not sure this is clear enough for someone not familiar with the topic.
   Can I suggest involving some additional readers here?
   @ilariapet , @aruggero , @liangkaiwen  can you involve some of your colleagues?
   We may need to rephrase a bit this chapter
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3249550133

   I fixed the tidy problem, but the tests (the ones expected to throw exceptions) are still failing.
   I gave it a very quick try, with debug, but it doesn't look obvious to me, as I'm not familiar with that type of test with an expected error string, so in case you can't manage to fix them, I'll give it a try, spending a bit more time. Let me know!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti merged PR #3385:
URL: https://github.com/apache/solr/pull/3385


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3245963319

   @alessandrobenedetti updated + fixed tests


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2162356233


##########
solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java:
##########
@@ -126,16 +131,41 @@ public DocValuesFormat getDocValuesFormatForField(String field) {
           public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
             final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
             FieldType fieldType = (schemaField == null ? null : schemaField.getType());
-            if (fieldType instanceof DenseVectorField vectorType) {
+            KnnVectorsFormat delegate;

Review Comment:
   Much better.  Did you consider init() also creating the codec to thus avoid the need corresponding fields, getters, setters?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on code in PR #3385:
URL: https://github.com/apache/solr/pull/3385#discussion_r2252665891


##########
solr/core/src/test-files/solr/collection1/conf/schema-densevector-quantized.xml:
##########
@@ -0,0 +1,86 @@
+<?xml version="1.0" ?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements.  See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License.  You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Test schema file for DenseVectorField types -->
+
+<schema name="schema-densevector-quantized" version="1.0">
+  <fieldType name="string" class="solr.StrField" multiValued="true"/>  
+  <fieldType name="knn_vector" class="solr.DenseVectorField" vectorDimension="4" similarityFunction="cosine" />
+  <fieldType name="knn_vector_byte_encoding" class="solr.DenseVectorField" vectorDimension="4" similarityFunction="cosine" vectorEncoding="BYTE"/>
+  <fieldType name="high_dimensional_float_knn_vector" class="solr.DenseVectorField" vectorDimension="2048" similarityFunction="cosine" vectorEncoding="FLOAT32"/>
+  <fieldType name="high_dimensional_byte_knn_vector" class="solr.DenseVectorField" vectorDimension="2048" similarityFunction="cosine" vectorEncoding="BYTE"/>
+  <fieldType name="plong" class="solr.LongPointField" useDocValuesAsStored="false"/>
+
+  <!-- Scalar Quantized vectors -->
+  <fieldType name="knn_vector_scalar_quantized_default" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+  />
+  <fieldType name="knn_vector_scalar_quantized_half_byte" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             bits="4"/>
+  <fieldType name="knn_vector_scalar_quantized_compressed" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             bits="4"
+            compress="true"/>
+  <fieldType name="knn_vector_scalar_quantized_confidence_interval" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             confidenceInterval="0.91"/>
+  <fieldType name="knn_vector_scalar_quantized_confidence_dynamic" class="solr.ScalarQuantizedDenseVectorField"
+             vectorDimension="4"
+             similarityFunction="cosine"
+             dynamicConfidenceInterval="true"/>
+
+
+  <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="false"/>
+  <field name="vector" type="knn_vector" indexed="true" stored="true"/>
+  <field name="vector2" type="knn_vector" indexed="true" stored="true"/>
+  <field name="vector_byte_encoding" type="knn_vector_byte_encoding" indexed="true" stored="true" />
+  <field name="2048_byte_vector" type="high_dimensional_byte_knn_vector" indexed="true" stored="true" />
+  <field name="2048_float_vector" type="high_dimensional_float_knn_vector" indexed="true" stored="true" />
+
+  <field name="v_scalar_default" type="knn_vector_scalar_quantized_default" indexed="true" stored="true" />
+  <field name="v_scalar_half_byte" type="knn_vector_scalar_quantized_half_byte" indexed="true" stored="true" />
+  <field name="v_scalar_compressed" type="knn_vector_scalar_quantized_compressed" indexed="true" stored="true" />
+  <field name="v_scalar_confidence" type="knn_vector_scalar_quantized_confidence_interval" indexed="true" stored="true" />
+  <field name="v_scalar_dynamic" type="knn_vector_scalar_quantized_confidence_dynamic" indexed="true" stored="true" />
+
+  <field name="string_field" type="string" indexed="true" stored="true" multiValued="false" required="false"/>
+
+  <field name="_version_" type="plong" indexed="true" stored="true" multiValued="false" />
+  <field name="_text_" type="text_general" indexed="true" stored="false" multiValued="true"/>
+  <copyField source="*" dest="_text_"/>
+  <fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true">
+    <analyzer type="index">
+      <tokenizer class="solr.StandardTokenizerFactory"/>

Review Comment:
   I can try it. Would that not just always error on the first invalid field though?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "liangkaiwen (via GitHub)" <gi...@apache.org>.
liangkaiwen commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3250303573

   Huh, I thought it had passed after I committed my last changes but I guess not. No problem, I will handle it


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "alessandrobenedetti (via GitHub)" <gi...@apache.org>.
alessandrobenedetti commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3243199677

   > Just a quick comment: next time please don't rebase a PR; simply merge main into it. I've found rebasing PRs to be a bad practice as it resets the GitHub review state, making it impossible to be certain what incremental changes happened (if any).
   
   Wasn't it mandatory to comply with Crave checks? That's the only reason I (and my colleagues at least) are doing it, has anything changed?
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


Re: [PR] SOLR-17780: Add support for scalar quantized dense vectors [solr]

Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on PR #3385:
URL: https://github.com/apache/solr/pull/3385#issuecomment-3243516726

   I don't recall Crave being confused by a merge from "main".  I do recall once in a while (rare-ish), GitHub PR would show changes from the merge that it shouldn't.  


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org