index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ORCChunkedReader.java
/* * * Copyright (c) 2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Provide an interface for reading an ORC file in an iterative manner. */ public class ORCChunkedReader implements AutoCloseable { static { NativeDepsLoader.loadNativeDeps(); } /** * Construct the reader instance from read limits, output row granularity, * and a file already loaded in a memory buffer. * * @param chunkReadLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param passReadLimit Limit on the amount of memory used by the chunked reader, * or 0 if there is no limit. * @param opts The options for ORC reading. * @param buffer Raw ORC file content. * @param offset The starting offset into buffer. * @param len The number of bytes to parse the given buffer. */ public ORCChunkedReader(long chunkReadLimit, long passReadLimit, ORCOptions opts, HostMemoryBuffer buffer, long offset, long len) { handle = createReader(chunkReadLimit, passReadLimit, opts.getIncludeColumnNames(), buffer.getAddress() + offset, len, opts.usingNumPyTypes(), opts.timeUnit().typeId.getNativeId(), opts.getDecimal128Columns()); if (handle == 0) { throw new IllegalStateException("Cannot create native chunked ORC reader object."); } } /** * Construct a chunked ORC reader instance, similar to * {@link ORCChunkedReader#ORCChunkedReader(long, long, ORCOptions, HostMemoryBuffer, long, long)}, * with an additional parameter to control the granularity of the output table. * When reading a chunk table, with respect to the given size limits, a subset of stripes may * be loaded, decompressed and decoded into a large intermediate table. The reader will then * subdivide that table into smaller tables for final output using * {@code outputRowSizingGranularity} as the subdivision step. If the chunked reader is * constructed without this parameter, the default value of 10k rows will be used. * * @param outputRowSizingGranularity The change step in number of rows in the output table. * @see ORCChunkedReader#ORCChunkedReader(long, long, ORCOptions, HostMemoryBuffer, long, long) */ public ORCChunkedReader(long chunkReadLimit, long passReadLimit, long outputRowSizingGranularity, ORCOptions opts, HostMemoryBuffer buffer, long offset, long len) { handle = createReaderWithOutputGranularity(chunkReadLimit, passReadLimit, outputRowSizingGranularity, opts.getIncludeColumnNames(), buffer.getAddress() + offset, len, opts.usingNumPyTypes(), opts.timeUnit().typeId.getNativeId(), opts.getDecimal128Columns()); if (handle == 0) { throw new IllegalStateException("Cannot create native chunked ORC reader object."); } } /** * Check if the given file has anything left to read. * * @return A boolean value indicating if there is more data to read from file. */ public boolean hasNext() { if (handle == 0) { throw new IllegalStateException("Native chunked ORC reader object may have been closed."); } if (firstCall) { // This function needs to return true at least once, so an empty table // (but having empty columns instead of no column) can be returned by readChunk() // if the input file has no row. firstCall = false; return true; } return hasNext(handle); } /** * Read a chunk of rows in the given ORC file such that the returning data has total size * does not exceed the given read limit. If the given file has no data, or all data has been read * before by previous calls to this function, a null Table will be returned. * * @return A table of new rows reading from the given file. */ public Table readChunk() { if (handle == 0) { throw new IllegalStateException("Native chunked ORC reader object may have been closed."); } long[] columnPtrs = readChunk(handle); return columnPtrs != null ? new Table(columnPtrs) : null; } @Override public void close() { if (handle != 0) { close(handle); handle = 0; } } /** * Auxiliary variable to help {@link #hasNext()} returning true at least once. */ private boolean firstCall = true; /** * Handle for memory address of the native ORC chunked reader class. */ private long handle; /** * Create a native chunked ORC reader object on heap and return its memory address. * * @param chunkReadLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param passReadLimit Limit on the amount of memory used by the chunked reader, * or 0 if there is no limit. * @param filterColumnNames Name of the columns to read, or an empty array if we want to read all. * @param bufferAddrs The address of a buffer to read from, or 0 if we are not using that buffer. * @param length The length of the buffer to read from. * @param usingNumPyTypes Whether the parser should implicitly promote TIMESTAMP * columns to TIMESTAMP_MILLISECONDS for compatibility with NumPy. * @param timeUnit return type of TimeStamp in units * @param decimal128Columns name of the columns which are read as Decimal128 rather than Decimal64 */ private static native long createReader(long chunkReadLimit, long passReadLimit, String[] filterColumnNames, long bufferAddrs, long length, boolean usingNumPyTypes, int timeUnit, String[] decimal128Columns); /** * Create a native chunked ORC reader object, similar to * {@link ORCChunkedReader#createReader(long, long, String[], long, long, boolean, int, String[])}, * with an additional parameter to control the granularity of the output table. * * @param outputRowSizingGranularity The change step in number of rows in the output table. * @see ORCChunkedReader#createReader(long, long, String[], long, long, boolean, int, String[]) */ private static native long createReaderWithOutputGranularity( long chunkReadLimit, long passReadLimit, long outputRowSizingGranularity, String[] filterColumnNames, long bufferAddrs, long length, boolean usingNumPyTypes, int timeUnit, String[] decimal128Columns); private static native boolean hasNext(long handle); private static native long[] readChunk(long handle); private static native void close(long handle); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ORCOptions.java
/* * * Copyright (c) 2019-2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Options for reading a ORC file */ public class ORCOptions extends ColumnFilterOptions { public static ORCOptions DEFAULT = new ORCOptions(new Builder()); private final boolean useNumPyTypes; private final DType unit; private final String[] decimal128Columns; private ORCOptions(Builder builder) { super(builder); decimal128Columns = builder.decimal128Columns.toArray(new String[0]); useNumPyTypes = builder.useNumPyTypes; unit = builder.unit; } boolean usingNumPyTypes() { return useNumPyTypes; } DType timeUnit() { return unit; } String[] getDecimal128Columns() { return decimal128Columns; } public static Builder builder() { return new Builder(); } public static class Builder extends ColumnFilterOptions.Builder<Builder> { private boolean useNumPyTypes = true; private DType unit = DType.EMPTY; final List<String> decimal128Columns = new ArrayList<>(); /** * Specify whether the parser should implicitly promote TIMESTAMP_DAYS * columns to TIMESTAMP_MILLISECONDS for compatibility with NumPy. * * @param useNumPyTypes true to request this conversion, false to avoid. * @return builder for chaining */ public Builder withNumPyTypes(boolean useNumPyTypes) { this.useNumPyTypes = useNumPyTypes; return this; } /** * Specify the time unit to use when returning timestamps. * @param unit default unit of time specified by the user * @return builder for chaining */ public ORCOptions.Builder withTimeUnit(DType unit) { assert unit.isTimestampType(); this.unit = unit; return this; } /** * Specify decimal columns which shall be read as DECIMAL128. Otherwise, decimal columns * will be read as DECIMAL64 by default in ORC. * * In terms of child columns of nested types, their parents need to be prepended as prefix * of the column name, in case of ambiguity. For struct columns, the names of child columns * are formatted as `{struct_col_name}.{child_col_name}`. For list columns, the data(child) * columns are named as `{list_col_name}.1`. * * @param names names of columns which read as DECIMAL128 * @return builder for chaining */ public Builder decimal128Column(String... names) { decimal128Columns.addAll(Arrays.asList(names)); return this; } public ORCOptions build() { return new ORCOptions(this); } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ORCWriterOptions.java
/* * * Copyright (c) 2019-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * This class represents settings for writing ORC files. It includes meta data information * that will be used by the ORC writer to write the file. */ public class ORCWriterOptions extends CompressionMetadataWriterOptions { private int stripeSizeRows; private ORCWriterOptions(Builder builder) { super(builder); this.stripeSizeRows = builder.stripeSizeRows; } public static Builder builder() { return new Builder(); } public int getStripeSizeRows() { return stripeSizeRows; } public static class Builder extends CompressionMetadataWriterOptions.Builder <Builder, ORCWriterOptions> { // < 1M rows default orc stripe rows, defined in cudf/cpp/include/cudf/io/orc.hpp private int stripeSizeRows = 1000000; public Builder withStripeSizeRows(int stripeSizeRows) { // maximum stripe size cannot be smaller than 512 if (stripeSizeRows < 512) { throw new IllegalArgumentException("Maximum stripe size cannot be smaller than 512"); } this.stripeSizeRows = stripeSizeRows; return this; } public ORCWriterOptions build() { return new ORCWriterOptions(this); } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/OrderByArg.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.io.Serializable; /** * Provides the ordering for specific columns. */ public final class OrderByArg implements Serializable { final int index; final boolean isDescending; final boolean isNullSmallest; OrderByArg(int index, boolean isDescending, boolean isNullSmallest) { this.index = index; this.isDescending = isDescending; this.isNullSmallest = isNullSmallest; } public static OrderByArg asc(final int index) { return new OrderByArg(index, false, false); } public static OrderByArg desc(final int index) { return new OrderByArg(index, true, false); } public static OrderByArg asc(final int index, final boolean isNullSmallest) { return new OrderByArg(index, false, isNullSmallest); } public static OrderByArg desc(final int index, final boolean isNullSmallest) { return new OrderByArg(index, true, isNullSmallest); } @Override public String toString() { return "ORDER BY " + index + (isDescending ? " DESC " : " ASC ") + (isNullSmallest ? "NULL SMALLEST" : "NULL LARGEST"); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/OutOfBoundsPolicy.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Policy to account for possible out-of-bounds indices * * `NULLIFY` means to nullify output values corresponding to out-of-bounds gather map values. * * `DONT_CHECK` means do not check whether the indices are out-of-bounds, for better * performance. Use `DONT_CHECK` carefully, as it can result in a CUDA exception if * the gather map values are actually out of range. * * @note This enum doesn't have a nativeId because the C++ out_of_bounds_policy is a * a boolean enum. It is just added for clarity in the Java API. */ public enum OutOfBoundsPolicy { /* Output values corresponding to out-of-bounds indices are null */ NULLIFY, /* No bounds checking is performed, better performance */ DONT_CHECK }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/PackedColumnMetadata.java
/* * * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.nio.ByteBuffer; /** * Metadata for a table that is backed by a single contiguous device buffer. */ public final class PackedColumnMetadata implements AutoCloseable { private long metadataHandle = 0; private ByteBuffer metadataBuffer = null; // This method is invoked by JNI static PackedColumnMetadata fromPackedColumnMeta(long metadataHandle) { return new PackedColumnMetadata(metadataHandle); } /** * Construct the PackedColumnMetadata instance given a metadata handle. * @param metadataHandle address of the cudf packed_table host-based metadata instance */ PackedColumnMetadata(long metadataHandle) { this.metadataHandle = metadataHandle; } /** * Get the byte buffer containing the host metadata describing the schema and layout of the * contiguous table. * <p> * NOTE: This is a direct byte buffer that is backed by the underlying native metadata instance * and therefore is only valid to be used while this PackedColumnMetadata instance is valid. * Attempts to cache and access the resulting buffer after this instance has been destroyed * will result in undefined behavior including the possibility of segmentation faults * or data corruption. */ public ByteBuffer getMetadataDirectBuffer() { if (metadataBuffer == null) { metadataBuffer = createMetadataDirectBuffer(metadataHandle); } return metadataBuffer.asReadOnlyBuffer(); } /** Close the PackedColumnMetadata instance and its underlying resources. */ @Override public void close() { if (metadataHandle != 0) { closeMetadata(metadataHandle); metadataHandle = 0; } } // create a DirectByteBuffer for the packed metadata private static native ByteBuffer createMetadataDirectBuffer(long metadataHandle); // release the native metadata resources for a packed table private static native void closeMetadata(long metadataHandle); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/PadSide.java
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; public enum PadSide { LEFT(0), RIGHT(1), BOTH(2); private static final PadSide[] PAD_SIDES = PadSide.values(); final int nativeId; PadSide(int nativeId) { this.nativeId = nativeId; } public int getNativeId() { return nativeId; } public static PadSide fromNative(int nativeId) { for (PadSide type : PAD_SIDES) { if (type.nativeId == nativeId) { return type; } } throw new IllegalArgumentException("Could not translate " + nativeId + " into a PadSide"); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ParquetChunkedReader.java
/* * * Copyright (c) 2022-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.io.File; /** * Provide an interface for reading a Parquet file in an iterative manner. */ public class ParquetChunkedReader implements AutoCloseable { static { NativeDepsLoader.loadNativeDeps(); } /** * Construct the reader instance from a read limit and a file path. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param filePath Full path of the input Parquet file to read. */ public ParquetChunkedReader(long chunkSizeByteLimit, File filePath) { this(chunkSizeByteLimit, ParquetOptions.DEFAULT, filePath); } /** * Construct the reader instance from a read limit, a ParquetOptions object, and a file path. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param opts The options for Parquet reading. * @param filePath Full path of the input Parquet file to read. */ public ParquetChunkedReader(long chunkSizeByteLimit, ParquetOptions opts, File filePath) { this(chunkSizeByteLimit, 0, opts, filePath); } /** * Construct the reader instance from a read limit, a ParquetOptions object, and a file path. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param passReadLimit Limit on the amount of memory used for reading and decompressing data or * 0 if there is no limit * @param opts The options for Parquet reading. * @param filePath Full path of the input Parquet file to read. */ public ParquetChunkedReader(long chunkSizeByteLimit, long passReadLimit, ParquetOptions opts, File filePath) { long[] handles = create(chunkSizeByteLimit, passReadLimit, opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), filePath.getAbsolutePath(), null, opts.timeUnit().typeId.getNativeId()); handle = handles[0]; if (handle == 0) { throw new IllegalStateException("Cannot create native chunked Parquet reader object."); } multiHostBufferSourceHandle = handles[1]; } /** * Construct the reader instance from a read limit and a file already read in a memory buffer. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param opts The options for Parquet reading. * @param buffer Raw Parquet file content. * @param offset The starting offset into buffer. * @param len The number of bytes to parse the given buffer. */ public ParquetChunkedReader(long chunkSizeByteLimit, ParquetOptions opts, HostMemoryBuffer buffer, long offset, long len) { this(chunkSizeByteLimit, 0L, opts, buffer, offset, len); } /** * Construct the reader instance from a read limit and a file already read in a memory buffer. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param passReadLimit Limit on the amount of memory used for reading and decompressing data or * 0 if there is no limit * @param opts The options for Parquet reading. * @param buffer Raw Parquet file content. * @param offset The starting offset into buffer. * @param len The number of bytes to parse the given buffer. */ public ParquetChunkedReader(long chunkSizeByteLimit, long passReadLimit, ParquetOptions opts, HostMemoryBuffer buffer, long offset, long len) { long[] addrsSizes = new long[]{ buffer.getAddress() + offset, len }; long[] handles = create(chunkSizeByteLimit,passReadLimit, opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), null, addrsSizes, opts.timeUnit().typeId.getNativeId()); handle = handles[0]; if (handle == 0) { throw new IllegalStateException("Cannot create native chunked Parquet reader object."); } multiHostBufferSourceHandle = handles[1]; } /** * Construct the reader instance from a read limit and data in host memory buffers. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param passReadLimit Limit on the amount of memory used for reading and decompressing data or * 0 if there is no limit * @param opts The options for Parquet reading. * @param buffers Array of buffers containing the file data. The buffers are logically * concatenated to construct the file being read. */ public ParquetChunkedReader(long chunkSizeByteLimit, long passReadLimit, ParquetOptions opts, HostMemoryBuffer... buffers) { long[] addrsSizes = new long[buffers.length * 2]; for (int i = 0; i < buffers.length; i++) { addrsSizes[i * 2] = buffers[i].getAddress(); addrsSizes[(i * 2) + 1] = buffers[i].getLength(); } long[] handles = create(chunkSizeByteLimit,passReadLimit, opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), null, addrsSizes, opts.timeUnit().typeId.getNativeId()); handle = handles[0]; if (handle == 0) { throw new IllegalStateException("Cannot create native chunked Parquet reader object."); } multiHostBufferSourceHandle = handles[1]; } /** * Construct a reader instance from a DataSource * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param opts The options for Parquet reading. * @param ds the data source to read from */ public ParquetChunkedReader(long chunkSizeByteLimit, ParquetOptions opts, DataSource ds) { dataSourceHandle = DataSourceHelper.createWrapperDataSource(ds); if (dataSourceHandle == 0) { throw new IllegalStateException("Cannot create native datasource object"); } boolean passed = false; try { handle = createWithDataSource(chunkSizeByteLimit, opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), opts.timeUnit().typeId.getNativeId(), dataSourceHandle); passed = true; } finally { if (!passed) { DataSourceHelper.destroyWrapperDataSource(dataSourceHandle); dataSourceHandle = 0; } } } /** * Check if the given file has anything left to read. * * @return A boolean value indicating if there is more data to read from file. */ public boolean hasNext() { if (handle == 0) { throw new IllegalStateException("Native chunked Parquet reader object may have been closed."); } if (firstCall) { // This function needs to return true at least once, so an empty table // (but having empty columns instead of no column) can be returned by readChunk() // if the input file has no row. firstCall = false; return true; } return hasNext(handle); } /** * Read a chunk of rows in the given Parquet file such that the returning data has total size * does not exceed the given read limit. If the given file has no data, or all data has been read * before by previous calls to this function, a null Table will be returned. * * @return A table of new rows reading from the given file. */ public Table readChunk() { if (handle == 0) { throw new IllegalStateException("Native chunked Parquet reader object may have been closed."); } long[] columnPtrs = readChunk(handle); return columnPtrs != null ? new Table(columnPtrs) : null; } @Override public void close() { if (handle != 0) { close(handle); handle = 0; } if (dataSourceHandle != 0) { DataSourceHelper.destroyWrapperDataSource(dataSourceHandle); dataSourceHandle = 0; } if (multiHostBufferSourceHandle != 0) { destroyMultiHostBufferSource(multiHostBufferSourceHandle); multiHostBufferSourceHandle = 0; } } /** * Auxiliary variable to help {@link #hasNext()} returning true at least once. */ private boolean firstCall = true; /** * Handle for memory address of the native Parquet chunked reader class. */ private long handle; private long dataSourceHandle = 0; private long multiHostBufferSourceHandle = 0; /** * Create a native chunked Parquet reader object on heap and return its memory address. * * @param chunkSizeByteLimit Limit on total number of bytes to be returned per read, * or 0 if there is no limit. * @param passReadLimit Limit on the amount of memory used for reading and decompressing * data or 0 if there is no limit. * @param filterColumnNames Name of the columns to read, or an empty array if we want to read all. * @param binaryToString Whether to convert the corresponding column to String if it is binary. * @param filePath Full path of the file to read, or given as null if reading from a buffer. * @param bufferAddrsSizes The address and size pairs of buffers to read from, or null if we are not using buffers. * @param timeUnit Return type of time unit for timestamps. */ private static native long[] create(long chunkSizeByteLimit, long passReadLimit, String[] filterColumnNames, boolean[] binaryToString, String filePath, long[] bufferAddrsSizes, int timeUnit); private static native long createWithDataSource(long chunkedSizeByteLimit, String[] filterColumnNames, boolean[] binaryToString, int timeUnit, long dataSourceHandle); private static native boolean hasNext(long handle); private static native long[] readChunk(long handle); private static native void close(long handle); private static native void destroyMultiHostBufferSource(long handle); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ParquetOptions.java
/* * * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Options for reading a parquet file */ public class ParquetOptions extends ColumnFilterOptions { public static ParquetOptions DEFAULT = new ParquetOptions(new Builder()); private final DType unit; private final boolean[] readBinaryAsString; private ParquetOptions(Builder builder) { super(builder); unit = builder.unit; readBinaryAsString = new boolean[builder.binaryAsStringColumns.size()]; for (int i = 0 ; i < builder.binaryAsStringColumns.size() ; i++) { readBinaryAsString[i] = builder.binaryAsStringColumns.get(i); } } DType timeUnit() { return unit; } boolean[] getReadBinaryAsString() { return readBinaryAsString; } public static ParquetOptions.Builder builder() { return new Builder(); } public static class Builder extends ColumnFilterOptions.Builder<Builder> { private DType unit = DType.EMPTY; final List<Boolean> binaryAsStringColumns = new ArrayList<>(); /** * Specify the time unit to use when returning timestamps. * @param unit default unit of time specified by the user * @return builder for chaining */ public Builder withTimeUnit(DType unit) { assert unit.isTimestampType(); this.unit = unit; return this; } /** * Include one or more specific columns. Any column not included will not be read. * @param names the name of the column, or more than one if you want. */ @Override public Builder includeColumn(String... names) { super.includeColumn(names); for (int i = 0 ; i < names.length ; i++) { binaryAsStringColumns.add(true); } return this; } /** * Include this column. * @param name the name of the column * @param isBinary whether this column is to be read in as binary */ public Builder includeColumn(String name, boolean isBinary) { includeColumnNames.add(name); binaryAsStringColumns.add(!isBinary); return this; } /** * Include one or more specific columns. Any column not included will not be read. * @param names the name of the column, or more than one if you want. */ @Override public Builder includeColumn(Collection<String> names) { super.includeColumn(names); for (int i = 0 ; i < names.size() ; i++) { binaryAsStringColumns.add(true); } return this; } public ParquetOptions build() { return new ParquetOptions(this); } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ParquetWriterOptions.java
/* * * Copyright (c) 2019-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * This class represents settings for writing Parquet files. It includes meta data information * that will be used by the Parquet writer to write the file */ public final class ParquetWriterOptions extends CompressionMetadataWriterOptions { private final StatisticsFrequency statsGranularity; private int rowGroupSizeRows; private long rowGroupSizeBytes; private ParquetWriterOptions(Builder builder) { super(builder); this.rowGroupSizeRows = builder.rowGroupSizeRows; this.rowGroupSizeBytes = builder.rowGroupSizeBytes; this.statsGranularity = builder.statsGranularity; } public enum StatisticsFrequency { /** Do not generate statistics */ NONE(0), /** Generate column statistics for each rowgroup */ ROWGROUP(1), /** Generate column statistics for each page */ PAGE(2); final int nativeId; StatisticsFrequency(int nativeId) { this.nativeId = nativeId; } } public static Builder builder() { return new Builder(); } public int getRowGroupSizeRows() { return rowGroupSizeRows; } public long getRowGroupSizeBytes() { return rowGroupSizeBytes; } public StatisticsFrequency getStatisticsFrequency() { return statsGranularity; } public static class Builder extends CompressionMetadataWriterOptions.Builder <Builder, ParquetWriterOptions> { private int rowGroupSizeRows = 1000000; //Max of 1 million rows per row group private long rowGroupSizeBytes = 128 * 1024 * 1024; //Max of 128MB per row group private StatisticsFrequency statsGranularity = StatisticsFrequency.ROWGROUP; public Builder() { super(); } public Builder withRowGroupSizeRows(int rowGroupSizeRows) { this.rowGroupSizeRows = rowGroupSizeRows; return this; } public Builder withRowGroupSizeBytes(long rowGroupSizeBytes) { this.rowGroupSizeBytes = rowGroupSizeBytes; return this; } public Builder withStatisticsFrequency(StatisticsFrequency statsGranularity) { this.statsGranularity = statsGranularity; return this; } public ParquetWriterOptions build() { return new ParquetWriterOptions(this); } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/PartitionedTable.java
/* * * Copyright (c) 2019-2020, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Class to provide a PartitionedTable */ public final class PartitionedTable implements AutoCloseable { private final Table table; private final int[] partitionsOffsets; /** * The package-private constructor is only called by the partition method in Table * .TableOperation.partition * @param table - {@link Table} which contains the partitioned data * @param partitionOffsets - This param is used to populate the offsets into the returned table * where partitionOffsets[i] indicates the starting position of * partition 'i' */ PartitionedTable(Table table, int[] partitionOffsets) { this.table = table; this.partitionsOffsets = partitionOffsets; } public Table getTable() { return table; } public ColumnVector getColumn(int index) { return table.getColumn(index); } public long getNumberOfColumns() { return table.getNumberOfColumns(); } public long getRowCount() { return table.getRowCount(); } @Override public void close() { table.close(); } /** * This method returns the partitions on this table. partitionOffsets[i] indicates the * starting position of partition 'i' in the partitioned table. Size of the partitions can * be calculated by the next offset * Ex: * partitionOffsets[0, 12, 12, 49] indicates 4 partitions with the following sizes * partition[0] - 12 * partition[1] - 0 (is empty) * partition[2] - 37 * partition[3] has the remaining values of the table (N-49) */ public int[] getPartitions() { return partitionsOffsets; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/PinnedMemoryPool.java
/* * * Copyright (c) 2019-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * This is the JNI interface to a rmm::pool_memory_resource<rmm::pinned_host_memory_resource>. */ public final class PinnedMemoryPool implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(PinnedMemoryPool.class); // These static fields should only ever be accessed when class-synchronized. // Do NOT use singleton_ directly! Use the getSingleton accessor instead. private static volatile PinnedMemoryPool singleton_ = null; private static Future<PinnedMemoryPool> initFuture = null; private long poolHandle; private long poolSize; private static final class PinnedHostBufferCleaner extends MemoryBuffer.MemoryBufferCleaner { private long address; private final long origLength; PinnedHostBufferCleaner(long address, long length) { this.address = address; origLength = length; } @Override protected synchronized boolean cleanImpl(boolean logErrorIfNotClean) { boolean neededCleanup = false; long origAddress = 0; if (address != -1) { origAddress = address; try { PinnedMemoryPool.freeInternal(address, origLength); } finally { // Always mark the resource as freed even if an exception is thrown. // We cannot know how far it progressed before the exception, and // therefore it is unsafe to retry. address = -1; } neededCleanup = true; } if (neededCleanup && logErrorIfNotClean) { log.error("A PINNED HOST BUFFER WAS LEAKED (ID: " + id + " " + Long.toHexString(origAddress) + ")"); logRefCountDebug("Leaked pinned host buffer"); } return neededCleanup; } @Override public boolean isClean() { return address == -1; } } private static PinnedMemoryPool getSingleton() { if (singleton_ == null) { if (initFuture == null) { return null; } synchronized (PinnedMemoryPool.class) { if (singleton_ == null) { try { singleton_ = initFuture.get(); } catch (Exception e) { throw new RuntimeException("Error initializing pinned memory pool", e); } initFuture = null; } } } return singleton_; } private static void freeInternal(long address, long origLength) { Objects.requireNonNull(getSingleton()).free(address, origLength); } /** * Initialize the pool. * * @param poolSize size of the pool to initialize. * @note when using this method, the pinned pool will be shared with cuIO */ public static synchronized void initialize(long poolSize) { initialize(poolSize, -1, true); } /** * Initialize the pool. * * @param poolSize size of the pool to initialize. * @param gpuId gpu id to set to get memory pool from, -1 means to use default * @note when using this method, the pinned pool will be shared with cuIO */ public static synchronized void initialize(long poolSize, int gpuId) { initialize(poolSize, gpuId, true); } /** * Initialize the pool. * * @param poolSize size of the pool to initialize. * @param gpuId gpu id to set to get memory pool from, -1 means to use default * @param setCudfPinnedPoolMemoryResource true if this pinned pool should be used by cuDF for pinned memory */ public static synchronized void initialize(long poolSize, int gpuId, boolean setCudfPinnedPoolMemoryResource) { if (isInitialized()) { throw new IllegalStateException("Can only initialize the pool once."); } ExecutorService initService = Executors.newSingleThreadExecutor(runnable -> { Thread t = new Thread(runnable, "pinned pool init"); t.setDaemon(true); return t; }); initFuture = initService.submit(() -> new PinnedMemoryPool(poolSize, gpuId, setCudfPinnedPoolMemoryResource)); initService.shutdown(); } /** * Check if the pool has been initialized or not. */ public static boolean isInitialized() { return getSingleton() != null; } /** * Shut down the RMM pool_memory_resource, nulling out our reference. Any allocation * or free that is in flight will fail after this. */ public static synchronized void shutdown() { PinnedMemoryPool pool = getSingleton(); if (pool != null) { pool.close(); pool = null; } initFuture = null; singleton_ = null; } /** * Factory method to create a pinned host memory buffer. * * @param bytes size in bytes to allocate * @return newly created buffer or null if insufficient pinned memory */ public static HostMemoryBuffer tryAllocate(long bytes) { HostMemoryBuffer result = null; PinnedMemoryPool pool = getSingleton(); if (pool != null) { result = pool.tryAllocateInternal(bytes); } return result; } /** * Factory method to create a host buffer but preferably pointing to pinned memory. * It is not guaranteed that the returned buffer will be pointer to pinned memory. * * @param bytes size in bytes to allocate * @return newly created buffer */ public static HostMemoryBuffer allocate(long bytes, HostMemoryAllocator hostMemoryAllocator) { HostMemoryBuffer result = tryAllocate(bytes); if (result == null) { result = hostMemoryAllocator.allocate(bytes, false); } return result; } /** * Factory method to create a host buffer but preferably pointing to pinned memory. * It is not guaranteed that the returned buffer will be pointer to pinned memory. * * @param bytes size in bytes to allocate * @return newly created buffer */ public static HostMemoryBuffer allocate(long bytes) { return allocate(bytes, DefaultHostMemoryAllocator.get()); } /** * Get the number of bytes that the pinned memory pool was allocated with. */ public static long getTotalPoolSizeBytes() { PinnedMemoryPool pool = getSingleton(); if (pool != null) { return pool.poolSize; } return 0; } private PinnedMemoryPool(long poolSize, int gpuId, boolean setCudfPinnedPoolMemoryResource) { if (gpuId > -1) { // set the gpu device to use Cuda.setDevice(gpuId); Cuda.freeZero(); } this.poolHandle = Rmm.newPinnedPoolMemoryResource(poolSize, poolSize); if (setCudfPinnedPoolMemoryResource) { Rmm.setCudfPinnedPoolMemoryResource(this.poolHandle); } this.poolSize = poolSize; } @Override public void close() { Rmm.releasePinnedPoolMemoryResource(this.poolHandle); this.poolHandle = -1; } /** * This makes an attempt to allocate pinned memory, and if the pinned memory allocation fails * it will return null, instead of throw. */ private synchronized HostMemoryBuffer tryAllocateInternal(long bytes) { long allocated = Rmm.allocFromPinnedPool(this.poolHandle, bytes); if (allocated == -1) { return null; } else { return new HostMemoryBuffer(allocated, bytes, new PinnedHostBufferCleaner(allocated, bytes)); } } private synchronized void free(long address, long size) { Rmm.freeFromPinnedPool(this.poolHandle, address, size); } /** * Sets the size of the cuDF default pinned pool. * * @note This has to be called before cuDF functions are executed. * * @param size initial and maximum size for the cuDF default pinned pool. * Pass size=0 to disable the default pool. * * @return true if we were able to setup the default resource, false if there was * a resource already set. */ public static synchronized boolean configureDefaultCudfPinnedPoolSize(long size) { return Rmm.configureDefaultCudfPinnedPoolSize(size); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/QuantileMethod.java
/* * * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Interpolation method to use when the desired quantile lies between * two data points i and j. */ public enum QuantileMethod { /** * Linear interpolation between i and j */ LINEAR(0), /** * Lower data point (i) */ LOWER(1), /** * Higher data point (j) */ HIGHER(2), /** * (i + j)/2 */ MIDPOINT(3), /** * i or j, whichever is nearest */ NEAREST(4); final int nativeId; QuantileMethod(int nativeId) { this.nativeId = nativeId; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/QuoteStyle.java
/* * * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Quote style for CSV records, closely following cudf::io::quote_style. */ public enum QuoteStyle { MINIMAL(0), // Quote only fields which contain special characters ALL(1), // Quote all fields NONNUMERIC(2), // Quote all non-numeric fields NONE(3); // Never quote fields; disable quotation parsing final int nativeId; // Native id, for use with libcudf. QuoteStyle(int nativeId) { this.nativeId = nativeId; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/Range.java
/* * * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import ai.rapids.cudf.HostColumnVector.Builder; import java.util.function.Consumer; /** * Helper utility for creating ranges. */ public final class Range { /** * Append a range to the builder. 0 inclusive to end exclusive. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendBytes(byte end) { return appendBytes((byte) 0, end, (byte) 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendBytes(byte start, byte end) { return appendBytes(start, end, (byte) 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @param step how must to step by. * @return the builder for chaining. */ public static final Consumer<Builder> appendBytes(byte start, byte end, byte step) { assert step > 0; assert start <= end; return (b) -> { for (byte i = start; i < end; i += step) { b.append(i); } }; } /** * Append a range to the builder. 0 inclusive to end exclusive. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendShorts(short end) { return appendShorts((short) 0, end, (short) 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendShorts(short start, short end) { return appendShorts(start, end, (short) 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @param step how must to step by. * @return the builder for chaining. */ public static final Consumer<Builder> appendShorts(short start, short end, short step) { assert step > 0; assert start <= end; return (b) -> { for (short i = start; i < end; i += step) { b.append(i); } }; } /** * Append a range to the builder. 0 inclusive to end exclusive. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendInts(int end) { return appendInts(0, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendInts(int start, int end) { return appendInts(start, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @param step how must to step by. * @return the builder for chaining. */ public static final Consumer<Builder> appendInts(int start, int end, int step) { assert step > 0; assert start <= end; return (b) -> { for (int i = start; i < end; i += step) { b.append(i); } }; } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @param step how must to step by. * @return the builder for chaining. */ public static final Consumer<Builder> appendLongs(long start, long end, long step) { assert step > 0; assert start <= end; return (b) -> { for (long i = start; i < end; i += step) { b.append(i); } }; } /** * Append a range to the builder. 0 inclusive to end exclusive. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendLongs(long end) { return appendLongs(0, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendLongs(long start, long end) { return appendLongs(start, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @param step how must to step by. * @return the builder for chaining. */ public static final Consumer<Builder> appendFloats(float start, float end, float step) { assert step > 0; assert start <= end; return (b) -> { for (float i = start; i < end; i += step) { b.append(i); } }; } /** * Append a range to the builder. 0 inclusive to end exclusive. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendFloats(float end) { return appendFloats(0, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendFloats(float start, float end) { return appendFloats(start, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @param step how must to step by. * @return the builder for chaining. */ public static final Consumer<Builder> appendDoubles(double start, double end, double step) { assert step > 0; assert start <= end; return (b) -> { for (double i = start; i < end; i += step) { b.append(i); } }; } /** * Append a range to the builder. 0 inclusive to end exclusive. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendDoubles(double end) { return appendDoubles(0, end, 1); } /** * Append a range to the builder. start inclusive to end exclusive. * @param start first entry. * @param end last entry exclusive. * @return the consumer. */ public static final Consumer<Builder> appendDoubles(double start, double end) { return appendDoubles(start, end, 1); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ReductionAggregation.java
/* * * Copyright (c) 2021-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * An aggregation that can be used for a reduce. */ public final class ReductionAggregation { private final Aggregation wrapped; private ReductionAggregation(Aggregation wrapped) { this.wrapped = wrapped; } long createNativeInstance() { return wrapped.createNativeInstance(); } long getDefaultOutput() { return wrapped.getDefaultOutput(); } Aggregation getWrapped() { return wrapped; } @Override public int hashCode() { return wrapped.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof ReductionAggregation) { ReductionAggregation o = (ReductionAggregation) other; return wrapped.equals(o.wrapped); } return false; } /** * Sum Aggregation */ public static ReductionAggregation sum() { return new ReductionAggregation(Aggregation.sum()); } /** * Product Aggregation. */ public static ReductionAggregation product() { return new ReductionAggregation(Aggregation.product()); } /** * Min Aggregation */ public static ReductionAggregation min() { return new ReductionAggregation(Aggregation.min()); } /** * Max Aggregation */ public static ReductionAggregation max() { return new ReductionAggregation(Aggregation.max()); } /** * Any reduction. Produces a true or 1, depending on the output type, * if any of the elements in the range are true or non-zero, otherwise produces a false or 0. * Null values are skipped. */ public static ReductionAggregation any() { return new ReductionAggregation(Aggregation.any()); } /** * All reduction. Produces true or 1, depending on the output type, if all of the elements in * the range are true or non-zero, otherwise produces a false or 0. * Null values are skipped. */ public static ReductionAggregation all() { return new ReductionAggregation(Aggregation.all()); } /** * Sum of squares reduction. */ public static ReductionAggregation sumOfSquares() { return new ReductionAggregation(Aggregation.sumOfSquares()); } /** * Arithmetic mean reduction. */ public static ReductionAggregation mean() { return new ReductionAggregation(Aggregation.mean()); } /** * Variance aggregation with 1 as the delta degrees of freedom. */ public static ReductionAggregation variance() { return new ReductionAggregation(Aggregation.variance()); } /** * Variance aggregation. * @param ddof delta degrees of freedom. The divisor used in calculation of variance is * <code>N - ddof</code>, where N is the population size. */ public static ReductionAggregation variance(int ddof) { return new ReductionAggregation(Aggregation.variance(ddof)); } /** * Standard deviation aggregation with 1 as the delta degrees of freedom. */ public static ReductionAggregation standardDeviation() { return new ReductionAggregation(Aggregation.standardDeviation()); } /** * Standard deviation aggregation. * @param ddof delta degrees of freedom. The divisor used in calculation of std is * <code>N - ddof</code>, where N is the population size. */ public static ReductionAggregation standardDeviation(int ddof) { return new ReductionAggregation(Aggregation.standardDeviation(ddof)); } /** * Median reduction. */ public static ReductionAggregation median() { return new ReductionAggregation(Aggregation.median()); } /** * Aggregate to compute the specified quantiles. Uses linear interpolation by default. */ public static ReductionAggregation quantile(double... quantiles) { return new ReductionAggregation(Aggregation.quantile(quantiles)); } /** * Aggregate to compute various quantiles. */ public static ReductionAggregation quantile(QuantileMethod method, double... quantiles) { return new ReductionAggregation(Aggregation.quantile(method, quantiles)); } /** * Number of unique, non-null, elements. */ public static ReductionAggregation nunique() { return new ReductionAggregation(Aggregation.nunique()); } /** * Number of unique elements. * @param nullPolicy INCLUDE if nulls should be counted else EXCLUDE. If nulls are counted they * compare as equal so multiple null values in a range would all only * increase the count by 1. */ public static ReductionAggregation nunique(NullPolicy nullPolicy) { return new ReductionAggregation(Aggregation.nunique(nullPolicy)); } /** * Get the nth, non-null, element in a group. * @param offset the offset to look at. Negative numbers go from the end of the group. Any * value outside of the group range results in a null. */ public static ReductionAggregation nth(int offset) { return new ReductionAggregation(Aggregation.nth(offset)); } /** * Get the nth element in a group. * @param offset the offset to look at. Negative numbers go from the end of the group. Any * value outside of the group range results in a null. * @param nullPolicy INCLUDE if nulls should be included in the aggregation or EXCLUDE if they * should be skipped. */ public static ReductionAggregation nth(int offset, NullPolicy nullPolicy) { return new ReductionAggregation(Aggregation.nth(offset, nullPolicy)); } /** * tDigest reduction. */ public static ReductionAggregation createTDigest(int delta) { return new ReductionAggregation(Aggregation.createTDigest(delta)); } /** * tDigest merge reduction. */ public static ReductionAggregation mergeTDigest(int delta) { return new ReductionAggregation(Aggregation.mergeTDigest(delta)); } /* * Collect the values into a list. Nulls will be skipped. */ public static ReductionAggregation collectList() { return new ReductionAggregation(Aggregation.collectList()); } /** * Collect the values into a list. * * @param nullPolicy Indicates whether to include/exclude nulls during collection. */ public static ReductionAggregation collectList(NullPolicy nullPolicy) { return new ReductionAggregation(Aggregation.collectList(nullPolicy)); } /** * Collect the values into a set. All null values will be excluded, and all NaN values are regarded as * unique instances. */ public static ReductionAggregation collectSet() { return new ReductionAggregation(Aggregation.collectSet()); } /** * Collect the values into a set. * * @param nullPolicy Indicates whether to include/exclude nulls during collection. * @param nullEquality Flag to specify whether null entries within each list should be considered equal. * @param nanEquality Flag to specify whether NaN values in floating point column should be considered equal. */ public static ReductionAggregation collectSet(NullPolicy nullPolicy, NullEquality nullEquality, NaNEquality nanEquality) { return new ReductionAggregation(Aggregation.collectSet(nullPolicy, nullEquality, nanEquality)); } /** * Merge the partial lists produced by multiple CollectListAggregations. * NOTICE: The partial lists to be merged should NOT include any null list element (but can include null list entries). */ public static ReductionAggregation mergeLists() { return new ReductionAggregation(Aggregation.mergeLists()); } /** * Merge the partial sets produced by multiple CollectSetAggregations. Each null/NaN value will be regarded as * a unique instance. */ public static ReductionAggregation mergeSets() { return new ReductionAggregation(Aggregation.mergeSets()); } /** * Merge the partial sets produced by multiple CollectSetAggregations. * * @param nullEquality Flag to specify whether null entries within each list should be considered equal. * @param nanEquality Flag to specify whether NaN values in floating point column should be considered equal. */ public static ReductionAggregation mergeSets(NullEquality nullEquality, NaNEquality nanEquality) { return new ReductionAggregation(Aggregation.mergeSets(nullEquality, nanEquality)); } /** * Execute a reduction using a host-side user-defined function (UDF). * @param wrapper The wrapper for the native host UDF instance. * @return A new ReductionAggregation instance */ public static ReductionAggregation hostUDF(HostUDFWrapper wrapper) { return new ReductionAggregation(Aggregation.hostUDF(wrapper)); } /** * Create HistogramAggregation, computing the frequencies for each unique row. * * @return A structs column in which the first child stores unique rows from the input and the * second child stores their corresponding frequencies. */ public static ReductionAggregation histogram() { return new ReductionAggregation(Aggregation.histogram()); } /** * Create MergeHistogramAggregation, to merge multiple histograms. * * @return A new histogram in which the frequencies of the unique rows are sum up. */ public static ReductionAggregation mergeHistogram() { return new ReductionAggregation(Aggregation.mergeHistogram()); } /** * Bitwise AND aggregation, computing the bitwise AND of all non-null values. */ public static ReductionAggregation bitAnd() { return new ReductionAggregation(Aggregation.bitAnd()); } /** * Bitwise OR aggregation, computing the bitwise OR of all non-null values. */ public static ReductionAggregation bitOr() { return new ReductionAggregation(Aggregation.bitOr()); } /** * Bitwise XOR aggregation, computing the bitwise XOR of all non-null values. */ public static ReductionAggregation bitXor() { return new ReductionAggregation(Aggregation.bitXor()); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RegexFlag.java
/* * * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Regex flags setting, closely following cudf::strings::regex_flags. * * These types can be or'd to combine them. The values are chosen to * leave room for future flags and to match the Python flag values. */ public enum RegexFlag { DEFAULT(0), // default MULTILINE(8), // the '^' and '$' honor new-line characters DOTALL(16), // the '.' matching includes new-line characters ASCII(256), // use only ASCII when matching built-in character classes /** * EXT_NEWLINE(512): Extends line delimiters to include the following Unicode characters * - NEXT_LINE ('\u0085') * - LINE_SEPARATOR ('\u2028') * - PARAGRAPH_SEPARATOR ('\u2029') * - CARRIAGE_RETURN ('\r') * - NEW_LINE ('\n') */ EXT_NEWLINE(512); final int nativeId; // Native id, for use with libcudf. private RegexFlag(int nativeId) { // Only constant values should be used this.nativeId = nativeId; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RegexProgram.java
/* * * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.util.EnumSet; /** * Regex program class, closely following cudf::strings::regex_program. */ public class RegexProgram { private String pattern; // regex pattern // regex flags for interpreting special characters in the pattern private EnumSet<RegexFlag> flags; // controls how capture groups in the pattern are used // default is to extract a capture group private CaptureGroups capture; /** * Constructor for RegexProgram * * @param pattern Regex pattern */ public RegexProgram(String pattern) { this(pattern, EnumSet.of(RegexFlag.DEFAULT), CaptureGroups.EXTRACT); } /** * Constructor for RegexProgram * * @param pattern Regex pattern * @param flags Regex flags setting */ public RegexProgram(String pattern, EnumSet<RegexFlag> flags) { this(pattern, flags, CaptureGroups.EXTRACT); } /** * Constructor for RegexProgram * * @param pattern Regex pattern setting * @param capture Capture groups setting */ public RegexProgram(String pattern, CaptureGroups capture) { this(pattern, EnumSet.of(RegexFlag.DEFAULT), capture); } /** * Constructor for RegexProgram * * @param pattern Regex pattern * @param flags Regex flags setting * @param capture Capture groups setting */ public RegexProgram(String pattern, EnumSet<RegexFlag> flags, CaptureGroups capture) { assert pattern != null : "pattern may not be null"; this.pattern = pattern; this.flags = flags; this.capture = capture; } /** * Get the pattern used to create this instance * * @param return A regex pattern as a string */ public String pattern() { return pattern; } /** * Get the regex flags setting used to create this instance * * @param return Regex flags setting */ public EnumSet<RegexFlag> flags() { return flags; } /** * Reset the regex flags setting for this instance * * @param flags Regex flags setting */ public void setFlags(EnumSet<RegexFlag> flags) { this.flags = flags; } /** * Get the capture groups setting used to create this instance * * @param return Capture groups setting */ public CaptureGroups capture() { return capture; } /** * Reset the capture groups setting for this instance * * @param capture Capture groups setting */ public void setCapture(CaptureGroups capture) { this.capture = capture; } /** * Combine the regex flags using 'or' * * @param return An integer representing the value of combined (or'ed) flags */ public int combinedFlags() { int allFlags = 0; for (RegexFlag flag : flags) { allFlags |= flag.nativeId; } return allFlags; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ReplacePolicy.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Policy to specify the position of replacement values relative to null rows. */ public enum ReplacePolicy { /** * The replacement value is the first non-null value preceding the null row. */ PRECEDING(true), /** * The replacement value is the first non-null value following the null row. */ FOLLOWING(false); ReplacePolicy(boolean isPreceding) { this.isPreceding = isPreceding; } final boolean isPreceding; /** * Indicate which column the replacement should happen on. */ public ReplacePolicyWithColumn onColumn(int columnNumber) { return new ReplacePolicyWithColumn(columnNumber, this); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ReplacePolicyWithColumn.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A replacement policy for a specific column */ public class ReplacePolicyWithColumn { final int column; final ReplacePolicy policy; ReplacePolicyWithColumn(int column, ReplacePolicy policy) { this.column = column; this.policy = policy; } @Override public boolean equals(Object other) { if (!(other instanceof ReplacePolicyWithColumn)) { return false; } ReplacePolicyWithColumn ro = (ReplacePolicyWithColumn)other; return this.column == ro.column && this.policy.equals(ro.policy); } @Override public int hashCode() { return 31 * column + policy.hashCode(); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/Rmm.java
/* * Copyright (c) 2019-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.io.File; import java.util.concurrent.TimeUnit; /** * This is the binding class for rmm lib. */ public class Rmm { private static volatile RmmTrackingResourceAdaptor<RmmDeviceMemoryResource> tracker = null; private static volatile RmmDeviceMemoryResource deviceResource = null; private static volatile boolean initialized = false; private static volatile long poolSize = -1; private static volatile boolean poolingEnabled = false; static { NativeDepsLoader.loadNativeDeps(); } enum LogLoc { NONE(0), FILE(1), STDOUT(2), STDERR(3); final int internalId; LogLoc(int internalId) { this.internalId = internalId; } } /** * What to send RMM alloc and free logs to. */ public static class LogConf { final File file; final LogLoc loc; private LogConf(File file, LogLoc loc) { this.file = file; this.loc = loc; } } /** * Create a config that will write alloc/free logs to a file. */ public static LogConf logTo(File location) { return new LogConf(location, LogLoc.FILE); } /** * Create a config that will write alloc/free logs to stdout. */ public static LogConf logToStdout() { return new LogConf(null, LogLoc.STDOUT); } /** * Create a config that will write alloc/free logs to stderr. */ public static LogConf logToStderr() { return new LogConf(null, LogLoc.STDERR); } /** * Get the RmmDeviceMemoryResource that was last set through the java APIs. This will * not return the correct value if the resource was not set using the java APIs. It will * return a null if the resource was never set through the java APIs. */ public static synchronized RmmDeviceMemoryResource getCurrentDeviceResource() { return deviceResource; } /** * Get the currently set RmmTrackingResourceAdaptor that is set. This might return null if * RMM has nto been initialized. */ public static synchronized RmmTrackingResourceAdaptor<RmmDeviceMemoryResource> getTracker() { return tracker; } /** * Set the current device resource that RMM should use for all allocations and de-allocations. * This should only be done if you feel comfortable that the current device resource has no * pending allocations. Note that the caller of this is responsible for closing the current * RmmDeviceMemoryResource that is returned by this. Assuming that it was not used to create * the newResource. Please use the `shutdown` API to clear the resource as it does best * effort clean up before shutting it down. If `newResource` is not null this will initialize * the CUDA context for the calling thread if it is not already set. The caller is responsible * for setting the desired CUDA device prior to this call if a specific device is already set. * <p>NOTE: All cudf methods will set the chosen CUDA device in the CUDA context of the calling * thread after this returns and `newResource` was not null. * <p>If `newResource` is null this will unset the default CUDA device and mark RMM as not * initialized. * <p>Be aware that for many of these APIs to work the RmmDeviceMemoryResource will need an * `RmmTrackingResourceAdaptor`. If one is not found and `newResource` is not null it will * be added to `newResource`. * <p>Also be very careful with how you set this up. It is possible to set up an * RmmDeviceMemoryResource that is just bad, like multiple pools or pools on top of an * RmmAsyncMemoryResource, that does pooling already. Unless you know what you are doing it is * best to just use the `initialize` API instead. * * @param newResource the new resource to set. If it is null an RmmCudaMemoryResource will be * used, and RMM will be set as not initialized. * @param expectedResource the resource that we expect to be set. This is to let us avoid race * conditions with multiple things trying to set this at once. It should * never happen, but just to be careful. * @param forceChange if true then the expectedResource check is not done. */ public static synchronized RmmDeviceMemoryResource setCurrentDeviceResource( RmmDeviceMemoryResource newResource, RmmDeviceMemoryResource expectedResource, boolean forceChange) { boolean shouldInit = false; boolean shouldDeinit = false; RmmDeviceMemoryResource newResourceToSet = newResource; if (newResourceToSet == null) { // We always want it to be set to something or else it can cause problems... newResourceToSet = new RmmCudaMemoryResource(); if (initialized) { shouldDeinit = true; } } else if (!initialized) { shouldInit = true; } RmmDeviceMemoryResource oldResource = deviceResource; if (!forceChange && expectedResource != null && deviceResource != null) { long expectedOldHandle = expectedResource.getHandle(); long oldHandle = deviceResource.getHandle(); if (oldHandle != expectedOldHandle) { throw new RmmException("The expected device resource is not correct " + Long.toHexString(oldHandle) + " != " + Long.toHexString(expectedOldHandle)); } } poolSize = -1; poolingEnabled = false; setGlobalValsFromResource(newResourceToSet); if (newResource != null && tracker == null) { // No tracker was set, but we need one tracker = new RmmTrackingResourceAdaptor<>(newResourceToSet, 256); newResourceToSet = tracker; } long newHandle = newResourceToSet.getHandle(); setCurrentDeviceResourceInternal(newHandle); deviceResource = newResource; if (shouldInit) { initDefaultCudaDevice(); MemoryCleaner.setDefaultGpu(Cuda.getDevice()); initialized = true; } if (shouldDeinit) { cleanupDefaultCudaDevice(); initialized = false; } return oldResource; } private static void setGlobalValsFromResource(RmmDeviceMemoryResource resource) { if (resource instanceof RmmTrackingResourceAdaptor) { Rmm.tracker = (RmmTrackingResourceAdaptor<RmmDeviceMemoryResource>) resource; } else if (resource instanceof RmmPoolMemoryResource) { Rmm.poolSize = Math.max(((RmmPoolMemoryResource)resource).getMaxSize(), Rmm.poolSize); Rmm.poolingEnabled = true; } else if (resource instanceof RmmArenaMemoryResource) { Rmm.poolSize = Math.max(((RmmArenaMemoryResource)resource).getSize(), Rmm.poolSize); Rmm.poolingEnabled = true; } else if (resource instanceof RmmCudaAsyncMemoryResource) { Rmm.poolSize = Math.max(((RmmCudaAsyncMemoryResource)resource).getSize(), Rmm.poolSize); Rmm.poolingEnabled = true; } // Recurse as needed if (resource instanceof RmmWrappingDeviceMemoryResource) { setGlobalValsFromResource(((RmmWrappingDeviceMemoryResource<RmmDeviceMemoryResource>)resource).getWrapped()); } } /** * Initialize memory manager state and storage. This will always initialize * the CUDA context for the calling thread if it is not already set. The * caller is responsible for setting the desired CUDA device prior to this * call if a specific device is already set. * <p>NOTE: All cudf methods will set the chosen CUDA device in the CUDA * context of the calling thread after this returns. * @param allocationMode Allocation strategy to use. Bit set using * {@link RmmAllocationMode#CUDA_DEFAULT}, * {@link RmmAllocationMode#POOL}, * {@link RmmAllocationMode#ARENA}, * {@link RmmAllocationMode#CUDA_ASYNC}, * {@link RmmAllocationMode#CUDA_ASYNC_FABRIC} and * {@link RmmAllocationMode#CUDA_MANAGED_MEMORY} * @param logConf How to do logging or null if you don't want to * @param poolSize The initial pool size in bytes * @throws IllegalStateException if RMM has already been initialized */ public static synchronized void initialize(int allocationMode, LogConf logConf, long poolSize) throws RmmException { if (initialized) { throw new IllegalStateException("RMM is already initialized"); } boolean isPool = (allocationMode & RmmAllocationMode.POOL) != 0; boolean isArena = (allocationMode & RmmAllocationMode.ARENA) != 0; boolean isAsync = (allocationMode & RmmAllocationMode.CUDA_ASYNC) != 0; boolean isAsyncFabric = (allocationMode & RmmAllocationMode.CUDA_ASYNC_FABRIC) != 0; boolean isManaged = (allocationMode & RmmAllocationMode.CUDA_MANAGED_MEMORY) != 0; if (isAsync && isManaged) { throw new IllegalArgumentException( "CUDA Unified Memory is not supported in CUDA_ASYNC allocation mode"); } RmmDeviceMemoryResource resource = null; boolean succeeded = false; try { if (isPool) { if (isManaged) { resource = new RmmPoolMemoryResource<>(new RmmManagedMemoryResource(), poolSize, poolSize); } else { resource = new RmmPoolMemoryResource<>(new RmmCudaMemoryResource(), poolSize, poolSize); } } else if (isArena) { if (isManaged) { resource = new RmmArenaMemoryResource<>(new RmmManagedMemoryResource(), poolSize, false); } else { resource = new RmmArenaMemoryResource<>(new RmmCudaMemoryResource(), poolSize, false); } } else if (isAsync) { resource = new RmmLimitingResourceAdaptor<>( new RmmCudaAsyncMemoryResource(poolSize, poolSize), poolSize, 512); } else if (isAsyncFabric) { resource = new RmmLimitingResourceAdaptor<>( new RmmCudaAsyncMemoryResource(poolSize, poolSize, true), poolSize, 512); } else if (isManaged) { resource = new RmmManagedMemoryResource(); } else { resource = new RmmCudaMemoryResource(); } if (logConf != null && logConf.loc != LogLoc.NONE) { resource = new RmmLoggingResourceAdaptor<>(resource, logConf, true); } resource = new RmmTrackingResourceAdaptor<>(resource, 256); setCurrentDeviceResource(resource, null, false); succeeded = true; } finally { if (!succeeded && resource != null) { resource.close(); } } } /** * Sets the size of the cuDF default pinned pool. * * @note This has to be called before cuDF functions are executed. * * @param size initial and maximum size for the cuDF default pinned pool. * Pass size=0 to disable the default pool. * * @return true if we were able to setup the default resource, false if there was * a resource already set. */ public static synchronized native boolean configureDefaultCudfPinnedPoolSize(long size); /** * Get the most recently set pool size or -1 if RMM has not been initialized or pooling is * not enabled. */ public static synchronized long getPoolSize() { return poolSize; } /** * Return true if rmm is initialized and pooling has been enabled, else false. */ public static synchronized boolean isPoolingEnabled() { return poolingEnabled; } /** * Check if RMM has been initialized already or not. */ public static boolean isInitialized() throws RmmException { return initialized; } /** * Return the amount of RMM memory allocated in bytes. Note that the result * may be less than the actual amount of allocated memory if underlying RMM * allocator decides to return more memory than what was requested. However, * the result will always be a lower bound on the amount allocated. */ public static synchronized long getTotalBytesAllocated() { if (tracker == null) { return 0; } else { return tracker.getTotalBytesAllocated(); } } /** * Returns the maximum amount of RMM memory (Bytes) outstanding during the * lifetime of the process. */ public static synchronized long getMaximumTotalBytesAllocated() { if (tracker == null) { return 0; } else { return tracker.getMaxTotalBytesAllocated(); } } /** * Resets a scoped maximum counter of RMM memory used to keep track of usage between * code sections while debugging. * * @param initialValue an initial value (in Bytes) to use for this scoped counter */ public static synchronized void resetScopedMaximumBytesAllocated(long initialValue) { if (tracker != null) { tracker.resetScopedMaxTotalBytesAllocated(initialValue); } } /** * Resets a scoped maximum counter of RMM memory used to keep track of usage between * code sections while debugging. * * This resets the counter to 0 Bytes. */ public static synchronized void resetScopedMaximumBytesAllocated() { if (tracker != null) { tracker.resetScopedMaxTotalBytesAllocated(0L); } } /** * Returns the maximum amount of RMM memory (Bytes) outstanding since the last * `resetScopedMaximumOutstanding` call was issued (it is "scoped" because it's the * maximum amount seen since the last reset). * <p> * If the memory used is net negative (for example if only frees happened since * reset, and we reset to 0), then result will be 0. * <p> * If `resetScopedMaximumBytesAllocated` is never called, the scope is the whole * program and is equivalent to `getMaximumTotalBytesAllocated`. * * @return the scoped maximum bytes allocated */ public static synchronized long getScopedMaximumBytesAllocated() { if (tracker == null) { return 0L; } else { return tracker.getScopedMaxTotalBytesAllocated(); } } /** * Sets the event handler to be called on RMM events (e.g.: allocation failure). * @param handler event handler to invoke on RMM events or null to clear an existing handler * @throws RmmException if an active handler is already set */ public static void setEventHandler(RmmEventHandler handler) throws RmmException { setEventHandler(handler, false); } /** * Sets the event handler to be called on RMM events (e.g.: allocation failure) and * optionally enable debug mode (callbacks on every allocate and deallocate) * <p> * NOTE: Only enable debug mode when necessary, as code will run much slower! * * @param handler event handler to invoke on RMM events or null to clear an existing handler * @param enableDebug if true enable debug callbacks in RmmEventHandler * (onAllocated, onDeallocated) * @throws RmmException if an active handler is already set */ public static synchronized void setEventHandler(RmmEventHandler handler, boolean enableDebug) throws RmmException { if (!initialized) { throw new RmmException("RMM has not been initialized"); } if (deviceResource instanceof RmmEventHandlerResourceAdaptor) { throw new RmmException("Another event handler is already set"); } if (tracker == null) { // This is just to be safe it should always be true if this is initialized. throw new RmmException("A tracker must be set for the event handler to work"); } RmmEventHandlerResourceAdaptor<RmmDeviceMemoryResource> newResource = new RmmEventHandlerResourceAdaptor<>(deviceResource, tracker, handler, enableDebug); boolean success = false; try { setCurrentDeviceResource(newResource, deviceResource, false); success = true; } finally { if (!success) { newResource.releaseWrapped(); } } } /** Clears the active RMM event handler if one is set. */ public static synchronized void clearEventHandler() throws RmmException { if (deviceResource != null && deviceResource instanceof RmmEventHandlerResourceAdaptor) { RmmEventHandlerResourceAdaptor<RmmDeviceMemoryResource> orig = (RmmEventHandlerResourceAdaptor<RmmDeviceMemoryResource>)deviceResource; boolean success = false; try { setCurrentDeviceResource(orig.wrapped, orig, false); success = true; } finally { if (success) { orig.releaseWrapped(); } } } } public static native void initDefaultCudaDevice(); public static native void cleanupDefaultCudaDevice(); /** * Shut down any initialized RMM instance. This should be used very rarely. It does not need to * be used when shutting down your process because CUDA will handle releasing all of the * resources when your process exits. This really should only be used if you want to turn off the * memory pool for some reasons. As such we make an effort to be sure no resources have been * leaked before shutting down. This may involve forcing a JVM GC to collect any leaked java * objects that still point to CUDA memory. By default this will do a gc every 2 seconds and * wait for up to 4 seconds before throwing an RmmException if not all of the resources are freed. * @throws RmmException on any error. This includes if there are outstanding allocations that * could not be collected. */ public static void shutdown() throws RmmException { shutdown(2, 4, TimeUnit.SECONDS); } /** * Shut down any initialized RMM instance. This should be used very rarely. It does not need to * be used when shutting down your process because CUDA will handle releasing all of the * resources when your process exits. This really should only be used if you want to turn off the * memory pool for some reasons. As such we make an effort to be sure no resources have been * leaked before shutting down. This may involve forcing a JVM GC to collect any leaked java * objects that still point to CUDA memory. * * @param forceGCInterval how frequently should we force a JVM GC. This is just a recommendation * to the JVM to do a gc. * @param maxWaitTime the maximum amount of time to wait for all objects to be collected before * throwing an exception. * @param units the units for forceGcInterval and maxWaitTime. * @throws RmmException on any error. This includes if there are outstanding allocations that * could not be collected before maxWaitTime. */ public static synchronized void shutdown(long forceGCInterval, long maxWaitTime, TimeUnit units) throws RmmException { long now = System.currentTimeMillis(); final long endTime = now + units.toMillis(maxWaitTime); long nextGcTime = now; try { if (MemoryCleaner.bestEffortHasRmmBlockers()) { do { if (nextGcTime <= now) { System.gc(); nextGcTime = nextGcTime + units.toMillis(forceGCInterval); } // Check if everything is ready about every 10 ms Thread.sleep(10); now = System.currentTimeMillis(); } while (endTime > now && MemoryCleaner.bestEffortHasRmmBlockers()); } } catch (InterruptedException e) { // Ignored } if (MemoryCleaner.bestEffortHasRmmBlockers()) { throw new RmmException("Could not shut down RMM there appear to be outstanding allocations"); } if (initialized) { if (deviceResource != null) { setCurrentDeviceResource(null, deviceResource, true).close(); } } } /** * Allocate device memory and return a pointer to device memory, using stream 0. * @param size The size in bytes of the allocated memory region * @return Returned pointer to the allocated memory */ public static DeviceMemoryBuffer alloc(long size) { return alloc(size, null); } /** * Allocate device memory and return a pointer to device memory. * @param size The size in bytes of the allocated memory region * @param stream The stream in which to synchronize this command. * @return Returned pointer to the allocated memory */ public static DeviceMemoryBuffer alloc(long size, Cuda.Stream stream) { long s = stream == null ? 0 : stream.getStream(); return new DeviceMemoryBuffer(allocInternal(size, s), size, stream); } private static native long allocInternal(long size, long stream) throws RmmException; static native void free(long ptr, long length, long stream) throws RmmException; /** * Delete an rmm::device_buffer. */ static native void freeDeviceBuffer(long rmmBufferAddress) throws RmmException; /** * Allocate device memory using `cudaMalloc` and return a pointer to device memory. * @param size The size in bytes of the allocated memory region * @param stream The stream in which to synchronize this command. * @return Returned pointer to the allocated memory */ public static CudaMemoryBuffer allocCuda(long size, Cuda.Stream stream) { long s = stream == null ? 0 : stream.getStream(); return new CudaMemoryBuffer(allocCudaInternal(size, s), size, stream); } private static native long allocCudaInternal(long size, long stream) throws RmmException; static native void freeCuda(long ptr, long length, long stream) throws RmmException; static native long newCudaMemoryResource() throws RmmException; static native void releaseCudaMemoryResource(long handle); static native long newManagedMemoryResource() throws RmmException; static native void releaseManagedMemoryResource(long handle); static native long newPoolMemoryResource(long childHandle, long initSize, long maxSize) throws RmmException; static native void releasePoolMemoryResource(long handle); static native long newArenaMemoryResource(long childHandle, long size, boolean dumpOnOOM) throws RmmException; static native void releaseArenaMemoryResource(long handle); static native long newCudaAsyncMemoryResource(long size, long release, boolean fabric) throws RmmException; static native void releaseCudaAsyncMemoryResource(long handle); static native long newLimitingResourceAdaptor(long handle, long limit, long align) throws RmmException; static native void releaseLimitingResourceAdaptor(long handle); static native long newLoggingResourceAdaptor(long handle, int type, String path, boolean autoFlush) throws RmmException; static native void releaseLoggingResourceAdaptor(long handle); static native long newTrackingResourceAdaptor(long handle, long alignment) throws RmmException; static native void releaseTrackingResourceAdaptor(long handle); static native long nativeGetTotalBytesAllocated(long handle); static native long nativeGetMaxTotalBytesAllocated(long handle); static native void nativeResetScopedMaxTotalBytesAllocated(long handle, long initValue); static native long nativeGetScopedMaxTotalBytesAllocated(long handle); static native long newEventHandlerResourceAdaptor(long handle, long trackerHandle, RmmEventHandler handler, long[] allocThresholds, long[] deallocThresholds, boolean debug); static native long releaseEventHandlerResourceAdaptor(long handle, boolean debug); private static native void setCurrentDeviceResourceInternal(long newHandle); public static native long newPinnedPoolMemoryResource(long initSize, long maxSize); public static native long setCudfPinnedPoolMemoryResource(long poolPtr); public static native void releasePinnedPoolMemoryResource(long poolPtr); public static native long allocFromPinnedPool(long poolPtr, long size); public static native void freeFromPinnedPool(long poolPtr, long ptr, long size); // only for tests public static native long allocFromFallbackPinnedPool(long size); // only for tests public static native void freeFromFallbackPinnedPool(long ptr, long size); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmAllocationMode.java
/* * Copyright (c) 2019-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; public class RmmAllocationMode { /** * Use cudaMalloc for allocation */ public static final int CUDA_DEFAULT = 0x00000000; /** * Use pool suballocation strategy */ public static final int POOL = 0x00000001; /** * Use cudaMallocManaged rather than cudaMalloc */ public static final int CUDA_MANAGED_MEMORY = 0x00000002; /** * Use arena suballocation strategy */ public static final int ARENA = 0x00000004; /** * Use CUDA async suballocation strategy */ public static final int CUDA_ASYNC = 0x00000008; /** * Use CUDA async suballocation strategy with fabric handles that are * peer accessible with read-write access */ public static final int CUDA_ASYNC_FABRIC = 0x00000010; }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmArenaMemoryResource.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that will pre-allocate a pool of resources and sub-allocate from this * pool to improve memory performance. This uses an algorithm to try and reduce fragmentation * much more than the RmmPoolMemoryResource does. */ public class RmmArenaMemoryResource<C extends RmmDeviceMemoryResource> extends RmmWrappingDeviceMemoryResource<C> { private final long size; private final boolean dumpLogOnFailure; private long handle = 0; /** * Create a new arena memory resource taking ownership of the RmmDeviceMemoryResource that it is * wrapping. * @param wrapped the memory resource to use for the pool. This should not be reused. * @param size the size of the pool * @param dumpLogOnFailure if true, dump memory log when running out of memory. */ public RmmArenaMemoryResource(C wrapped, long size, boolean dumpLogOnFailure) { super(wrapped); this.size = size; this.dumpLogOnFailure = dumpLogOnFailure; handle = Rmm.newArenaMemoryResource(wrapped.getHandle(), size, dumpLogOnFailure); } @Override public long getHandle() { return handle; } public long getSize() { return size; } @Override public void close() { if (handle != 0) { Rmm.releaseArenaMemoryResource(handle); handle = 0; } super.close(); } @Override public String toString() { return Long.toHexString(getHandle()) + "/ARENA(" + wrapped + ", " + size + ", " + dumpLogOnFailure + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmCudaAsyncMemoryResource.java
/* * Copyright (c) 2023-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that uses `cudaMallocAsync` and `cudaFreeAsync` for allocation and * deallocation. */ public class RmmCudaAsyncMemoryResource implements RmmDeviceMemoryResource { private final long releaseThreshold; private final long size; private long handle = 0; /** * Create a new async memory resource * @param size the initial size of the pool * @param releaseThreshold size in bytes for when memory is released back to cuda */ public RmmCudaAsyncMemoryResource(long size, long releaseThreshold) { this(size, releaseThreshold, false); } /** * Create a new async memory resource * @param size the initial size of the pool * @param releaseThreshold size in bytes for when memory is released back to cuda * @param fabric if true request peer read+write accessible fabric handles when * creating the pool */ public RmmCudaAsyncMemoryResource(long size, long releaseThreshold, boolean fabric) { this.size = size; this.releaseThreshold = releaseThreshold; handle = Rmm.newCudaAsyncMemoryResource(size, releaseThreshold, fabric); } @Override public long getHandle() { return handle; } public long getSize() { return size; } @Override public void close() { if (handle != 0) { Rmm.releaseCudaAsyncMemoryResource(handle); handle = 0; } } @Override public String toString() { return Long.toHexString(getHandle()) + "/ASYNC(" + size + ", " + releaseThreshold + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmCudaMemoryResource.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that uses `cudaMalloc` and `cudaFree` for allocation and deallocation. */ public class RmmCudaMemoryResource implements RmmDeviceMemoryResource { private long handle = 0; public RmmCudaMemoryResource() { handle = Rmm.newCudaMemoryResource(); } @Override public long getHandle() { return handle; } @Override public void close() { if (handle != 0) { Rmm.releaseCudaMemoryResource(handle); handle = 0; } } @Override public String toString() { return Long.toHexString(getHandle()) + "/CUDA()"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmDeviceMemoryResource.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A resource that allocates/deallocates device memory. This is not intended to be something that * a user will just subclass. This is intended to be a wrapper around a C++ class that RMM will * use directly. */ public interface RmmDeviceMemoryResource extends AutoCloseable { /** * Returns a pointer to the underlying C++ class that implements rmm::mr::device_memory_resource */ long getHandle(); // Remove the exception... void close(); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmEventHandler.java
/* * * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; public interface RmmEventHandler { /** * Invoked on a memory allocation failure. * @param sizeRequested number of bytes that failed to allocate * @deprecated deprecated in favor of onAllocFailure(long, boolean) * @return true if the memory allocation should be retried or false if it should fail */ default boolean onAllocFailure(long sizeRequested) { // this should not be called since it was the previous interface, // and it was abstract before, throwing by default for good measure. throw new UnsupportedOperationException( "Unexpected invocation of deprecated onAllocFailure without retry count."); } /** * Invoked after every memory allocation when debug mode is enabled. * @param size number of bytes allocated */ default void onAllocated(long size) {} /** * Invoked after every memory deallocation when debug mode is enabled. * @param size number of bytes deallocated */ default void onDeallocated(long size) {} /** * Invoked on a memory allocation failure. * @param sizeRequested number of bytes that failed to allocate * @param retryCount number of times this allocation has been retried after failure * @return true if the memory allocation should be retried or false if it should fail */ default boolean onAllocFailure(long sizeRequested, int retryCount) { // newer code should override this implementation of `onAllocFailure` to handle // `retryCount`. Otherwise, we call the prior implementation to not // break existing code. return onAllocFailure(sizeRequested); } /** * Get the memory thresholds that will trigger {@link #onAllocThreshold(long)} * to be called when one or more of the thresholds is crossed during a memory allocation. * A threshold is crossed when the total memory allocated before the RMM allocate operation * is less than a threshold value and the threshold value is less than or equal to the * total memory allocated after the RMM memory allocate operation. * @return allocate memory thresholds or null for no thresholds. */ long[] getAllocThresholds(); /** * Get the memory thresholds that will trigger {@link #onDeallocThreshold(long)} * to be called when one or more of the thresholds is crossed during a memory deallocation. * A threshold is crossed when the total memory allocated before the RMM deallocate operation * is greater than or equal to a threshold value and the threshold value is greater than the * total memory allocated after the RMM memory deallocate operation. * @return deallocate memory thresholds or null for no thresholds. */ long[] getDeallocThresholds(); /** * Invoked after an RMM memory allocate operation when an allocate threshold is crossed. * See {@link #getAllocThresholds()} for details on allocate threshold crossing. * <p>NOTE: Any exception thrown by this method will cause the corresponding allocation * that triggered the threshold callback to be released before the exception is * propagated to the application. * @param totalAllocSize total amount of memory allocated after the crossing */ void onAllocThreshold(long totalAllocSize); /** * Invoked after an RMM memory deallocation operation when a deallocate threshold is crossed. * See {@link #getDeallocThresholds()} for details on deallocate threshold crossing. * <p>NOTE: Any exception thrown by this method will be propagated to the application * after the resource that triggered the threshold was released. * @param totalAllocSize total amount of memory allocated after the crossing */ void onDeallocThreshold(long totalAllocSize); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmEventHandlerResourceAdaptor.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.util.Arrays; /** * A device memory resource that will give callbacks in specific situations. */ public class RmmEventHandlerResourceAdaptor<C extends RmmDeviceMemoryResource> extends RmmWrappingDeviceMemoryResource<C> { private long handle = 0; private final long [] allocThresholds; private final long [] deallocThresholds; private final boolean debug; /** * Create a new logging resource adaptor. * @param wrapped the memory resource to get callbacks for. This should not be reused. * @param handler the handler that will get the callbacks * @param tracker the tracking event handler * @param debug true if you want all the callbacks, else false */ public RmmEventHandlerResourceAdaptor(C wrapped, RmmTrackingResourceAdaptor<?> tracker, RmmEventHandler handler, boolean debug) { super(wrapped); this.debug = debug; allocThresholds = sortThresholds(handler.getAllocThresholds()); deallocThresholds = sortThresholds(handler.getDeallocThresholds()); handle = Rmm.newEventHandlerResourceAdaptor(wrapped.getHandle(), tracker.getHandle(), handler, allocThresholds, deallocThresholds, debug); } private static long[] sortThresholds(long[] thresholds) { if (thresholds == null) { return null; } long[] result = Arrays.copyOf(thresholds, thresholds.length); Arrays.sort(result); return result; } @Override public long getHandle() { return handle; } @Override public void close() { if (handle != 0) { Rmm.releaseEventHandlerResourceAdaptor(handle, debug); handle = 0; } super.close(); } @Override public String toString() { return Long.toHexString(getHandle()) + "/EVENT(" + wrapped + ", " + debug + ", " + Arrays.toString(allocThresholds) + ", " + Arrays.toString(deallocThresholds) + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmException.java
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Exception from RMM allocator. */ public class RmmException extends RuntimeException { RmmException(String message) { super(message); } RmmException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmLimitingResourceAdaptor.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that will limit the maximum amount allocated. */ public class RmmLimitingResourceAdaptor<C extends RmmDeviceMemoryResource> extends RmmWrappingDeviceMemoryResource<C> { private final long limit; private final long alignment; private long handle = 0; /** * Create a new limiting resource adaptor. * @param wrapped the memory resource to limit. This should not be reused. * @param limit the allocation limit in bytes * @param alignment the alignment */ public RmmLimitingResourceAdaptor(C wrapped, long limit, long alignment) { super(wrapped); this.limit = limit; this.alignment = alignment; handle = Rmm.newLimitingResourceAdaptor(wrapped.getHandle(), limit, alignment); } @Override public long getHandle() { return handle; } @Override public void close() { if (handle != 0) { Rmm.releaseLimitingResourceAdaptor(handle); handle = 0; } super.close(); } @Override public String toString() { return Long.toHexString(getHandle()) + "/LIMIT(" + wrapped + ", " + limit + ", " + alignment + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmLoggingResourceAdaptor.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that will log interactions. */ public class RmmLoggingResourceAdaptor<C extends RmmDeviceMemoryResource> extends RmmWrappingDeviceMemoryResource<C> { private long handle = 0; /** * Create a new logging resource adaptor. * @param wrapped the memory resource to log interactions with. This should not be reused. * @param conf the config of where this should be logged to * @param autoFlush should the results be flushed after each entry or not. */ public RmmLoggingResourceAdaptor(C wrapped, Rmm.LogConf conf, boolean autoFlush) { super(wrapped); if (conf.loc == Rmm.LogLoc.NONE) { throw new RmmException("Cannot initialize RmmLoggingResourceAdaptor with no logging"); } handle = Rmm.newLoggingResourceAdaptor(wrapped.getHandle(), conf.loc.internalId, conf.file == null ? null : conf.file.getAbsolutePath(), autoFlush); } @Override public long getHandle() { return handle; } @Override public void close() { if (handle != 0) { Rmm.releaseLoggingResourceAdaptor(handle); handle = 0; } super.close(); } @Override public String toString() { return Long.toHexString(getHandle()) + "/LOG(" + wrapped + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmManagedMemoryResource.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that uses `cudaMallocManaged` and `cudaFreeManaged` for allocation and * deallocation. */ public class RmmManagedMemoryResource implements RmmDeviceMemoryResource { private long handle = 0; public RmmManagedMemoryResource() { handle = Rmm.newManagedMemoryResource(); } @Override public long getHandle() { return handle; } @Override public void close() { if (handle != 0) { Rmm.releaseManagedMemoryResource(handle); handle = 0; } } @Override public String toString() { return Long.toHexString(getHandle()) + "/CUDA_MANAGED()"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmPoolMemoryResource.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that will pre-allocate a pool of resources and sub-allocate from this * pool to improve memory performance. */ public class RmmPoolMemoryResource<C extends RmmDeviceMemoryResource> extends RmmWrappingDeviceMemoryResource<C> { private long handle = 0; private final long initSize; private final long maxSize; /** * Create a new pooled memory resource taking ownership of the RmmDeviceMemoryResource that it is * wrapping. * @param wrapped the memory resource to use for the pool. This should not be reused. * @param initSize the size of the initial pool * @param maxSize the size of the maximum pool */ public RmmPoolMemoryResource(C wrapped, long initSize, long maxSize) { super(wrapped); this.initSize = initSize; this.maxSize = maxSize; handle = Rmm.newPoolMemoryResource(wrapped.getHandle(), initSize, maxSize); } public long getMaxSize() { return maxSize; } @Override public long getHandle() { return handle; } @Override public void close() { if (handle != 0) { Rmm.releasePoolMemoryResource(handle); handle = 0; } super.close(); } @Override public String toString() { return Long.toHexString(getHandle()) + "/POOL(" + wrapped + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmTrackingResourceAdaptor.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A device memory resource that will track some basic statistics about the memory usage. */ public class RmmTrackingResourceAdaptor<C extends RmmDeviceMemoryResource> extends RmmWrappingDeviceMemoryResource<C> { private long handle = 0; /** * Create a new tracking resource adaptor. * @param wrapped the memory resource to track allocations. This should not be reused. * @param alignment the alignment to apply. */ public RmmTrackingResourceAdaptor(C wrapped, long alignment) { super(wrapped); handle = Rmm.newTrackingResourceAdaptor(wrapped.getHandle(), alignment); } @Override public long getHandle() { return handle; } public long getTotalBytesAllocated() { return Rmm.nativeGetTotalBytesAllocated(getHandle()); } public long getMaxTotalBytesAllocated() { return Rmm.nativeGetMaxTotalBytesAllocated(getHandle()); } public void resetScopedMaxTotalBytesAllocated(long initValue) { Rmm.nativeResetScopedMaxTotalBytesAllocated(getHandle(), initValue); } public long getScopedMaxTotalBytesAllocated() { return Rmm.nativeGetScopedMaxTotalBytesAllocated(getHandle()); } @Override public void close() { if (handle != 0) { Rmm.releaseTrackingResourceAdaptor(handle); handle = 0; } super.close(); } @Override public String toString() { return Long.toHexString(getHandle()) + "/TRACK(" + wrapped + ")"; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RmmWrappingDeviceMemoryResource.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A resource that wraps another RmmDeviceMemoryResource */ public abstract class RmmWrappingDeviceMemoryResource<C extends RmmDeviceMemoryResource> implements RmmDeviceMemoryResource { protected C wrapped = null; public RmmWrappingDeviceMemoryResource(C wrapped) { this.wrapped = wrapped; } /** * Get the resource that this is wrapping. Be very careful when using this as the returned value * should not be added to another resource until it has been released. * @return the resource that this is wrapping. */ public C getWrapped() { return this.wrapped; } /** * Release the wrapped device memory resource and close this. * @return the wrapped DeviceMemoryResource. */ public C releaseWrapped() { C ret = this.wrapped; this.wrapped = null; close(); return ret; } @Override public void close() { if (wrapped != null) { wrapped.close(); wrapped = null; } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RollingAggregation.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * An aggregation that can be used on rolling windows. */ public final class RollingAggregation { private final Aggregation wrapped; private RollingAggregation(Aggregation wrapped) { this.wrapped = wrapped; } long createNativeInstance() { return wrapped.createNativeInstance(); } long getDefaultOutput() { return wrapped.getDefaultOutput(); } /** * Add a column to the Aggregation so it can be used on a specific column of data. * @param columnIndex the index of the column to operate on. */ public RollingAggregationOnColumn onColumn(int columnIndex) { return new RollingAggregationOnColumn(this, columnIndex); } @Override public int hashCode() { return wrapped.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof RollingAggregation) { RollingAggregation o = (RollingAggregation) other; return wrapped.equals(o.wrapped); } return false; } /** * Rolling Window Sum */ public static RollingAggregation sum() { return new RollingAggregation(Aggregation.sum()); } /** * Rolling Window Min */ public static RollingAggregation min() { return new RollingAggregation(Aggregation.min()); } /** * Rolling Window Max */ public static RollingAggregation max() { return new RollingAggregation(Aggregation.max()); } /** * Rolling Window Standard Deviation with 1 as delta degrees of freedom(DDOF). */ public static RollingAggregation standardDeviation() { return new RollingAggregation(Aggregation.standardDeviation()); } /** * Rolling Window Standard Deviation with configurable delta degrees of freedom(DDOF). */ public static RollingAggregation standardDeviation(int ddof) { return new RollingAggregation(Aggregation.standardDeviation(ddof)); } /** * Count number of valid, a.k.a. non-null, elements. */ public static RollingAggregation count() { return new RollingAggregation(Aggregation.count()); } /** * Count number of elements. * @param nullPolicy INCLUDE if nulls should be counted. EXCLUDE if only non-null values * should be counted. */ public static RollingAggregation count(NullPolicy nullPolicy) { return new RollingAggregation(Aggregation.count(nullPolicy)); } /** * Arithmetic Mean */ public static RollingAggregation mean() { return new RollingAggregation(Aggregation.mean()); } /** * Index of max element. */ public static RollingAggregation argMax() { return new RollingAggregation(Aggregation.argMax()); } /** * Index of min element. */ public static RollingAggregation argMin() { return new RollingAggregation(Aggregation.argMin()); } /** * Get the row number. */ public static RollingAggregation rowNumber() { return new RollingAggregation(Aggregation.rowNumber()); } /** * In a rolling window return the value offset entries ahead or null if it is outside of the * window. */ public static RollingAggregation lead(int offset) { return lead(offset, null); } /** * In a rolling window return the value offset entries ahead or the corresponding value from * defaultOutput if it is outside of the window. Note that this does not take any ownership of * defaultOutput and the caller mush ensure that defaultOutput remains valid during the life * time of this aggregation operation. */ public static RollingAggregation lead(int offset, ColumnVector defaultOutput) { return new RollingAggregation(Aggregation.lead(offset, defaultOutput)); } /** * In a rolling window return the value offset entries behind or null if it is outside of the * window. */ public static RollingAggregation lag(int offset) { return lag(offset, null); } /** * In a rolling window return the value offset entries behind or the corresponding value from * defaultOutput if it is outside of the window. Note that this does not take any ownership of * defaultOutput and the caller mush ensure that defaultOutput remains valid during the life * time of this aggregation operation. */ public static RollingAggregation lag(int offset, ColumnVector defaultOutput) { return new RollingAggregation(Aggregation.lag(offset, defaultOutput)); } /** * Collect the values into a list. Nulls will be skipped. */ public static RollingAggregation collectList() { return new RollingAggregation(Aggregation.collectList()); } /** * Collect the values into a list. * * @param nullPolicy Indicates whether to include/exclude nulls during collection. */ public static RollingAggregation collectList(NullPolicy nullPolicy) { return new RollingAggregation(Aggregation.collectList(nullPolicy)); } /** * Collect the values into a set. All null values will be excluded, and all nan values are regarded as * unique instances. */ public static RollingAggregation collectSet() { return new RollingAggregation(Aggregation.collectSet()); } /** * Collect the values into a set. * * @param nullPolicy Indicates whether to include/exclude nulls during collection. * @param nullEquality Flag to specify whether null entries within each list should be considered equal. * @param nanEquality Flag to specify whether NaN values in floating point column should be considered equal. */ public static RollingAggregation collectSet(NullPolicy nullPolicy, NullEquality nullEquality, NaNEquality nanEquality) { return new RollingAggregation(Aggregation.collectSet(nullPolicy, nullEquality, nanEquality)); } /** * Select the nth element from a specified window. * * @param n Indicates the index of the element to be selected from the window * @param nullPolicy Indicates whether null elements are to be skipped, or not */ public static RollingAggregation nth(int n, NullPolicy nullPolicy) { return new RollingAggregation(Aggregation.nth(n, nullPolicy)); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RollingAggregationOnColumn.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A RollingAggregation for a specific column in a table. */ public final class RollingAggregationOnColumn { protected final RollingAggregation wrapped; protected final int columnIndex; RollingAggregationOnColumn(RollingAggregation wrapped, int columnIndex) { this.wrapped = wrapped; this.columnIndex = columnIndex; } public int getColumnIndex() { return columnIndex; } public AggregationOverWindow overWindow(WindowOptions windowOptions) { return new AggregationOverWindow(this, windowOptions); } @Override public int hashCode() { return 31 * wrapped.hashCode() + columnIndex; } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof RollingAggregationOnColumn) { RollingAggregationOnColumn o = (RollingAggregationOnColumn) other; return wrapped.equals(o.wrapped) && columnIndex == o.columnIndex; } return false; } long createNativeInstance() { return wrapped.createNativeInstance(); } long getDefaultOutput() { return wrapped.getDefaultOutput(); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/RoundMode.java
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Rounding modes supported in round method. * HALF_UP : Rounding mode to round towards "nearest neighbor". If both neighbors are * equidistant, then round up. * HALF_EVEN : Rounding mode to round towards the "nearest neighbor". If both neighbors are * equidistant, round towards the even neighbor. */ public enum RoundMode { HALF_UP(0), HALF_EVEN(1); final int nativeId; RoundMode(int nativeId) { this.nativeId = nativeId; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/Scalar.java
/* * * Copyright (c) 2019-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * A single scalar value. */ public final class Scalar implements AutoCloseable, BinaryOperable { static { NativeDepsLoader.loadNativeDeps(); } private static final Logger LOG = LoggerFactory.getLogger(Scalar.class); private final DType type; private int refCount; private final OffHeapState offHeap; public static Scalar fromNull(DType type) { switch (type.typeId) { case EMPTY: case BOOL8: return new Scalar(type, makeBool8Scalar(false, false)); case INT8: return new Scalar(type, makeInt8Scalar((byte)0, false)); case UINT8: return new Scalar(type, makeUint8Scalar((byte)0, false)); case INT16: return new Scalar(type, makeInt16Scalar((short)0, false)); case UINT16: return new Scalar(type, makeUint16Scalar((short)0, false)); case INT32: return new Scalar(type, makeInt32Scalar(0, false)); case UINT32: return new Scalar(type, makeUint32Scalar(0, false)); case TIMESTAMP_DAYS: return new Scalar(type, makeTimestampDaysScalar(0, false)); case FLOAT32: return new Scalar(type, makeFloat32Scalar(0, false)); case FLOAT64: return new Scalar(type, makeFloat64Scalar(0, false)); case INT64: return new Scalar(type, makeInt64Scalar(0, false)); case UINT64: return new Scalar(type, makeUint64Scalar(0, false)); case TIMESTAMP_SECONDS: case TIMESTAMP_MILLISECONDS: case TIMESTAMP_MICROSECONDS: case TIMESTAMP_NANOSECONDS: return new Scalar(type, makeTimestampTimeScalar(type.typeId.getNativeId(), 0, false)); case STRING: return new Scalar(type, makeStringScalar(null, false)); case DURATION_DAYS: return new Scalar(type, makeDurationDaysScalar(0, false)); case DURATION_MICROSECONDS: case DURATION_MILLISECONDS: case DURATION_NANOSECONDS: case DURATION_SECONDS: return new Scalar(type, makeDurationTimeScalar(type.typeId.getNativeId(), 0, false)); case DECIMAL32: return new Scalar(type, makeDecimal32Scalar(0, type.getScale(), false)); case DECIMAL64: return new Scalar(type, makeDecimal64Scalar(0L, type.getScale(), false)); case DECIMAL128: return new Scalar(type, makeDecimal128Scalar(BigInteger.ZERO.toByteArray(), type.getScale(), false)); case LIST: throw new IllegalArgumentException("Please call 'listFromNull' to create a null list scalar."); default: throw new IllegalArgumentException("Unexpected type: " + type); } } public static Scalar fromBool(boolean value) { return new Scalar(DType.BOOL8, makeBool8Scalar(value, true)); } public static Scalar fromBool(Boolean value) { if (value == null) { return Scalar.fromNull(DType.BOOL8); } return Scalar.fromBool(value.booleanValue()); } public static Scalar fromByte(byte value) { return new Scalar(DType.INT8, makeInt8Scalar(value, true)); } public static Scalar fromByte(Byte value) { if (value == null) { return Scalar.fromNull(DType.INT8); } return Scalar.fromByte(value.byteValue()); } public static Scalar fromUnsignedByte(byte value) { return new Scalar(DType.UINT8, makeUint8Scalar(value, true)); } public static Scalar fromUnsignedByte(Byte value) { if (value == null) { return Scalar.fromNull(DType.UINT8); } return Scalar.fromUnsignedByte(value.byteValue()); } public static Scalar fromShort(short value) { return new Scalar(DType.INT16, makeInt16Scalar(value, true)); } public static Scalar fromShort(Short value) { if (value == null) { return Scalar.fromNull(DType.INT16); } return Scalar.fromShort(value.shortValue()); } public static Scalar fromUnsignedShort(short value) { return new Scalar(DType.UINT16, makeUint16Scalar(value, true)); } public static Scalar fromUnsignedShort(Short value) { if (value == null) { return Scalar.fromNull(DType.UINT16); } return Scalar.fromUnsignedShort(value.shortValue()); } /** * Returns a DURATION_DAYS scalar * @param value - days * @return - Scalar value */ public static Scalar durationDaysFromInt(int value) { return new Scalar(DType.DURATION_DAYS, makeDurationDaysScalar(value, true)); } /** * Returns a DURATION_DAYS scalar * @param value - days * @return - Scalar value */ public static Scalar durationDaysFromInt(Integer value) { if (value == null) { return Scalar.fromNull(DType.DURATION_DAYS); } return Scalar.durationDaysFromInt(value.intValue()); } public static Scalar fromInt(int value) { return new Scalar(DType.INT32, makeInt32Scalar(value, true)); } public static Scalar fromInt(Integer value) { if (value == null) { return Scalar.fromNull(DType.INT32); } return Scalar.fromInt(value.intValue()); } public static Scalar fromUnsignedInt(int value) { return new Scalar(DType.UINT32, makeUint32Scalar(value, true)); } public static Scalar fromUnsignedInt(Integer value) { if (value == null) { return Scalar.fromNull(DType.UINT32); } return Scalar.fromUnsignedInt(value.intValue()); } public static Scalar fromLong(long value) { return new Scalar(DType.INT64, makeInt64Scalar(value, true)); } public static Scalar fromLong(Long value) { if (value == null) { return Scalar.fromNull(DType.INT64); } return Scalar.fromLong(value.longValue()); } public static Scalar fromUnsignedLong(long value) { return new Scalar(DType.UINT64, makeUint64Scalar(value, true)); } public static Scalar fromUnsignedLong(Long value) { if (value == null) { return Scalar.fromNull(DType.UINT64); } return Scalar.fromUnsignedLong(value.longValue()); } public static Scalar fromFloat(float value) { return new Scalar(DType.FLOAT32, makeFloat32Scalar(value, true)); } public static Scalar fromDecimal(int scale, int unscaledValue) { long handle = makeDecimal32Scalar(unscaledValue, scale, true); return new Scalar(DType.create(DType.DTypeEnum.DECIMAL32, scale), handle); } public static Scalar fromDecimal(int scale, long unscaledValue) { long handle = makeDecimal64Scalar(unscaledValue, scale, true); return new Scalar(DType.create(DType.DTypeEnum.DECIMAL64, scale), handle); } public static Scalar fromDecimal(int scale, BigInteger unscaledValue) { byte[] unscaledValueBytes = unscaledValue.toByteArray(); byte[] finalBytes = convertDecimal128FromJavaToCudf(unscaledValueBytes); long handle = makeDecimal128Scalar(finalBytes, scale, true); return new Scalar(DType.create(DType.DTypeEnum.DECIMAL128, scale), handle); } public static Scalar fromFloat(Float value) { if (value == null) { return Scalar.fromNull(DType.FLOAT32); } return Scalar.fromFloat(value.floatValue()); } public static Scalar fromDouble(double value) { return new Scalar(DType.FLOAT64, makeFloat64Scalar(value, true)); } public static Scalar fromDouble(Double value) { if (value == null) { return Scalar.fromNull(DType.FLOAT64); } return Scalar.fromDouble(value.doubleValue()); } public static Scalar fromDecimal(BigDecimal value) { if (value == null) { return Scalar.fromNull(DType.create(DType.DTypeEnum.DECIMAL64, 0)); } DType dt = DType.fromJavaBigDecimal(value); return fromDecimal(value.unscaledValue(), dt); } public static Scalar fromDecimal(BigInteger unscaledValue, DType dt) { if (unscaledValue == null) { return Scalar.fromNull(dt); } long handle; if (dt.typeId == DType.DTypeEnum.DECIMAL32) { handle = makeDecimal32Scalar(unscaledValue.intValueExact(), dt.getScale(), true); } else if (dt.typeId == DType.DTypeEnum.DECIMAL64) { handle = makeDecimal64Scalar(unscaledValue.longValueExact(), dt.getScale(), true); } else { byte[] unscaledValueBytes = unscaledValue.toByteArray(); byte[] finalBytes = convertDecimal128FromJavaToCudf(unscaledValueBytes); handle = makeDecimal128Scalar(finalBytes, dt.getScale(), true); } return new Scalar(dt, handle); } public static Scalar timestampDaysFromInt(int value) { return new Scalar(DType.TIMESTAMP_DAYS, makeTimestampDaysScalar(value, true)); } public static Scalar timestampDaysFromInt(Integer value) { if (value == null) { return Scalar.fromNull(DType.TIMESTAMP_DAYS); } return Scalar.timestampDaysFromInt(value.intValue()); } /** * Returns a duration scalar based on the type parameter. * @param type - dtype of scalar to be returned * @param value - corresponding value for the scalar * @return - Scalar of the respective type */ public static Scalar durationFromLong(DType type, long value) { if (type.isDurationType()) { if (type.equals(DType.DURATION_DAYS)) { int intValue = (int)value; if (value != intValue) { throw new IllegalArgumentException("value too large for type " + type + ": " + value); } return durationDaysFromInt(intValue); } else { return new Scalar(type, makeDurationTimeScalar(type.typeId.getNativeId(), value, true)); } } else { throw new IllegalArgumentException("type is not a timestamp: " + type); } } /** * Returns a duration scalar based on the type parameter. * @param type - dtype of scalar to be returned * @param value - corresponding value for the scalar * @return - Scalar of the respective type */ public static Scalar durationFromLong(DType type, Long value) { if (value == null) { return Scalar.fromNull(type); } return Scalar.durationFromLong(type, value.longValue()); } public static Scalar timestampFromLong(DType type, long value) { if (type.isTimestampType()) { if (type.equals(DType.TIMESTAMP_DAYS)) { int intValue = (int)value; if (value != intValue) { throw new IllegalArgumentException("value too large for type " + type + ": " + value); } return timestampDaysFromInt(intValue); } else { return new Scalar(type, makeTimestampTimeScalar(type.typeId.getNativeId(), value, true)); } } else { throw new IllegalArgumentException("type is not a timestamp: " + type); } } public static Scalar timestampFromLong(DType type, Long value) { if (value == null) { return Scalar.fromNull(type); } return Scalar.timestampFromLong(type, value.longValue()); } public static Scalar fromString(String value) { return fromUTF8String(value == null ? null : value.getBytes(StandardCharsets.UTF_8)); } /** * Creates a String scalar from an array of UTF8 bytes. * @param value the array of UTF8 bytes * @return a String scalar */ public static Scalar fromUTF8String(byte[] value) { if (value == null) { return fromNull(DType.STRING); } return new Scalar(DType.STRING, makeStringScalar(value, true)); } /** * Creates a null scalar of list type. * * Having this special API because the element type is required to build an empty * nested column as the underlying column of the list scalar. * * @param elementType the data type of the element in the list. * @return a null scalar of list type */ public static Scalar listFromNull(HostColumnVector.DataType elementType) { try (ColumnVector col = ColumnVector.empty(elementType)) { return new Scalar(DType.LIST, makeListScalar(col.getNativeView(), false)); } } /** * Creates a scalar of list from a ColumnView. * * All the rows in the ColumnView will be copied into the Scalar. So the ColumnView * can be closed after this call completes. */ public static Scalar listFromColumnView(ColumnView list) { if (list == null) { throw new IllegalArgumentException("'list' should NOT be null." + " Please call 'listFromNull' to create a null list scalar."); } return new Scalar(DType.LIST, makeListScalar(list.getNativeView(), true)); } /** * Creates a null scalar of struct type. * * @param elementTypes data types of children in the struct * @return a null scalar of struct type */ public static Scalar structFromNull(HostColumnVector.DataType... elementTypes) { ColumnVector[] children = new ColumnVector[elementTypes.length]; long[] childHandles = new long[elementTypes.length]; RuntimeException error = null; try { for (int i = 0; i < elementTypes.length; i++) { // Build column vector having single null value rather than empty column vector, // because struct scalar requires row count of children columns == 1. children[i] = buildNullColumnVector(elementTypes[i]); childHandles[i] = children[i].getNativeView(); } return new Scalar(DType.STRUCT, makeStructScalar(childHandles, false)); } catch (RuntimeException ex) { error = ex; throw ex; } catch (Exception ex) { error = new RuntimeException(ex); throw ex; } finally { // close all empty children for (ColumnVector child : children) { // We closed all created ColumnViews when we hit null. Therefore we exit the loop. if (child == null) break; // suppress exception during the close process to ensure that all elements are closed try { child.close(); } catch (Exception ex) { if (error == null) { error = new RuntimeException(ex); continue; } error.addSuppressed(ex); } } if (error != null) throw error; } } /** * Creates a scalar of struct from a ColumnView. * * @param columns children columns of struct * @return a Struct scalar */ public static Scalar structFromColumnViews(ColumnView... columns) { if (columns == null) { throw new IllegalArgumentException("input columns should NOT be null"); } long[] columnHandles = new long[columns.length]; for (int i = 0; i < columns.length; i++) { columnHandles[i] = columns[i].getNativeView(); } return new Scalar(DType.STRUCT, makeStructScalar(columnHandles, true)); } /** * Build column vector of single row who holds a null value * * @param hostType host data type of null column vector * @return the null vector */ private static ColumnVector buildNullColumnVector(HostColumnVector.DataType hostType) { DType dt = hostType.getType(); if (!dt.isNestedType()) { try (HostColumnVector.Builder builder = HostColumnVector.builder(dt, 1)) { builder.appendNull(); try (HostColumnVector hcv = builder.build()) { return hcv.copyToDevice(); } } } else if (dt.typeId == DType.DTypeEnum.LIST) { // type of List doesn't matter here because of type erasure in Java try (HostColumnVector hcv = HostColumnVector.fromLists(hostType, (List<Integer>) null)) { return hcv.copyToDevice(); } } else if (dt.typeId == DType.DTypeEnum.STRUCT) { try (HostColumnVector hcv = HostColumnVector.fromStructs( hostType, (HostColumnVector.StructData) null)) { return hcv.copyToDevice(); } } else { throw new IllegalArgumentException("Unsupported data type: " + hostType); } } private static native void closeScalar(long scalarHandle); private static native boolean isScalarValid(long scalarHandle); private static native byte getByte(long scalarHandle); private static native short getShort(long scalarHandle); private static native int getInt(long scalarHandle); private static native long getLong(long scalarHandle); private static native byte[] getBigIntegerBytes(long scalarHandle); private static native float getFloat(long scalarHandle); private static native double getDouble(long scalarHandle); private static native byte[] getUTF8(long scalarHandle); private static native long getListAsColumnView(long scalarHandle); private static native long[] getChildrenFromStructScalar(long scalarHandle); private static native long makeBool8Scalar(boolean isValid, boolean value); private static native long makeInt8Scalar(byte value, boolean isValid); private static native long makeUint8Scalar(byte value, boolean isValid); private static native long makeInt16Scalar(short value, boolean isValid); private static native long makeUint16Scalar(short value, boolean isValid); private static native long makeInt32Scalar(int value, boolean isValid); private static native long makeUint32Scalar(int value, boolean isValid); private static native long makeInt64Scalar(long value, boolean isValid); private static native long makeUint64Scalar(long value, boolean isValid); private static native long makeFloat32Scalar(float value, boolean isValid); private static native long makeFloat64Scalar(double value, boolean isValid); private static native long makeStringScalar(byte[] value, boolean isValid); private static native long makeDurationDaysScalar(int value, boolean isValid); private static native long makeDurationTimeScalar(int dtype, long value, boolean isValid); private static native long makeTimestampDaysScalar(int value, boolean isValid); private static native long makeTimestampTimeScalar(int dtypeNativeId, long value, boolean isValid); private static native long makeDecimal32Scalar(int value, int scale, boolean isValid); private static native long makeDecimal64Scalar(long value, int scale, boolean isValid); private static native long makeDecimal128Scalar(byte[] value, int scale, boolean isValid); private static native long makeListScalar(long viewHandle, boolean isValid); private static native long makeStructScalar(long[] viewHandles, boolean isValid); private static native long repeatString(long scalarHandle, int repeatTimes); /** * Constructor to create a scalar from a native handle and a type. * * @param type The type of the scalar * @param scalarHandle The native handle (pointer address) to the scalar data */ public Scalar(DType type, long scalarHandle) { this.type = type; this.offHeap = new OffHeapState(scalarHandle); MemoryCleaner.register(this, offHeap); incRefCount(); } /** * Get the native handle (native pointer address) for the scalar. * * @return The native handle */ public long getScalarHandle() { return offHeap.scalarHandle; } /** * Increment the reference count for this scalar. You need to call close on this * to decrement the reference count again. */ public synchronized Scalar incRefCount() { if (offHeap.scalarHandle == 0) { offHeap.logRefCountDebug("INC AFTER CLOSE " + this); throw new IllegalStateException("Scalar is already closed"); } offHeap.addRef(); ++refCount; return this; } /** * Free the memory associated with a scalar. */ @Override public synchronized void close() { refCount--; offHeap.delRef(); if (refCount == 0) { offHeap.clean(false); } else if (refCount < 0) { offHeap.logRefCountDebug("double free " + this); throw new IllegalStateException("Close called too many times " + this); } } @Override public DType getType() { return type; } public boolean isValid() { return isScalarValid(getScalarHandle()); } /** * Returns the scalar value as a boolean. */ public boolean getBoolean() { return getByte(getScalarHandle()) != 0; } /** * Returns the scalar value as a byte. */ public byte getByte() { return getByte(getScalarHandle()); } /** * Returns the scalar value as a short. */ public short getShort() { return getShort(getScalarHandle()); } /** * Returns the scalar value as an int. */ public int getInt() { return getInt(getScalarHandle()); } /** * Returns the scalar value as a long. */ public long getLong() { return getLong(getScalarHandle()); } /** * Returns the BigDecimal unscaled scalar value as a byte array. */ public byte[] getBigInteger() { byte[] res = getBigIntegerBytes(getScalarHandle()); convertInPlaceToBigEndian(res); return res; } /** * Returns the scalar value as a float. */ public float getFloat() { return getFloat(getScalarHandle()); } /** * Returns the scalar value as a double. */ public double getDouble() { return getDouble(getScalarHandle()); } /** * Returns the scalar value as a BigDecimal. */ public BigDecimal getBigDecimal() { if (this.type.typeId == DType.DTypeEnum.DECIMAL32) { return BigDecimal.valueOf(getInt(), -type.getScale()); } else if (this.type.typeId == DType.DTypeEnum.DECIMAL64) { return BigDecimal.valueOf(getLong(), -type.getScale()); } else if (this.type.typeId == DType.DTypeEnum.DECIMAL128) { return new BigDecimal(new BigInteger(getBigInteger()), -type.getScale()); } throw new IllegalArgumentException("Couldn't getBigDecimal from nonDecimal scalar"); } /** * Returns the scalar value as a Java string. */ public String getJavaString() { return new String(getUTF8(getScalarHandle()), StandardCharsets.UTF_8); } /** * Returns the scalar value as UTF-8 data. */ public byte[] getUTF8() { return getUTF8(getScalarHandle()); } /** * Returns the scalar value as a ColumnView. Callers should close the returned ColumnView to * avoid memory leak. * * The returned ColumnView is only valid as long as the Scalar remains valid. If the Scalar * is closed before this ColumnView is closed, using this ColumnView will result in undefined * behavior. */ public ColumnView getListAsColumnView() { assert DType.LIST.equals(type) : "Cannot get list for the vector of type " + type; return new ColumnView(getListAsColumnView(getScalarHandle())); } /** * Fetches views of children columns from struct scalar. * The returned ColumnViews should be closed appropriately. Otherwise, a native memory leak will occur. * * @return array of column views refer to children of struct scalar */ public ColumnView[] getChildrenFromStructScalar() { assert DType.STRUCT.equals(type) : "Cannot get table for the vector of type " + type; long[] childHandles = getChildrenFromStructScalar(getScalarHandle()); return ColumnView.getColumnViewsFromPointers(childHandles); } @Override public ColumnVector binaryOp(BinaryOp op, BinaryOperable rhs, DType outType) { if (rhs instanceof ColumnView) { ColumnView cvRhs = (ColumnView) rhs; return new ColumnVector(binaryOp(this, cvRhs, op, outType)); } else { throw new IllegalArgumentException(rhs.getClass() + " is not supported as a binary op with " + "Scalar"); } } static long binaryOp(Scalar lhs, ColumnView rhs, BinaryOp op, DType outputType) { return binaryOpSV(lhs.getScalarHandle(), rhs.getNativeView(), op.nativeId, outputType.typeId.getNativeId(), outputType.getScale()); } private static native long binaryOpSV(long lhs, long rhs, int op, int dtype, int scale); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Scalar other = (Scalar) o; if (!type.equals(other.type)) return false; boolean valid = isValid(); if (valid != other.isValid()) return false; if (!valid) return true; switch (type.typeId) { case EMPTY: return true; case BOOL8: return getBoolean() == other.getBoolean(); case INT8: case UINT8: return getByte() == other.getByte(); case INT16: case UINT16: return getShort() == other.getShort(); case INT32: case UINT32: case TIMESTAMP_DAYS: case DECIMAL32: return getInt() == other.getInt(); case FLOAT32: return getFloat() == other.getFloat(); case FLOAT64: return getDouble() == other.getDouble(); case INT64: case UINT64: case TIMESTAMP_SECONDS: case TIMESTAMP_MILLISECONDS: case TIMESTAMP_MICROSECONDS: case TIMESTAMP_NANOSECONDS: case DECIMAL64: return getLong() == other.getLong(); case DECIMAL128: return getBigDecimal().equals(other.getBigDecimal()); case STRING: return Arrays.equals(getUTF8(), other.getUTF8()); case LIST: try (ColumnView viewMe = getListAsColumnView(); ColumnView viewO = other.getListAsColumnView()) { return viewMe.equals(viewO); } default: throw new IllegalStateException("Unexpected type: " + type); } } @Override public int hashCode() { int valueHash = 0; if (isValid()) { switch (type.typeId) { case EMPTY: valueHash = 0; break; case BOOL8: valueHash = getBoolean() ? 1 : 0; break; case INT8: case UINT8: valueHash = getByte(); break; case INT16: case UINT16: valueHash = getShort(); break; case INT32: case UINT32: case TIMESTAMP_DAYS: case DECIMAL32: case DURATION_DAYS: valueHash = getInt(); break; case INT64: case UINT64: case TIMESTAMP_SECONDS: case TIMESTAMP_MILLISECONDS: case TIMESTAMP_MICROSECONDS: case TIMESTAMP_NANOSECONDS: case DECIMAL64: case DURATION_MICROSECONDS: case DURATION_SECONDS: case DURATION_MILLISECONDS: case DURATION_NANOSECONDS: valueHash = Long.hashCode(getLong()); break; case FLOAT32: valueHash = Float.hashCode(getFloat()); break; case FLOAT64: valueHash = Double.hashCode(getDouble()); break; case STRING: valueHash = Arrays.hashCode(getUTF8()); break; case LIST: try (ColumnView v = getListAsColumnView()) { valueHash = v.hashCode(); } break; case DECIMAL128: valueHash = getBigDecimal().hashCode(); break; default: throw new IllegalStateException("Unknown scalar type: " + type); } } return Objects.hash(type, valueHash); } @Override public String toString() { StringBuilder sb = new StringBuilder("Scalar{type="); sb.append(type); if (getScalarHandle() != 0) { sb.append(" value="); switch (type.typeId) { case BOOL8: sb.append(getBoolean()); break; case INT8: sb.append(getByte()); break; case UINT8: sb.append(Byte.toUnsignedInt(getByte())); break; case INT16: sb.append(getShort()); break; case UINT16: sb.append(Short.toUnsignedInt(getShort())); break; case INT32: case TIMESTAMP_DAYS: sb.append(getInt()); break; case UINT32: sb.append(Integer.toUnsignedLong(getInt())); break; case INT64: case TIMESTAMP_SECONDS: case TIMESTAMP_MILLISECONDS: case TIMESTAMP_MICROSECONDS: case TIMESTAMP_NANOSECONDS: sb.append(getLong()); break; case UINT64: sb.append(Long.toUnsignedString(getLong())); break; case FLOAT32: sb.append(getFloat()); break; case FLOAT64: sb.append(getDouble()); break; case STRING: sb.append('"'); sb.append(getJavaString()); sb.append('"'); break; case DECIMAL32: // FALL THROUGH case DECIMAL64: // FALL THROUGH case DECIMAL128: sb.append(getBigDecimal()); break; case LIST: try (ColumnView v = getListAsColumnView()) { // It's not easy to pull out the elements so just a simple string of some metadata. sb.append(v.toString()); } break; default: throw new IllegalArgumentException("Unknown scalar type: " + type); } } sb.append("} (ID: "); sb.append(offHeap.id); sb.append(" "); sb.append(Long.toHexString(offHeap.scalarHandle)); sb.append(")"); return sb.toString(); } /** * Repeat the given string scalar a number of times specified by the <code>repeatTimes</code> * parameter. If that parameter has a non-positive value, an empty (valid) string scalar will be * returned. An invalid input scalar will always result in an invalid output scalar regardless * of the value of <code>repeatTimes</code>. * * @param repeatTimes The number of times the input string is copied to the output. * @return The resulting scalar containing repeated result of the current string. */ public Scalar repeatString(int repeatTimes) { return new Scalar(DType.STRING, repeatString(getScalarHandle(), repeatTimes)); } private static byte[] convertDecimal128FromJavaToCudf(byte[] bytes) { byte[] finalBytes = new byte[DType.DTypeEnum.DECIMAL128.sizeInBytes]; byte lastByte = bytes[0]; //Convert to 2's complement representation and make sure the sign bit is extended correctly byte setByte = (lastByte & 0x80) > 0 ? (byte)0xff : (byte)0x00; for(int i = bytes.length; i < finalBytes.length; i++) { finalBytes[i] = setByte; } // After setting the sign bits, reverse the rest of the bytes for endianness for(int k = 0; k < bytes.length; k++) { finalBytes[k] = bytes[bytes.length - k - 1]; } return finalBytes; } private void convertInPlaceToBigEndian(byte[] res) { assert ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); int i =0; int j = res.length -1; while (j > i) { byte tmp; tmp = res[j]; res[j] = res[i]; res[i] = tmp; j--; i++; } } /** * Holds the off-heap state of the scalar so it can be cleaned up, even if it is leaked. */ private static class OffHeapState extends MemoryCleaner.Cleaner { private long scalarHandle; OffHeapState(long scalarHandle) { this.scalarHandle = scalarHandle; } @Override protected synchronized boolean cleanImpl(boolean logErrorIfNotClean) { if (scalarHandle != 0) { if (logErrorIfNotClean) { LOG.error("A SCALAR WAS LEAKED(ID: " + id + " " + Long.toHexString(scalarHandle) + ")"); logRefCountDebug("Leaked scalar"); } try { closeScalar(scalarHandle); } finally { // Always mark the resource as freed even if an exception is thrown. // We cannot know how far it progressed before the exception, and // therefore it is unsafe to retry. scalarHandle = 0; } return true; } return false; } @Override public boolean isClean() { return scalarHandle == 0; } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ScanAggregation.java
/* * * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * An aggregation that can be used for a scan. */ public final class ScanAggregation { private final Aggregation wrapped; private ScanAggregation(Aggregation wrapped) { this.wrapped = wrapped; } long createNativeInstance() { return wrapped.createNativeInstance(); } long getDefaultOutput() { return wrapped.getDefaultOutput(); } Aggregation getWrapped() { return wrapped; } @Override public int hashCode() { return wrapped.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof ScanAggregation) { ScanAggregation o = (ScanAggregation) other; return wrapped.equals(o.wrapped); } return false; } /** * Sum Aggregation */ public static ScanAggregation sum() { return new ScanAggregation(Aggregation.sum()); } /** * Product Aggregation. */ public static ScanAggregation product() { return new ScanAggregation(Aggregation.product()); } /** * Min Aggregation */ public static ScanAggregation min() { return new ScanAggregation(Aggregation.min()); } /** * Max Aggregation */ public static ScanAggregation max() { return new ScanAggregation(Aggregation.max()); } /** * Get the row's ranking. */ public static ScanAggregation rank() { return new ScanAggregation(Aggregation.rank()); } /** * Get the row's dense ranking. */ public static ScanAggregation denseRank() { return new ScanAggregation(Aggregation.denseRank()); } /** * Get the row's percent rank. */ public static ScanAggregation percentRank() { return new ScanAggregation(Aggregation.percentRank()); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ScanType.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Scan operation type. */ public enum ScanType { /** * Include the current row in the scan. */ INCLUSIVE(true), /** * Exclude the current row from the scan. */ EXCLUSIVE(false); ScanType(boolean isInclusive) { this.isInclusive = isInclusive; } final boolean isInclusive; }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/Schema.java
/* * * Copyright (c) 2019-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * The schema of data to be read in. */ public class Schema { public static final Schema INFERRED = new Schema(); private final DType topLevelType; /** * Default value for precision value, when it is not specified or the column type is not decimal. */ private static final int UNKNOWN_PRECISION = -1; /** * Store precision for the top level column, only applicable if the column is a decimal type. * <p/> * This variable is not designed to be used by any libcudf's APIs since libcudf does not support * precisions for fixed point numbers. * Instead, it is used only to pass down the precision values from Spark's DecimalType to the * JNI level, where some JNI functions require these values to perform their operations. */ private final int topLevelPrecision; private final List<String> childNames; private final List<Schema> childSchemas; private boolean flattened = false; private String[] flattenedNames; private DType[] flattenedTypes; private int[] flattenedPrecisions; private int[] flattenedCounts; private Schema(DType topLevelType, int topLevelPrecision, List<String> childNames, List<Schema> childSchemas) { this.topLevelType = topLevelType; this.topLevelPrecision = topLevelPrecision; this.childNames = childNames; this.childSchemas = childSchemas; } private Schema(DType topLevelType, List<String> childNames, List<Schema> childSchemas) { this(topLevelType, UNKNOWN_PRECISION, childNames, childSchemas); } /** * Inferred schema. */ private Schema() { topLevelType = null; topLevelPrecision = UNKNOWN_PRECISION; childNames = null; childSchemas = null; } /** * Get the schema of a child element. Note that an inferred schema will have no children. * @param i the index of the child to read. * @return the new Schema * @throws IndexOutOfBoundsException if the index is not in the range of children. */ public Schema getChild(int i) { if (childSchemas == null) { throw new IndexOutOfBoundsException("There are 0 children in this schema"); } return childSchemas.get(i); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(topLevelType); if (topLevelType == DType.STRUCT) { sb.append("{"); if (childNames != null) { for (int i = 0; i < childNames.size(); i++) { if (i != 0) { sb.append(", "); } sb.append(childNames.get(i)); sb.append(": "); sb.append(childSchemas.get(i)); } } sb.append("}"); } else if (topLevelType == DType.LIST) { sb.append("["); if (childNames != null) { for (int i = 0; i < childNames.size(); i++) { if (i != 0) { sb.append(", "); } sb.append(childSchemas.get(i)); } } sb.append("]"); } return sb.toString(); } private void flattenIfNeeded() { if (!flattened) { int flatLen = flattenedLength(0); if (flatLen == 0) { flattenedNames = null; flattenedTypes = null; flattenedPrecisions = null; flattenedCounts = null; } else { String[] names = new String[flatLen]; DType[] types = new DType[flatLen]; int[] precisions = new int[flatLen]; int[] counts = new int[flatLen]; collectFlattened(names, types, precisions, counts, 0); flattenedNames = names; flattenedTypes = types; flattenedPrecisions = precisions; flattenedCounts = counts; } flattened = true; } } private int flattenedLength(int startingLength) { if (childSchemas != null) { for (Schema child : childSchemas) { startingLength++; startingLength = child.flattenedLength(startingLength); } } return startingLength; } private int collectFlattened(String[] names, DType[] types, int[] precisions, int[] counts, int offset) { if (childSchemas != null) { for (int i = 0; i < childSchemas.size(); i++) { Schema child = childSchemas.get(i); names[offset] = childNames.get(i); types[offset] = child.topLevelType; precisions[offset] = child.topLevelPrecision; if (child.childNames != null) { counts[offset] = child.childNames.size(); } else { counts[offset] = 0; } offset++; offset = this.childSchemas.get(i).collectFlattened(names, types, precisions, counts, offset); } } return offset; } public static Builder builder() { return new Builder(DType.STRUCT); } /** * Get names of the columns flattened from all levels in schema by depth-first traversal. * @return An array containing names of all columns in schema. */ public String[] getFlattenedColumnNames() { flattenIfNeeded(); return flattenedNames; } /** * Get names of the top level child columns in schema. * @return An array containing names of top level child columns. */ public String[] getColumnNames() { if (childNames == null) { return null; } return childNames.toArray(new String[childNames.size()]); } /** * Check if the schema is nested (i.e., top level type is LIST or STRUCT). * @return true if the schema is nested, false otherwise. */ public boolean isNested() { return childSchemas != null && childSchemas.size() > 0; } /** * This is really for a top level struct schema where it is nested, but * for things like CSV we care that it does not have any children that are also * nested. */ public boolean hasNestedChildren() { if (childSchemas != null) { for (Schema child : childSchemas) { if (child.isNested()) { return true; } } } return false; } /** * Get type ids of the columns flattened from all levels in schema by depth-first traversal. * @return An array containing type ids of all columns in schema. */ public int[] getFlattenedTypeIds() { flattenIfNeeded(); if (flattenedTypes == null) { return null; } int[] ret = new int[flattenedTypes.length]; for (int i = 0; i < flattenedTypes.length; i++) { ret[i] = flattenedTypes[i].getTypeId().nativeId; } return ret; } /** * Get scales of the columns' types flattened from all levels in schema by depth-first traversal. * @return An array containing type scales of all columns in schema. */ public int[] getFlattenedTypeScales() { flattenIfNeeded(); if (flattenedTypes == null) { return null; } int[] ret = new int[flattenedTypes.length]; for (int i = 0; i < flattenedTypes.length; i++) { ret[i] = flattenedTypes[i].getScale(); } return ret; } /** * Get decimal precisions of the columns' types flattened from all levels in schema by * depth-first traversal. * <p/> * This is used to pass down the decimal precisions from Spark to only the JNI layer, where * some JNI functions require precision values to perform their operations. * Decimal precisions should not be consumed by any libcudf's APIs since libcudf does not * support precisions for fixed point numbers. * * @return An array containing decimal precision of all columns in schema. */ public int[] getFlattenedDecimalPrecisions() { flattenIfNeeded(); return flattenedPrecisions; } /** * Get the types of the columns in schema flattened from all levels by depth-first traversal. * @return An array containing types of all columns in schema. */ public DType[] getFlattenedTypes() { flattenIfNeeded(); return flattenedTypes; } /** * Get types of the top level child columns in schema. * @return An array containing types of top level child columns. */ public DType[] getChildTypes() { if (childSchemas == null) { return null; } DType[] ret = new DType[childSchemas.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = childSchemas.get(i).topLevelType; } return ret; } /** * Get number of top level child columns in schema. * @return Number of child columns. */ public int getNumChildren() { if (childSchemas == null) { return 0; } return childSchemas.size(); } /** * Get numbers of child columns for each level in schema. * @return Numbers of child columns for all levels flattened by depth-first traversal. */ public int[] getFlattenedNumChildren() { flattenIfNeeded(); return flattenedCounts; } public DType getType() { return topLevelType; } /** * Check to see if the schema includes a struct at all. * @return true if this or any one of its descendants contains a struct, else false. */ public boolean isStructOrHasStructDescendant() { if (DType.STRUCT == topLevelType) { return true; } else if (DType.LIST == topLevelType) { return childSchemas.stream().anyMatch(Schema::isStructOrHasStructDescendant); } return false; } public HostColumnVector.DataType asHostDataType() { if (topLevelType == DType.LIST) { assert (childSchemas != null && childSchemas.size() == 1); HostColumnVector.DataType element = childSchemas.get(0).asHostDataType(); return new HostColumnVector.ListType(true, element); } else if (topLevelType == DType.STRUCT) { if (childSchemas == null) { return new HostColumnVector.StructType(true); } else { List<HostColumnVector.DataType> childTypes = childSchemas.stream().map(Schema::asHostDataType).collect(Collectors.toList()); return new HostColumnVector.StructType(true, childTypes); } } else { return new HostColumnVector.BasicType(true, topLevelType); } } public static class Builder { private final DType topLevelType; private final int topLevelPrecision; private final List<String> names; private final List<Builder> types; private Builder(DType topLevelType, int topLevelPrecision) { this.topLevelType = topLevelType; this.topLevelPrecision = topLevelPrecision; if (topLevelType == DType.STRUCT || topLevelType == DType.LIST) { // There can be children names = new ArrayList<>(); types = new ArrayList<>(); } else { names = null; types = null; } } private Builder(DType topLevelType) { this(topLevelType, UNKNOWN_PRECISION); } /** * Add a new column * @param type the type of column to add * @param name the name of the column to add (Ignored for list types) * @param precision the decimal precision, only applicable for decimal types * @return the builder for the new column. This should really only be used when the type * passed in is a LIST or a STRUCT. */ public Builder addColumn(DType type, String name, int precision) { if (names == null) { throw new IllegalStateException("A column of type " + topLevelType + " cannot have children"); } if (topLevelType == DType.LIST && names.size() > 0) { throw new IllegalStateException("A LIST column can only have one child"); } if (names.contains(name)) { throw new IllegalStateException("Cannot add duplicate names to a schema"); } Builder ret = new Builder(type, precision); types.add(ret); names.add(name); return ret; } public Builder addColumn(DType type, String name) { return addColumn(type, name, UNKNOWN_PRECISION); } /** * Adds a single column to the current schema. addColumn is preferred as it can be used * to support nested types. * @param type the type of the column. * @param name the name of the column. * @param precision the decimal precision, only applicable for decimal types. * @return this for chaining. */ public Builder column(DType type, String name, int precision) { addColumn(type, name, precision); return this; } public Builder column(DType type, String name) { addColumn(type, name, UNKNOWN_PRECISION); return this; } public Schema build() { List<Schema> children = null; if (types != null) { children = new ArrayList<>(types.size()); for (Builder b : types) { children.add(b.build()); } } return new Schema(topLevelType, topLevelPrecision, names, children); } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/SegmentedReductionAggregation.java
/* * * Copyright (c) 2022-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * An aggregation that can be used for a reduce. */ public final class SegmentedReductionAggregation { private final Aggregation wrapped; private SegmentedReductionAggregation(Aggregation wrapped) { this.wrapped = wrapped; } long createNativeInstance() { return wrapped.createNativeInstance(); } long getDefaultOutput() { return wrapped.getDefaultOutput(); } Aggregation getWrapped() { return wrapped; } @Override public int hashCode() { return wrapped.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof SegmentedReductionAggregation) { SegmentedReductionAggregation o = (SegmentedReductionAggregation) other; return wrapped.equals(o.wrapped); } return false; } /** * Sum Aggregation */ public static SegmentedReductionAggregation sum() { return new SegmentedReductionAggregation(Aggregation.sum()); } /** * Product Aggregation. */ public static SegmentedReductionAggregation product() { return new SegmentedReductionAggregation(Aggregation.product()); } /** * Min Aggregation */ public static SegmentedReductionAggregation min() { return new SegmentedReductionAggregation(Aggregation.min()); } /** * Max Aggregation */ public static SegmentedReductionAggregation max() { return new SegmentedReductionAggregation(Aggregation.max()); } /** * Any reduction. Produces a true or 1, depending on the output type, * if any of the elements in the range are true or non-zero, otherwise produces a false or 0. * Null values are skipped. */ public static SegmentedReductionAggregation any() { return new SegmentedReductionAggregation(Aggregation.any()); } /** * All reduction. Produces true or 1, depending on the output type, if all of the elements in * the range are true or non-zero, otherwise produces a false or 0. * Null values are skipped. */ public static SegmentedReductionAggregation all() { return new SegmentedReductionAggregation(Aggregation.all()); } /** * Execute a reduction using a host-side user-defined function (UDF). * @param wrapper The wrapper for the native host UDF instance. * @return A new SegmentedReductionAggregation instance */ public static SegmentedReductionAggregation hostUDF(HostUDFWrapper wrapper) { return new SegmentedReductionAggregation(Aggregation.hostUDF(wrapper)); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/StreamedTableReader.java
/* * * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Provides an interface for reading multiple tables from a single input source. */ public interface StreamedTableReader extends AutoCloseable { /** * Get the next table if available. * @return the next Table or null if done reading tables. * @throws CudfException on any error. */ Table getNextIfAvailable() throws CudfException; /** * Get the next table if available. * @param rowTarget the target number of rows to read (this is really just best effort). * @return the next Table or null if done reading tables. * @throws CudfException on any error. */ Table getNextIfAvailable(int rowTarget) throws CudfException; @Override void close() throws CudfException; }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/Table.java
/* * * Copyright (c) 2019-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import ai.rapids.cudf.HostColumnVector.BasicType; import ai.rapids.cudf.HostColumnVector.DataType; import ai.rapids.cudf.HostColumnVector.ListType; import ai.rapids.cudf.HostColumnVector.StructData; import ai.rapids.cudf.HostColumnVector.StructType; import ai.rapids.cudf.ast.CompiledExpression; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.nio.ByteBuffer; import java.util.*; /** * Class to represent a collection of ColumnVectors and operations that can be performed on them * collectively. * The refcount on the columns will be increased once they are passed in */ public final class Table implements AutoCloseable { static { NativeDepsLoader.loadNativeDeps(); } private final long rows; private long nativeHandle; private ColumnVector[] columns; /** * Table class makes a copy of the array of {@link ColumnVector}s passed to it. The class * will decrease the refcount * on itself and all its contents when closed and free resources if refcount is zero * @param columns - Array of ColumnVectors */ public Table(ColumnVector... columns) { assert columns != null && columns.length > 0 : "ColumnVectors can't be null or empty"; rows = columns[0].getRowCount(); for (ColumnVector columnVector : columns) { assert (null != columnVector) : "ColumnVectors can't be null"; assert (rows == columnVector.getRowCount()) : "All columns should have the same number of " + "rows " + columnVector.getType(); } // Since Arrays are mutable objects make a copy this.columns = new ColumnVector[columns.length]; long[] viewPointers = new long[columns.length]; for (int i = 0; i < columns.length; i++) { this.columns[i] = columns[i]; columns[i].incRefCount(); viewPointers[i] = columns[i].getNativeView(); } nativeHandle = createCudfTableView(viewPointers); } /** * Create a Table from an array of existing on device cudf::column pointers. Ownership of the * columns is transferred to the ColumnVectors held by the new Table. In the case of an exception * the columns will be deleted. * @param cudfColumns - Array of nativeHandles */ public Table(long[] cudfColumns) { assert cudfColumns != null && cudfColumns.length > 0 : "CudfColumns can't be null or empty"; this.columns = ColumnVector.getColumnVectorsFromPointers(cudfColumns); try { long[] views = new long[columns.length]; for (int i = 0; i < columns.length; i++) { views[i] = columns[i].getNativeView(); } nativeHandle = createCudfTableView(views); this.rows = columns[0].getRowCount(); } catch (Throwable t) { for (ColumnVector column : columns) { try { column.close(); } catch (Throwable s) { t.addSuppressed(s); } } throw t; } } /** * Provides a faster way to get access to the columns. Only to be used internally, and it should * never be modified in anyway. */ ColumnVector[] getColumns() { return columns; } /** Return the native table view handle for this table */ public long getNativeView() { return nativeHandle; } /** * Return the {@link ColumnVector} at the specified index. If you want to keep a reference to * the column around past the life time of the table, you will need to increment the reference * count on the column yourself. */ public ColumnVector getColumn(int index) { assert index < columns.length; return columns[index]; } public final long getRowCount() { return rows; } public final int getNumberOfColumns() { return columns.length; } @Override public void close() { if (nativeHandle != 0) { deleteCudfTable(nativeHandle); nativeHandle = 0; } if (columns != null) { for (int i = 0; i < columns.length; i++) { columns[i].close(); columns[i] = null; } columns = null; } } @Override public String toString() { return "Table{" + "columns=" + Arrays.toString(columns) + ", cudfTable=" + nativeHandle + ", rows=" + rows + '}'; } /** * Returns the Device memory buffer size. */ public long getDeviceMemorySize() { long total = 0; for (ColumnVector cv: columns) { total += cv.getDeviceMemorySize(); } return total; } /** * This method is internal and exposed purely for testing purpopses */ static Table removeNullMasksIfNeeded(Table table) { return new Table(removeNullMasksIfNeeded(table.nativeHandle)); } ///////////////////////////////////////////////////////////////////////////// // NATIVE APIs ///////////////////////////////////////////////////////////////////////////// private static native long[] removeNullMasksIfNeeded(long tableView) throws CudfException; private static native ContiguousTable[] contiguousSplit(long inputTable, int[] indices); private static native long makeChunkedPack(long inputTable, long bounceBufferSize, long tempMemoryResource); private static native long[] partition(long inputTable, long partitionView, int numberOfPartitions, int[] outputOffsets); private static native long[] hashPartition(long inputTable, int[] columnsToHash, int hashTypeId, int numberOfPartitions, int seed, int[] outputOffsets) throws CudfException; private static native long[] roundRobinPartition(long inputTable, int numberOfPartitions, int startPartition, int[] outputOffsets) throws CudfException; private static native void deleteCudfTable(long handle) throws CudfException; private static native long bound(long inputTable, long valueTable, boolean[] descFlags, boolean[] areNullsSmallest, boolean isUpperBound) throws CudfException; /** * Ugly long function to read CSV. This is a long function to avoid the overhead of reaching * into a java * object to try and pull out all of the options. If this becomes unwieldy we can change it. * @param columnNames names of all of the columns, even the ones filtered out * @param dTypeIds native types IDs of all of the columns. * @param dTypeScales scale of the type for all of the columns. * @param filterColumnNames name of the columns to read, or an empty array if we want to read * all of them * @param filePath the path of the file to read, or null if no path should be read. * @param address the address of the buffer to read from or 0 if we should not. * @param length the length of the buffer to read from. * @param headerRow the 0 based index row of the header can be -1 * @param delim character deliminator (must be ASCII). * @param quoteStyle quote style expected to be used in the input (represented as int) * @param quote character quote (must be ASCII). * @param comment character that starts a comment line (must be ASCII) use '\0' * @param nullValues values that should be treated as nulls * @param trueValues values that should be treated as boolean true * @param falseValues values that should be treated as boolean false */ private static native long[] readCSV(String[] columnNames, int[] dTypeIds, int[] dTypeScales, String[] filterColumnNames, String filePath, long address, long length, int headerRow, byte delim, int quoteStyle, byte quote, byte comment, String[] nullValues, String[] trueValues, String[] falseValues) throws CudfException; private static native long[] readCSVFromDataSource(String[] columnNames, int[] dTypeIds, int[] dTypeScales, String[] filterColumnNames, int headerRow, byte delim, int quoteStyle, byte quote, byte comment, String[] nullValues, String[] trueValues, String[] falseValues, long dataSourceHandle) throws CudfException; /** * read JSON data and return a pointer to a TableWithMeta object. */ private static native long readJSON(int[] numChildren, String[] columnNames, int[] dTypeIds, int[] dTypeScales, String filePath, long address, long length, boolean dayFirst, boolean lines, boolean recoverWithNulls, boolean normalizeSingleQuotes, boolean normalizeWhitespace, boolean mixedTypesAsStrings, boolean keepStringQuotes, boolean strictValidation, boolean allowLeadingZeros, boolean allowNonNumericNumbers, boolean allowUnquotedControl, boolean experimental, byte lineDelimiter) throws CudfException; private static native long readJSONFromDataSource(int[] numChildren, String[] columnNames, int[] dTypeIds, int[] dTypeScales, boolean dayFirst, boolean lines, boolean recoverWithNulls, boolean normalizeSingleQuotes, boolean normalizeWhitespace, boolean mixedTypesAsStrings, boolean keepStringQuotes, boolean strictValidation, boolean allowLeadingZeros, boolean allowNonNumericNumbers, boolean allowUnquotedControl, boolean experimental, byte lineDelimiter, long dsHandle) throws CudfException; private static native long readAndInferJSONFromDataSource(boolean dayFirst, boolean lines, boolean recoverWithNulls, boolean normalizeSingleQuotes, boolean normalizeWhitespace, boolean mixedTypesAsStrings, boolean keepStringQuotes, boolean strictValidation, boolean allowLeadingZeros, boolean allowNonNumericNumbers, boolean allowUnquotedControl, boolean experimental, byte lineDelimiter, long dsHandle) throws CudfException; private static native long readAndInferJSON(long address, long length, boolean dayFirst, boolean lines, boolean recoverWithNulls, boolean normalizeSingleQuotes, boolean normalizeWhitespace, boolean mixedTypesAsStrings, boolean keepStringQuotes, boolean strictValidation, boolean allowLeadingZeros, boolean allowNonNumericNumbers, boolean allowUnquotedControl, boolean experimental, byte lineDelimiter) throws CudfException; /** * Read in Parquet formatted data. * @param filterColumnNames name of the columns to read, or an empty array if we want to read * all of them * @param binaryToString whether to convert this column to String if binary * @param filePath the path of the file to read, or null if no path should be read. * @param addrsAndSizes the address and size pairs for every buffer or null for no buffers. * @param timeUnit return type of TimeStamp in units */ private static native long[] readParquet(String[] filterColumnNames, boolean[] binaryToString, String filePath, long[] addrsAndSizes, int timeUnit) throws CudfException; private static native long[] readParquetFromDataSource(String[] filterColumnNames, boolean[] binaryToString, int timeUnit, long dataSourceHandle) throws CudfException; /** * Read in Avro formatted data. * @param filterColumnNames name of the columns to read, or an empty array if we want to read * all of them * @param filePath the path of the file to read, or null if no path should be read. * @param address the address of the buffer to read from or 0 if we should not. * @param length the length of the buffer to read from. */ private static native long[] readAvro(String[] filterColumnNames, String filePath, long address, long length) throws CudfException; private static native long[] readAvroFromDataSource(String[] filterColumnNames, long dataSourceHandle) throws CudfException; /** * Setup everything to write parquet formatted data to a file. * @param columnNames names that correspond to the table columns * @param numChildren Children of the top level * @param flatNumChildren flattened list of children per column * @param nullable true if the column can have nulls else false * @param metadataKeys Metadata key names to place in the Parquet file * @param metadataValues Metadata values corresponding to metadataKeys * @param compression native compression codec ID * @param rowGroupSizeRows max #rows in a row group * @param rowGroupSizeBytes max #bytes in a row group * @param statsFreq native statistics frequency ID * @param isInt96 true if timestamp type is int96 * @param precisions precision list containing all the precisions of the decimal types in * the columns * @param isMapValues true if a column is a map * @param isBinaryValues true if a column is a binary * @param filename local output path * @return a handle that is used in later calls to writeParquetChunk and writeParquetEnd. */ private static native long writeParquetFileBegin(String[] columnNames, int numChildren, int[] flatNumChildren, boolean[] nullable, String[] metadataKeys, String[] metadataValues, int compression, int rowGroupSizeRows, long rowGroupSizeBytes, int statsFreq, boolean[] isInt96, int[] precisions, boolean[] isMapValues, boolean[] isBinaryValues, boolean[] hasParquetFieldIds, int[] parquetFieldIds, String filename) throws CudfException; /** * Setup everything to write parquet formatted data to a buffer. * @param columnNames names that correspond to the table columns * @param numChildren Children of the top level * @param flatNumChildren flattened list of children per column * @param nullable true if the column can have nulls else false * @param metadataKeys Metadata key names to place in the Parquet file * @param metadataValues Metadata values corresponding to metadataKeys * @param compression native compression codec ID * @param rowGroupSizeRows max #rows in a row group * @param rowGroupSizeBytes max #bytes in a row group * @param statsFreq native statistics frequency ID * @param isInt96 true if timestamp type is int96 * @param precisions precision list containing all the precisions of the decimal types in * the columns * @param isMapValues true if a column is a map * @param isBinaryValues true if a column is a binary * @param consumer consumer of host buffers produced. * @return a handle that is used in later calls to writeParquetChunk and writeParquetEnd. */ private static native long writeParquetBufferBegin(String[] columnNames, int numChildren, int[] flatNumChildren, boolean[] nullable, String[] metadataKeys, String[] metadataValues, int compression, int rowGroupSizeRows, long rowGroupSizeBytes, int statsFreq, boolean[] isInt96, int[] precisions, boolean[] isMapValues, boolean[] isBinaryValues, boolean[] hasParquetFieldIds, int[] parquetFieldIds, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator ) throws CudfException; /** * Write out a table to an open handle. * @param handle the handle to the writer. * @param table the table to write out. * @param tableMemSize the size of the table in bytes to help with memory allocation. */ private static native void writeParquetChunk(long handle, long table, long tableMemSize); /** * Finish writing out parquet. * @param handle the handle. Do not use again once this returns. */ private static native void writeParquetEnd(long handle); /** * Read in ORC formatted data. * @param filterColumnNames name of the columns to read, or an empty array if we want to read * all of them * @param filePath the path of the file to read, or null if no path should be read. * @param address the address of the buffer to read from or 0 for no buffer. * @param length the length of the buffer to read from. * @param usingNumPyTypes whether the parser should implicitly promote TIMESTAMP * columns to TIMESTAMP_MILLISECONDS for compatibility with NumPy. * @param timeUnit return type of TimeStamp in units * @param decimal128Columns name of the columns which are read as Decimal128 rather than Decimal64 */ private static native long[] readORC(String[] filterColumnNames, String filePath, long address, long length, boolean usingNumPyTypes, int timeUnit, String[] decimal128Columns) throws CudfException; private static native long[] readORCFromDataSource(String[] filterColumnNames, boolean usingNumPyTypes, int timeUnit, String[] decimal128Columns, long dataSourceHandle) throws CudfException; /** * Setup everything to write ORC formatted data to a file. * @param columnNames names that correspond to the table columns * @param numChildren Children of the top level * @param flatNumChildren flattened list of children per column * @param nullable true if the column can have nulls else false * @param metadataKeys Metadata key names to place in the Parquet file * @param metadataValues Metadata values corresponding to metadataKeys * @param compression native compression codec ID * @param precisions precision list containing all the precisions of the decimal types in * the columns * @param isMapValues true if a column is a map * @param filename local output path * @return a handle that is used in later calls to writeORCChunk and writeORCEnd. */ private static native long writeORCFileBegin(String[] columnNames, int numChildren, int[] flatNumChildren, boolean[] nullable, String[] metadataKeys, String[] metadataValues, int compression, int[] precisions, boolean[] isMapValues, int stripeSizeRows, String filename) throws CudfException; /** * Setup everything to write ORC formatted data to a buffer. * @param columnNames names that correspond to the table columns * @param numChildren Children of the top level * @param flatNumChildren flattened list of children per column * @param nullable true if the column can have nulls else false * @param metadataKeys Metadata key names to place in the Parquet file * @param metadataValues Metadata values corresponding to metadataKeys * @param compression native compression codec ID * @param precisions precision list containing all the precisions of the decimal types in * the columns * @param isMapValues true if a column is a map * @param consumer consumer of host buffers produced. * @return a handle that is used in later calls to writeORCChunk and writeORCEnd. */ private static native long writeORCBufferBegin(String[] columnNames, int numChildren, int[] flatNumChildren, boolean[] nullable, String[] metadataKeys, String[] metadataValues, int compression, int[] precisions, boolean[] isMapValues, int stripeSizeRows, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator ) throws CudfException; /** * Write out a table to an open handle. * @param handle the handle to the writer. * @param table the table to write out. * @param tableMemSize the size of the table in bytes to help with memory allocation. */ private static native void writeORCChunk(long handle, long table, long tableMemSize); /** * Finish writing out ORC. * @param handle the handle. Do not use again once this returns. */ private static native void writeORCEnd(long handle); /** * Setup everything to write Arrow IPC formatted data to a file. * @param columnNames names that correspond to the table columns * @param filename local output path * @return a handle that is used in later calls to writeArrowIPCChunk and writeArrowIPCEnd. */ private static native long writeArrowIPCFileBegin(String[] columnNames, String filename); /** * Setup everything to write Arrow IPC formatted data to a buffer. * @param columnNames names that correspond to the table columns * @param consumer consumer of host buffers produced. * @param hostMemoryAllocator allocator for host memory buffers. * @return a handle that is used in later calls to writeArrowIPCChunk and writeArrowIPCEnd. */ private static native long writeArrowIPCBufferBegin(String[] columnNames, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator); /** * Convert a cudf table to an arrow table handle. * @param handle the handle to the writer. * @param tableHandle the table to convert */ private static native long convertCudfToArrowTable(long handle, long tableHandle); /** * Write out a table to an open handle. * @param handle the handle to the writer. * @param arrowHandle the arrow table to write out. * @param maxChunkSize the maximum number of rows that could * be written out in a single chunk. Generally this setting will be * followed unless for some reason the arrow table is not a single group. * This can happen when reading arrow data, but not when converting from * cudf. */ private static native void writeArrowIPCArrowChunk(long handle, long arrowHandle, long maxChunkSize); /** * Finish writing out Arrow IPC. * @param handle the handle. Do not use again once this returns. */ private static native void writeArrowIPCEnd(long handle); /** * Setup everything to read an Arrow IPC formatted data file. * @param path local input path * @return a handle that is used in later calls to readArrowIPCChunk and readArrowIPCEnd. */ private static native long readArrowIPCFileBegin(String path); /** * Setup everything to read Arrow IPC formatted data from a provider. * @param provider the class that will provide the data. * @return a handle that is used in later calls to readArrowIPCChunk and readArrowIPCEnd. */ private static native long readArrowIPCBufferBegin(ArrowReaderWrapper provider); /** * Read the next chunk/table of data. * @param handle the handle that is holding the data. * @param rowTarget the number of rows to read. * @return a pointer to an arrow table handle. */ private static native long readArrowIPCChunkToArrowTable(long handle, int rowTarget); /** * Close the arrow table handle returned by readArrowIPCChunkToArrowTable or * convertCudfToArrowTable */ private static native void closeArrowTable(long arrowHandle); /** * Convert an arrow table handle as returned by readArrowIPCChunkToArrowTable to * cudf table handles. */ private static native long[] convertArrowTableToCudf(long arrowHandle); /** * Finish reading the data. We are done. * @param handle the handle to clean up. */ private static native void readArrowIPCEnd(long handle); private static native long[] groupByAggregate(long inputTable, int[] keyIndices, int[] aggColumnsIndices, long[] aggInstances, boolean ignoreNullKeys, boolean keySorted, boolean[] keysDescending, boolean[] keysNullSmallest) throws CudfException; private static native long[] groupByScan(long inputTable, int[] keyIndices, int[] aggColumnsIndices, long[] aggInstances, boolean ignoreNullKeys, boolean keySorted, boolean[] keysDescending, boolean[] keysNullSmallest) throws CudfException; private static native long[] groupByReplaceNulls(long inputTable, int[] keyIndices, int[] replaceColumnsIndices, boolean[] isPreceding, boolean ignoreNullKeys, boolean keySorted, boolean[] keysDescending, boolean[] keysNullSmallest) throws CudfException; private static native long[] rollingWindowAggregate( long inputTable, int[] keyIndices, long[] defaultOutputs, int[] aggColumnsIndices, long[] aggInstances, int[] minPeriods, int[] preceding, int[] following, boolean[] unboundedPreceding, boolean[] unboundedFollowing, boolean ignoreNullKeys) throws CudfException; private static native long[] rangeRollingWindowAggregate(long inputTable, int[] keyIndices, int[] orderByIndices, boolean[] isOrderByAscending, int[] aggColumnsIndices, long[] aggInstances, int[] minPeriods, long[] preceding, long[] following, int[] precedingRangeExtent, int[] followingRangeExtent, boolean ignoreNullKeys) throws CudfException; private static native long sortOrder(long inputTable, long[] sortKeys, boolean[] isDescending, boolean[] areNullsSmallest) throws CudfException; private static native long[] orderBy(long inputTable, long[] sortKeys, boolean[] isDescending, boolean[] areNullsSmallest) throws CudfException; private static native long[] merge(long[] tableHandles, int[] sortKeyIndexes, boolean[] isDescending, boolean[] areNullsSmallest) throws CudfException; private static native long[] leftJoinGatherMaps(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long[] leftDistinctJoinGatherMap(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long leftJoinRowCount(long leftTable, long rightHashJoin) throws CudfException; private static native long[] leftHashJoinGatherMaps(long leftTable, long rightHashJoin) throws CudfException; private static native long[] leftHashJoinGatherMapsWithCount(long leftTable, long rightHashJoin, long outputRowCount) throws CudfException; private static native long[] innerJoinGatherMaps(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long[] innerDistinctJoinGatherMaps(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long innerJoinRowCount(long table, long hashJoin) throws CudfException; private static native long[] innerHashJoinGatherMaps(long table, long hashJoin) throws CudfException; private static native long[] innerHashJoinGatherMapsWithCount(long table, long hashJoin, long outputRowCount) throws CudfException; private static native long[] fullJoinGatherMaps(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long fullJoinRowCount(long leftTable, long rightHashJoin) throws CudfException; private static native long[] fullHashJoinGatherMaps(long leftTable, long rightHashJoin) throws CudfException; private static native long[] fullHashJoinGatherMapsWithCount(long leftTable, long rightHashJoin, long outputRowCount) throws CudfException; private static native long[] leftSemiJoinGatherMap(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long[] leftAntiJoinGatherMap(long leftKeys, long rightKeys, boolean compareNullsEqual) throws CudfException; private static native long conditionalLeftJoinRowCount(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalLeftJoinGatherMaps(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalLeftJoinGatherMapsWithCount(long leftTable, long rightTable, long condition, long rowCount) throws CudfException; private static native long conditionalInnerJoinRowCount(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalInnerJoinGatherMaps(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalInnerJoinGatherMapsWithCount(long leftTable, long rightTable, long condition, long rowCount) throws CudfException; private static native long[] conditionalFullJoinGatherMaps(long leftTable, long rightTable, long condition) throws CudfException; private static native long conditionalLeftSemiJoinRowCount(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalLeftSemiJoinGatherMap(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalLeftSemiJoinGatherMapWithCount(long leftTable, long rightTable, long condition, long rowCount) throws CudfException; private static native long conditionalLeftAntiJoinRowCount(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalLeftAntiJoinGatherMap(long leftTable, long rightTable, long condition) throws CudfException; private static native long[] conditionalLeftAntiJoinGatherMapWithCount(long leftTable, long rightTable, long condition, long rowCount) throws CudfException; private static native long[] mixedLeftJoinSize(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] mixedLeftJoinGatherMaps(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] mixedLeftJoinGatherMapsWithSize(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual, long outputRowCount, long matchesColumnView); private static native long[] mixedInnerJoinSize(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] mixedInnerJoinGatherMaps(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] mixedInnerJoinGatherMapsWithSize(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual, long outputRowCount, long matchesColumnView); private static native long[] mixedFullJoinGatherMaps(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] mixedLeftSemiJoinGatherMap(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] mixedLeftAntiJoinGatherMap(long leftKeysTable, long rightKeysTable, long leftConditionTable, long rightConditionTable, long condition, boolean compareNullsEqual); private static native long[] crossJoin(long leftTable, long rightTable) throws CudfException; private static native long[] concatenate(long[] cudfTablePointers) throws CudfException; private static native long interleaveColumns(long input); private static native long[] filter(long input, long mask); private static native long[] dropDuplicates(long nativeHandle, int[] keyColumns, int keepValue, boolean nullsEqual) throws CudfException; private static native long[] gather(long tableHandle, long gatherView, boolean checkBounds); private static native long[] scatterTable(long srcTableHandle, long scatterView, long targetTableHandle) throws CudfException; private static native long[] scatterScalars(long[] srcScalarHandles, long scatterView, long targetTableHandle) throws CudfException; private static native long[] repeatStaticCount(long tableHandle, int count); private static native long[] repeatColumnCount(long tableHandle, long columnHandle); private static native long rowBitCount(long tableHandle) throws CudfException; private static native long[] explode(long tableHandle, int index); private static native long[] explodePosition(long tableHandle, int index); private static native long[] explodeOuter(long tableHandle, int index); private static native long[] explodeOuterPosition(long tableHandle, int index); private static native long createCudfTableView(long[] nativeColumnViewHandles); private static native long[] columnViewsFromPacked(ByteBuffer metadata, long dataAddress); private static native ContigSplitGroupByResult contiguousSplitGroups(long inputTable, int[] keyIndices, boolean ignoreNullKeys, boolean keySorted, boolean[] keysDescending, boolean[] keysNullSmallest, boolean genUniqKeys); private static native long[] sample(long tableHandle, long n, boolean replacement, long seed); private static native int distinctCount(long handle, boolean nullsEqual); ///////////////////////////////////////////////////////////////////////////// // TABLE CREATION APIs ///////////////////////////////////////////////////////////////////////////// /** * Read a CSV file using the default CSVOptions. * @param schema the schema of the file. You may use Schema.INFERRED to infer the schema. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readCSV(Schema schema, File path) { return readCSV(schema, CSVOptions.DEFAULT, path); } /** * Read a CSV file. * @param schema the schema of the file. You may use Schema.INFERRED to infer the schema. * @param opts various CSV parsing options. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readCSV(Schema schema, CSVOptions opts, File path) { if (schema.hasNestedChildren()) { throw new IllegalArgumentException("CSV does not support nested types"); } return new Table( readCSV(schema.getFlattenedColumnNames(), schema.getFlattenedTypeIds(), schema.getFlattenedTypeScales(), opts.getIncludeColumnNames(), path.getAbsolutePath(), 0, 0, opts.getHeaderRow(), opts.getDelim(), opts.getQuoteStyle().nativeId, opts.getQuote(), opts.getComment(), opts.getNullValues(), opts.getTrueValues(), opts.getFalseValues())); } /** * Read CSV formatted data using the default CSVOptions. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param buffer raw UTF8 formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readCSV(Schema schema, byte[] buffer) { return readCSV(schema, CSVOptions.DEFAULT, buffer, 0, buffer.length); } /** * Read CSV formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various CSV parsing options. * @param buffer raw UTF8 formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readCSV(Schema schema, CSVOptions opts, byte[] buffer) { return readCSV(schema, opts, buffer, 0, buffer.length); } /** * Read CSV formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various CSV parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param hostMemoryAllocator allocator for host memory buffers * @return the data parsed as a table on the GPU. */ public static Table readCSV(Schema schema, CSVOptions opts, byte[] buffer, long offset, long len, HostMemoryAllocator hostMemoryAllocator) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.length - offset; assert offset >= 0 && offset < buffer.length; try (HostMemoryBuffer newBuf = hostMemoryAllocator.allocate(len)) { newBuf.setBytes(0, buffer, offset, len); return readCSV(schema, opts, newBuf, 0, len); } } public static Table readCSV(Schema schema, CSVOptions opts, byte[] buffer, long offset, long len) { return readCSV(schema, opts, buffer, offset, len, DefaultHostMemoryAllocator.get()); } /** * Read CSV formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various CSV parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU. */ public static Table readCSV(Schema schema, CSVOptions opts, HostMemoryBuffer buffer, long offset, long len) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.getLength() - offset; assert offset >= 0 && offset < buffer.length; if (schema.hasNestedChildren()) { throw new IllegalArgumentException("CSV does not support nested types"); } return new Table(readCSV(schema.getFlattenedColumnNames(), schema.getFlattenedTypeIds(), schema.getFlattenedTypeScales(), opts.getIncludeColumnNames(), null, buffer.getAddress() + offset, len, opts.getHeaderRow(), opts.getDelim(), opts.getQuoteStyle().nativeId, opts.getQuote(), opts.getComment(), opts.getNullValues(), opts.getTrueValues(), opts.getFalseValues())); } public static Table readCSV(Schema schema, CSVOptions opts, DataSource ds) { long dsHandle = DataSourceHelper.createWrapperDataSource(ds); try { if (schema.hasNestedChildren()) { throw new IllegalArgumentException("CSV does not support nested types"); } return new Table(readCSVFromDataSource(schema.getFlattenedColumnNames(), schema.getFlattenedTypeIds(), schema.getFlattenedTypeScales(), opts.getIncludeColumnNames(), opts.getHeaderRow(), opts.getDelim(), opts.getQuoteStyle().nativeId, opts.getQuote(), opts.getComment(), opts.getNullValues(), opts.getTrueValues(), opts.getFalseValues(), dsHandle)); } finally { DataSourceHelper.destroyWrapperDataSource(dsHandle); } } private static native void writeCSVToFile(long table, String[] columnNames, boolean includeHeader, String rowDelimiter, byte fieldDelimiter, String nullValue, String trueValue, String falseValue, int quoteStyle, String outputPath) throws CudfException; public void writeCSVToFile(CSVWriterOptions options, String outputPath) { writeCSVToFile(nativeHandle, options.getColumnNames(), options.getIncludeHeader(), options.getRowDelimiter(), options.getFieldDelimiter(), options.getNullValue(), options.getTrueValue(), options.getFalseValue(), options.getQuoteStyle().nativeId, outputPath); } private static native long startWriteCSVToBuffer(String[] columnNames, boolean includeHeader, String rowDelimiter, byte fieldDelimiter, String nullValue, String trueValue, String falseValue, int quoteStyle, HostBufferConsumer buffer, HostMemoryAllocator hostMemoryAllocator ) throws CudfException; private static native void writeCSVChunkToBuffer(long writerHandle, long tableHandle); private static native void endWriteCSVToBuffer(long writerHandle); private static class CSVTableWriter extends TableWriter { private HostBufferConsumer consumer; private CSVTableWriter(CSVWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { super(startWriteCSVToBuffer(options.getColumnNames(), options.getIncludeHeader(), options.getRowDelimiter(), options.getFieldDelimiter(), options.getNullValue(), options.getTrueValue(), options.getFalseValue(), options.getQuoteStyle().nativeId, consumer, hostMemoryAllocator)); this.consumer = consumer; } @Override public void write(Table table) { if (writerHandle == 0) { throw new IllegalStateException("Writer was already closed"); } writeCSVChunkToBuffer(writerHandle, table.nativeHandle); } @Override public void close() throws CudfException { if (writerHandle != 0) { endWriteCSVToBuffer(writerHandle); writerHandle = 0; } if (consumer != null) { consumer.done(); consumer = null; } } } public static TableWriter getCSVBufferWriter(CSVWriterOptions options, HostBufferConsumer bufferConsumer, HostMemoryAllocator hostMemoryAllocator) { return new CSVTableWriter(options, bufferConsumer, hostMemoryAllocator); } public static TableWriter getCSVBufferWriter(CSVWriterOptions options, HostBufferConsumer bufferConsumer) { return getCSVBufferWriter(options, bufferConsumer, DefaultHostMemoryAllocator.get()); } /** * Read a JSON file using the default JSONOptions. * @param schema the schema of the file. You may use Schema.INFERRED to infer the schema. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readJSON(Schema schema, File path) { return readJSON(schema, JSONOptions.DEFAULT, path); } /** * Read JSON formatted data using the default JSONOptions. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param buffer raw UTF8 formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readJSON(Schema schema, byte[] buffer) { return readJSON(schema, JSONOptions.DEFAULT, buffer, 0, buffer.length); } /** * Read JSON formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param buffer raw UTF8 formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readJSON(Schema schema, JSONOptions opts, byte[] buffer) { return readJSON(schema, opts, buffer, 0, buffer.length); } /** * Read a JSON file. * @param schema the schema of the file. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readJSON(Schema schema, JSONOptions opts, File path) { try (TableWithMeta twm = new TableWithMeta( readJSON(schema.getFlattenedNumChildren(), schema.getFlattenedColumnNames(), schema.getFlattenedTypeIds(), schema.getFlattenedTypeScales(), path.getAbsolutePath(), 0, 0, opts.isDayFirst(), opts.isLines(), opts.isRecoverWithNull(), opts.isNormalizeSingleQuotes(), opts.isNormalizeWhitespace(), opts.isMixedTypesAsStrings(), opts.keepStringQuotes(), opts.strictValidation(), opts.leadingZerosAllowed(), opts.nonNumericNumbersAllowed(), opts.unquotedControlChars(), opts.experimental(), opts.getLineDelimiter()))) { return twm.releaseTable(); } } /** * Read JSON formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param hostMemoryAllocator allocator for host memory buffers * @return the data parsed as a table on the GPU. */ public static Table readJSON(Schema schema, JSONOptions opts, byte[] buffer, long offset, long len, HostMemoryAllocator hostMemoryAllocator) { return readJSON(schema, opts, buffer, offset, len, hostMemoryAllocator, -1); } /** * Read JSON formatted data. * * @deprecated This method is deprecated since emptyRowCount is not used. Use the method without * emptyRowCount instead. * * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param hostMemoryAllocator allocator for host memory buffers * @param emptyRowCount the number of rows to return if no columns were read. * @return the data parsed as a table on the GPU. */ @SuppressWarnings("unused") public static Table readJSON(Schema schema, JSONOptions opts, byte[] buffer, long offset, long len, HostMemoryAllocator hostMemoryAllocator, int emptyRowCount) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.length - offset; assert offset >= 0 && offset < buffer.length; try (HostMemoryBuffer newBuf = hostMemoryAllocator.allocate(len)) { newBuf.setBytes(0, buffer, offset, len); return readJSON(schema, opts, newBuf, 0, len); } } @SuppressWarnings("unused") public static Table readJSON(Schema schema, JSONOptions opts, byte[] buffer, long offset, long len, int emptyRowCount) { return readJSON(schema, opts, buffer, offset, len, DefaultHostMemoryAllocator.get()); } public static Table readJSON(Schema schema, JSONOptions opts, byte[] buffer, long offset, long len) { return readJSON(schema, opts, buffer, offset, len, DefaultHostMemoryAllocator.get()); } /** * Read JSON formatted data and infer the column names and schema. * @param opts various JSON parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU and the metadata for the table returned. */ public static TableWithMeta readJSON(JSONOptions opts, HostMemoryBuffer buffer, long offset, long len) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.length - offset; assert offset >= 0 && offset < buffer.length; return new TableWithMeta(readAndInferJSON(buffer.getAddress() + offset, len, opts.isDayFirst(), opts.isLines(), opts.isRecoverWithNull(), opts.isNormalizeSingleQuotes(), opts.isNormalizeWhitespace(), opts.isMixedTypesAsStrings(), opts.keepStringQuotes(), opts.strictValidation(), opts.leadingZerosAllowed(), opts.nonNumericNumbersAllowed(), opts.unquotedControlChars(), opts.experimental(), opts.getLineDelimiter())); } /** * Read JSON formatted data and infer the column names and schema. * @param opts various JSON parsing options. * @return the data parsed as a table on the GPU and the metadata for the table returned. */ public static TableWithMeta readAndInferJSON(JSONOptions opts, DataSource ds) { long dsHandle = DataSourceHelper.createWrapperDataSource(ds); try { TableWithMeta twm = new TableWithMeta(readAndInferJSONFromDataSource(opts.isDayFirst(), opts.isLines(), opts.isRecoverWithNull(), opts.isNormalizeSingleQuotes(), opts.isNormalizeWhitespace(), opts.isMixedTypesAsStrings(), opts.keepStringQuotes(), opts.strictValidation(), opts.leadingZerosAllowed(), opts.nonNumericNumbersAllowed(), opts.unquotedControlChars(), opts.experimental(), opts.getLineDelimiter(), dsHandle)); return twm; } finally { DataSourceHelper.destroyWrapperDataSource(dsHandle); } } /** * Read JSON formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU. */ public static Table readJSON(Schema schema, JSONOptions opts, HostMemoryBuffer buffer, long offset, long len) { return readJSON(schema, opts, buffer, offset, len, -1); } /** * Read JSON formatted data. * * @deprecated This method is deprecated since emptyRowCount is not used. Use the method without * emptyRowCount instead. * * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param buffer raw UTF8 formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param emptyRowCount the number of rows to use if no columns were found. * @return the data parsed as a table on the GPU. */ @SuppressWarnings("unused") public static Table readJSON(Schema schema, JSONOptions opts, HostMemoryBuffer buffer, long offset, long len, int emptyRowCount) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.length - offset; assert offset >= 0 && offset < buffer.length; try (TableWithMeta twm = new TableWithMeta(readJSON( schema.getFlattenedNumChildren(), schema.getFlattenedColumnNames(), schema.getFlattenedTypeIds(), schema.getFlattenedTypeScales(), null, buffer.getAddress() + offset, len, opts.isDayFirst(), opts.isLines(), opts.isRecoverWithNull(), opts.isNormalizeSingleQuotes(), opts.isNormalizeWhitespace(), opts.isMixedTypesAsStrings(), opts.keepStringQuotes(), opts.strictValidation(), opts.leadingZerosAllowed(), opts.nonNumericNumbersAllowed(), opts.unquotedControlChars(), opts.experimental(), opts.getLineDelimiter()))) { return twm.releaseTable(); } } /** * Read JSON formatted data. * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param ds the DataSource to read from. * @return the data parsed as a table on the GPU. */ public static Table readJSON(Schema schema, JSONOptions opts, DataSource ds) { return readJSON(schema, opts, ds, -1); } /** * Read JSON formatted data. * * @deprecated This method is deprecated since emptyRowCount is not used. Use the method without * emptyRowCount instead. * * @param schema the schema of the data. You may use Schema.INFERRED to infer the schema. * @param opts various JSON parsing options. * @param ds the DataSource to read from. * @param emptyRowCount the number of rows to return if no columns were read. * @return the data parsed as a table on the GPU. */ @SuppressWarnings("unused") public static Table readJSON(Schema schema, JSONOptions opts, DataSource ds, int emptyRowCount) { long dsHandle = DataSourceHelper.createWrapperDataSource(ds); try (TableWithMeta twm = new TableWithMeta(readJSONFromDataSource(schema.getFlattenedNumChildren(), schema.getFlattenedColumnNames(), schema.getFlattenedTypeIds(), schema.getFlattenedTypeScales(), opts.isDayFirst(), opts.isLines(), opts.isRecoverWithNull(), opts.isNormalizeSingleQuotes(), opts.isNormalizeWhitespace(), opts.isMixedTypesAsStrings(), opts.keepStringQuotes(), opts.strictValidation(), opts.leadingZerosAllowed(), opts.nonNumericNumbersAllowed(), opts.unquotedControlChars(), opts.experimental(), opts.getLineDelimiter(), dsHandle))) { return twm.releaseTable(); } finally { DataSourceHelper.destroyWrapperDataSource(dsHandle); } } /** * Read a Parquet file using the default ParquetOptions. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readParquet(File path) { return readParquet(ParquetOptions.DEFAULT, path); } /** * Read a Parquet file. * @param opts various parquet parsing options. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, File path) { return new Table(readParquet(opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), path.getAbsolutePath(), null, opts.timeUnit().typeId.getNativeId())); } /** * Read parquet formatted data. * @param buffer raw parquet formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readParquet(byte[] buffer) { return readParquet(ParquetOptions.DEFAULT, buffer, 0, buffer.length); } /** * Read parquet formatted data. * @param opts various parquet parsing options. * @param buffer raw parquet formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, byte[] buffer) { return readParquet(opts, buffer, 0, buffer.length); } /** * Read parquet formatted data. * @param opts various parquet parsing options. * @param buffer raw parquet formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param hostMemoryAllocator allocator for host memory buffers * @return the data parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, byte[] buffer, long offset, long len, HostMemoryAllocator hostMemoryAllocator) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.length - offset; assert offset >= 0 && offset < buffer.length; try (HostMemoryBuffer newBuf = hostMemoryAllocator.allocate(len)) { newBuf.setBytes(0, buffer, offset, len); return readParquet(opts, newBuf, 0, len); } } /** * Read parquet formatted data. * @param opts various parquet parsing options. * @param buffer raw parquet formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, byte[] buffer, long offset, long len) { return readParquet(opts, buffer, offset, len, DefaultHostMemoryAllocator.get()); } /** * Read parquet formatted data. * @param opts various parquet parsing options. * @param buffer raw parquet formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, HostMemoryBuffer buffer, long offset, long len) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.getLength() - offset; assert offset >= 0 && offset < buffer.length; long[] addrsSizes = new long[]{ buffer.getAddress() + offset, len }; return new Table(readParquet(opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), null, addrsSizes, opts.timeUnit().typeId.getNativeId())); } /** * Read parquet formatted data. * @param opts various parquet parsing options. * @param buffers Buffers containing the Parquet data. The buffers are logically concatenated * in order to construct the file being read. * @return the data parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, HostMemoryBuffer... buffers) { assert buffers.length > 0; long[] addrsSizes = new long[buffers.length * 2]; for (int i = 0; i < buffers.length; i++) { addrsSizes[i * 2] = buffers[i].getAddress(); addrsSizes[(i * 2) + 1] = buffers[i].getLength(); } return new Table(readParquet(opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), null, addrsSizes, opts.timeUnit().typeId.getNativeId())); } /** * Read parquet formatted data. * @param opts various parquet parsing options. * @param ds custom datasource to provide the Parquet file data * @return the data parsed as a table on the GPU. */ public static Table readParquet(ParquetOptions opts, DataSource ds) { long dataSourceHandle = DataSourceHelper.createWrapperDataSource(ds); try { return new Table(readParquetFromDataSource(opts.getIncludeColumnNames(), opts.getReadBinaryAsString(), opts.timeUnit().typeId.getNativeId(), dataSourceHandle)); } finally { DataSourceHelper.destroyWrapperDataSource(dataSourceHandle); } } /** * Read an Avro file using the default AvroOptions. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readAvro(File path) { return readAvro(AvroOptions.DEFAULT, path); } /** * Read an Avro file. * @param opts various Avro parsing options. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readAvro(AvroOptions opts, File path) { return new Table(readAvro(opts.getIncludeColumnNames(), path.getAbsolutePath(), 0, 0)); } /** * Read Avro formatted data. * @param buffer raw Avro formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readAvro(byte[] buffer) { return readAvro(AvroOptions.DEFAULT, buffer, 0, buffer.length); } /** * Read Avro formatted data. * @param opts various Avro parsing options. * @param buffer raw Avro formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readAvro(AvroOptions opts, byte[] buffer) { return readAvro(opts, buffer, 0, buffer.length); } /** * Read Avro formatted data. * @param opts various Avro parsing options. * @param buffer raw Avro formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param hostMemoryAllocator allocator for host memory buffers * @return the data parsed as a table on the GPU. */ public static Table readAvro(AvroOptions opts, byte[] buffer, long offset, long len, HostMemoryAllocator hostMemoryAllocator) { assert offset >= 0 && offset < buffer.length; assert len <= buffer.length - offset; len = len > 0 ? len : buffer.length - offset; try (HostMemoryBuffer newBuf = hostMemoryAllocator.allocate(len)) { newBuf.setBytes(0, buffer, offset, len); return readAvro(opts, newBuf, 0, len); } } public static Table readAvro(AvroOptions opts, byte[] buffer, long offset, long len) { return readAvro(opts, buffer, offset, len, DefaultHostMemoryAllocator.get()); } /** * Read Avro formatted data. * @param opts various Avro parsing options. * @param buffer raw Avro formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU. */ public static Table readAvro(AvroOptions opts, HostMemoryBuffer buffer, long offset, long len) { assert offset >= 0 && offset < buffer.length; assert len <= buffer.length - offset; len = len > 0 ? len : buffer.length - offset; return new Table(readAvro(opts.getIncludeColumnNames(), null, buffer.getAddress() + offset, len)); } public static Table readAvro(AvroOptions opts, DataSource ds) { long dataSourceHandle = DataSourceHelper.createWrapperDataSource(ds); try { return new Table(readAvroFromDataSource(opts.getIncludeColumnNames(), dataSourceHandle)); } finally { DataSourceHelper.destroyWrapperDataSource(dataSourceHandle); } } /** * Read a ORC file using the default ORCOptions. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readORC(File path) { return readORC(ORCOptions.DEFAULT, path); } /** * Read a ORC file. * @param opts ORC parsing options. * @param path the local file to read. * @return the file parsed as a table on the GPU. */ public static Table readORC(ORCOptions opts, File path) { return new Table(readORC(opts.getIncludeColumnNames(), path.getAbsolutePath(), 0, 0, opts.usingNumPyTypes(), opts.timeUnit().typeId.getNativeId(), opts.getDecimal128Columns())); } /** * Read ORC formatted data. * @param buffer raw ORC formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readORC(byte[] buffer) { return readORC(ORCOptions.DEFAULT, buffer, 0, buffer.length); } /** * Read ORC formatted data. * @param opts various ORC parsing options. * @param buffer raw ORC formatted bytes. * @return the data parsed as a table on the GPU. */ public static Table readORC(ORCOptions opts, byte[] buffer) { return readORC(opts, buffer, 0, buffer.length); } /** * Read ORC formatted data. * @param opts various ORC parsing options. * @param buffer raw ORC formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @param hostMemoryAllocator allocator for host memory buffers * @return the data parsed as a table on the GPU. */ public static Table readORC(ORCOptions opts, byte[] buffer, long offset, long len, HostMemoryAllocator hostMemoryAllocator) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.length - offset; assert offset >= 0 && offset < buffer.length; try (HostMemoryBuffer newBuf = hostMemoryAllocator.allocate(len)) { newBuf.setBytes(0, buffer, offset, len); return readORC(opts, newBuf, 0, len); } } public static Table readORC(ORCOptions opts, byte[] buffer, long offset, long len) { return readORC(opts, buffer, offset, len, DefaultHostMemoryAllocator.get()); } /** * Read ORC formatted data. * @param opts various ORC parsing options. * @param buffer raw ORC formatted bytes. * @param offset the starting offset into buffer. * @param len the number of bytes to parse. * @return the data parsed as a table on the GPU. */ public static Table readORC(ORCOptions opts, HostMemoryBuffer buffer, long offset, long len) { if (len <= 0) { len = buffer.length - offset; } assert len > 0; assert len <= buffer.getLength() - offset; assert offset >= 0 && offset < buffer.length; return new Table(readORC(opts.getIncludeColumnNames(), null, buffer.getAddress() + offset, len, opts.usingNumPyTypes(), opts.timeUnit().typeId.getNativeId(), opts.getDecimal128Columns())); } public static Table readORC(ORCOptions opts, DataSource ds) { long dataSourceHandle = DataSourceHelper.createWrapperDataSource(ds); try { return new Table(readORCFromDataSource(opts.getIncludeColumnNames(), opts.usingNumPyTypes(), opts.timeUnit().typeId.getNativeId(), opts.getDecimal128Columns(), dataSourceHandle)); } finally { DataSourceHelper.destroyWrapperDataSource(dataSourceHandle); } } private static class ParquetTableWriter extends TableWriter { HostBufferConsumer consumer; private ParquetTableWriter(ParquetWriterOptions options, File outputFile) { super(writeParquetFileBegin(options.getFlatColumnNames(), options.getTopLevelChildren(), options.getFlatNumChildren(), options.getFlatIsNullable(), options.getMetadataKeys(), options.getMetadataValues(), options.getCompressionType().nativeId, options.getRowGroupSizeRows(), options.getRowGroupSizeBytes(), options.getStatisticsFrequency().nativeId, options.getFlatIsTimeTypeInt96(), options.getFlatPrecision(), options.getFlatIsMap(), options.getFlatIsBinary(), options.getFlatHasParquetFieldId(), options.getFlatParquetFieldId(), outputFile.getAbsolutePath())); this.consumer = null; } private ParquetTableWriter(ParquetWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { super(writeParquetBufferBegin(options.getFlatColumnNames(), options.getTopLevelChildren(), options.getFlatNumChildren(), options.getFlatIsNullable(), options.getMetadataKeys(), options.getMetadataValues(), options.getCompressionType().nativeId, options.getRowGroupSizeRows(), options.getRowGroupSizeBytes(), options.getStatisticsFrequency().nativeId, options.getFlatIsTimeTypeInt96(), options.getFlatPrecision(), options.getFlatIsMap(), options.getFlatIsBinary(), options.getFlatHasParquetFieldId(), options.getFlatParquetFieldId(), consumer, hostMemoryAllocator)); this.consumer = consumer; } @Override public void write(Table table) { if (writerHandle == 0) { throw new IllegalStateException("Writer was already closed"); } writeParquetChunk(writerHandle, table.nativeHandle, table.getDeviceMemorySize()); } @Override public void close() throws CudfException { if (writerHandle != 0) { writeParquetEnd(writerHandle); } writerHandle = 0; if (consumer != null) { consumer.done(); consumer = null; } } } /** * Get a table writer to write parquet data to a file. * @param options the parquet writer options. * @param outputFile where to write the file. * @return a table writer to use for writing out multiple tables. */ public static TableWriter writeParquetChunked(ParquetWriterOptions options, File outputFile) { return new ParquetTableWriter(options, outputFile); } /** * Get a table writer to write parquet data and handle each chunk with a callback. * @param options the parquet writer options. * @param consumer a class that will be called when host buffers are ready with parquet * formatted data in them. * @param hostMemoryAllocator allocator for host memory buffers * @return a table writer to use for writing out multiple tables. */ public static TableWriter writeParquetChunked(ParquetWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { return new ParquetTableWriter(options, consumer, hostMemoryAllocator); } public static TableWriter writeParquetChunked(ParquetWriterOptions options, HostBufferConsumer consumer) { return writeParquetChunked(options, consumer, DefaultHostMemoryAllocator.get()); } /** * This is an evolving API and most likely be removed in future releases. Please use with the * caveat that this will not exist in the near future. * @param options the Parquet writer options. * @param consumer a class that will be called when host buffers are ready with Parquet * formatted data in them. * @param hostMemoryAllocator allocator for host memory buffers * @param columnViews ColumnViews to write to Parquet */ public static void writeColumnViewsToParquet(ParquetWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator, ColumnView... columnViews) { assert columnViews != null && columnViews.length > 0 : "ColumnViews can't be null or empty"; long rows = columnViews[0].getRowCount(); for (ColumnView columnView : columnViews) { assert (null != columnView) : "ColumnViews can't be null"; assert (rows == columnView.getRowCount()) : "All columns should have the same number of " + "rows " + columnView.getType(); } // Since Arrays are mutable objects make a copy long[] viewPointers = new long[columnViews.length]; for (int i = 0; i < columnViews.length; i++) { viewPointers[i] = columnViews[i].getNativeView(); } long nativeHandle = createCudfTableView(viewPointers); try { try ( ParquetTableWriter writer = new ParquetTableWriter(options, consumer, hostMemoryAllocator) ) { long total = 0; for (ColumnView cv : columnViews) { total += cv.getDeviceMemorySize(); } writeParquetChunk(writer.writerHandle, nativeHandle, total); } } finally { deleteCudfTable(nativeHandle); } } public static void writeColumnViewsToParquet(ParquetWriterOptions options, HostBufferConsumer consumer, ColumnView... columnViews) { writeColumnViewsToParquet(options, consumer, DefaultHostMemoryAllocator.get(), columnViews); } private static class ORCTableWriter extends TableWriter { HostBufferConsumer consumer; private ORCTableWriter(ORCWriterOptions options, File outputFile) { super(writeORCFileBegin(options.getFlatColumnNames(), options.getTopLevelChildren(), options.getFlatNumChildren(), options.getFlatIsNullable(), options.getMetadataKeys(), options.getMetadataValues(), options.getCompressionType().nativeId, options.getFlatPrecision(), options.getFlatIsMap(), options.getStripeSizeRows(), outputFile.getAbsolutePath())); this.consumer = null; } private ORCTableWriter(ORCWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { super(writeORCBufferBegin(options.getFlatColumnNames(), options.getTopLevelChildren(), options.getFlatNumChildren(), options.getFlatIsNullable(), options.getMetadataKeys(), options.getMetadataValues(), options.getCompressionType().nativeId, options.getFlatPrecision(), options.getFlatIsMap(), options.getStripeSizeRows(), consumer, hostMemoryAllocator)); this.consumer = consumer; } @Override public void write(Table table) { if (writerHandle == 0) { throw new IllegalStateException("Writer was already closed"); } writeORCChunk(writerHandle, table.nativeHandle, table.getDeviceMemorySize()); } @Override public void close() throws CudfException { if (writerHandle != 0) { writeORCEnd(writerHandle); } writerHandle = 0; if (consumer != null) { consumer.done(); consumer = null; } } } /** * Get a table writer to write ORC data to a file. * @param options the ORC writer options. * @param outputFile where to write the file. * @return a table writer to use for writing out multiple tables. */ public static TableWriter writeORCChunked(ORCWriterOptions options, File outputFile) { return new ORCTableWriter(options, outputFile); } /** * Get a table writer to write ORC data and handle each chunk with a callback. * @param options the ORC writer options. * @param consumer a class that will be called when host buffers are ready with ORC * formatted data in them. * @param hostMemoryAllocator allocator for host memory buffers * @return a table writer to use for writing out multiple tables. */ public static TableWriter writeORCChunked(ORCWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { return new ORCTableWriter(options, consumer, hostMemoryAllocator); } public static TableWriter writeORCChunked(ORCWriterOptions options, HostBufferConsumer consumer) { return writeORCChunked(options, consumer, DefaultHostMemoryAllocator.get()); } private static class ArrowIPCTableWriter extends TableWriter { private final ArrowIPCWriterOptions.DoneOnGpu callback; private HostBufferConsumer consumer; private long maxChunkSize; private ArrowIPCTableWriter(ArrowIPCWriterOptions options, File outputFile) { super(writeArrowIPCFileBegin(options.getColumnNames(), outputFile.getAbsolutePath())); this.callback = options.getCallback(); this.consumer = null; this.maxChunkSize = options.getMaxChunkSize(); } private ArrowIPCTableWriter(ArrowIPCWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { super(writeArrowIPCBufferBegin(options.getColumnNames(), consumer, hostMemoryAllocator)); this.callback = options.getCallback(); this.consumer = consumer; this.maxChunkSize = options.getMaxChunkSize(); } @Override public void write(Table table) { if (writerHandle == 0) { throw new IllegalStateException("Writer was already closed"); } long arrowHandle = convertCudfToArrowTable(writerHandle, table.nativeHandle); try { callback.doneWithTheGpu(table); writeArrowIPCArrowChunk(writerHandle, arrowHandle, maxChunkSize); } finally { closeArrowTable(arrowHandle); } } @Override public void close() throws CudfException { if (writerHandle != 0) { writeArrowIPCEnd(writerHandle); } writerHandle = 0; if (consumer != null) { consumer.done(); consumer = null; } } } /** * Get a table writer to write arrow IPC data to a file. * @param options the arrow IPC writer options. * @param outputFile where to write the file. * @return a table writer to use for writing out multiple tables. */ public static TableWriter writeArrowIPCChunked(ArrowIPCWriterOptions options, File outputFile) { return new ArrowIPCTableWriter(options, outputFile); } /** * Get a table writer to write arrow IPC data and handle each chunk with a callback. * @param options the arrow IPC writer options. * @param consumer a class that will be called when host buffers are ready with arrow IPC * formatted data in them. * @param hostMemoryAllocator allocator for host memory buffers * @return a table writer to use for writing out multiple tables. */ public static TableWriter writeArrowIPCChunked(ArrowIPCWriterOptions options, HostBufferConsumer consumer, HostMemoryAllocator hostMemoryAllocator) { return new ArrowIPCTableWriter(options, consumer, hostMemoryAllocator); } public static TableWriter writeArrowIPCChunked(ArrowIPCWriterOptions options, HostBufferConsumer consumer) { return writeArrowIPCChunked(options, consumer, DefaultHostMemoryAllocator.get()); } private static class ArrowReaderWrapper implements AutoCloseable { private HostBufferProvider provider; private HostMemoryBuffer buffer; private final HostMemoryAllocator hostMemoryAllocator; private ArrowReaderWrapper(HostBufferProvider provider, HostMemoryAllocator hostMemoryAllocator) { this.provider = provider; this.hostMemoryAllocator = hostMemoryAllocator; buffer = this.hostMemoryAllocator.allocate(10 * 1024 * 1024, false); } // Called From JNI public long readInto(long dstAddress, long amount) { long totalRead = 0; long amountLeft = amount; while (amountLeft > 0) { long amountToCopy = Math.min(amountLeft, buffer.length); long amountRead = provider.readInto(buffer, amountToCopy); buffer.copyToMemory(totalRead + dstAddress, amountRead); amountLeft -= amountRead; totalRead += amountRead; if (amountRead < amountToCopy) { // EOF amountLeft = 0; } } return totalRead; } @Override public void close() { if (provider != null) { provider.close(); provider = null; } if (buffer != null) { buffer.close(); buffer = null; } } } private static class ArrowIPCStreamedTableReader implements StreamedTableReader { private final ArrowIPCOptions.NeedGpu callback; private long handle; private ArrowReaderWrapper provider; private ArrowIPCStreamedTableReader(ArrowIPCOptions options, File inputFile) { this.provider = null; this.handle = readArrowIPCFileBegin( inputFile.getAbsolutePath()); this.callback = options.getCallback(); } private ArrowIPCStreamedTableReader(ArrowIPCOptions options, HostBufferProvider provider, HostMemoryAllocator hostMemoryAllocator) { this.provider = new ArrowReaderWrapper(provider, hostMemoryAllocator); this.handle = readArrowIPCBufferBegin(this.provider); this.callback = options.getCallback(); } @Override public Table getNextIfAvailable() throws CudfException { // In this case rowTarget is the minimum number of rows to read. return getNextIfAvailable(1); } @Override public Table getNextIfAvailable(int rowTarget) throws CudfException { long arrowTableHandle = readArrowIPCChunkToArrowTable(handle, rowTarget); try { if (arrowTableHandle == 0) { return null; } callback.needTheGpu(); return new Table(convertArrowTableToCudf(arrowTableHandle)); } finally { closeArrowTable(arrowTableHandle); } } @Override public void close() throws CudfException { if (handle != 0) { readArrowIPCEnd(handle); } handle = 0; if (provider != null) { provider.close(); provider = null; } } } /** * Get a reader that will return tables. * @param options options for reading. * @param inputFile the file to read the Arrow IPC formatted data from * @return a reader. */ public static StreamedTableReader readArrowIPCChunked(ArrowIPCOptions options, File inputFile) { return new ArrowIPCStreamedTableReader(options, inputFile); } /** * Get a reader that will return tables. * @param inputFile the file to read the Arrow IPC formatted data from * @return a reader. */ public static StreamedTableReader readArrowIPCChunked(File inputFile) { return readArrowIPCChunked(ArrowIPCOptions.DEFAULT, inputFile); } /** * Get a reader that will return tables. * @param options options for reading. * @param provider what will provide the data being read. * @return a reader. */ public static StreamedTableReader readArrowIPCChunked(ArrowIPCOptions options, HostBufferProvider provider, HostMemoryAllocator hostMemoryAllocator) { return new ArrowIPCStreamedTableReader(options, provider, hostMemoryAllocator); } public static StreamedTableReader readArrowIPCChunked(ArrowIPCOptions options, HostBufferProvider provider) { return new ArrowIPCStreamedTableReader(options, provider, DefaultHostMemoryAllocator.get()); } /** * Get a reader that will return tables. * @param provider what will provide the data being read. * @return a reader. */ public static StreamedTableReader readArrowIPCChunked(HostBufferProvider provider) { return readArrowIPCChunked(ArrowIPCOptions.DEFAULT, provider); } /** * Concatenate multiple tables together to form a single table. * The schema of each table (i.e.: number of columns and types of each column) must be equal * across all tables and will determine the schema of the resulting table. */ public static Table concatenate(Table... tables) { if (tables.length < 2) { throw new IllegalArgumentException("concatenate requires 2 or more tables"); } int numColumns = tables[0].getNumberOfColumns(); long[] tableHandles = new long[tables.length]; for (int i = 0; i < tables.length; ++i) { tableHandles[i] = tables[i].nativeHandle; assert tables[i].getNumberOfColumns() == numColumns : "all tables must have the same schema"; } return new Table(concatenate(tableHandles)); } /** * Interleave all columns into a single column. Columns must all have the same data type and length. * * Example: * ``` * input = [[A1, A2, A3], [B1, B2, B3]] * return = [A1, B1, A2, B2, A3, B3] * ``` * * @return The interleaved columns as a single column */ public ColumnVector interleaveColumns() { assert this.getNumberOfColumns() >= 2 : ".interleaveColumns() operation requires at least 2 columns"; return new ColumnVector(interleaveColumns(this.nativeHandle)); } /** * Repeat each row of this table count times. * @param count the number of times to repeat each row. * @return the new Table. */ public Table repeat(int count) { return new Table(repeatStaticCount(this.nativeHandle, count)); } /** * Create a new table by repeating each row of this table. The number of * repetitions of each row is defined by the corresponding value in counts. * @param counts the number of times to repeat each row. Cannot have nulls, must be an * Integer type, and must have one entry for each row in the table. * @return the new Table. * @throws CudfException on any error. */ public Table repeat(ColumnView counts) { return new Table(repeatColumnCount(this.nativeHandle, counts.getNativeView())); } /** * Partition this table using the mapping in partitionMap. partitionMap must be an integer * column. The number of rows in partitionMap must be the same as this table. Each row * in the map will indicate which partition the rows in the table belong to. * @param partitionMap the partitions for each row. * @param numberOfPartitions number of partitions * @return {@link PartitionedTable} Table that exposes a limited functionality of the * {@link Table} class */ public PartitionedTable partition(ColumnView partitionMap, int numberOfPartitions) { int[] partitionOffsets = new int[numberOfPartitions]; return new PartitionedTable(new Table(partition( getNativeView(), partitionMap.getNativeView(), partitionOffsets.length, partitionOffsets)), partitionOffsets); } /** * Find smallest indices in a sorted table where values should be inserted to maintain order. * <pre> * Example: * * Single column: * idx 0 1 2 3 4 * inputTable = { 10, 20, 20, 30, 50 } * valuesTable = { 20 } * result = { 1 } * * Multi Column: * idx 0 1 2 3 4 * inputTable = {{ 10, 20, 20, 20, 20 }, * { 5.0, .5, .5, .7, .7 }, * { 90, 77, 78, 61, 61 }} * valuesTable = {{ 20 }, * { .7 }, * { 61 }} * result = { 3 } * </pre> * The input table and the values table need to be non-empty (row count > 0) * @param areNullsSmallest per column, true if nulls are assumed smallest * @param valueTable the table of values to find insertion locations for * @param descFlags per column indicates the ordering, true if descending. * @return ColumnVector with lower bound indices for all rows in valueTable */ public ColumnVector lowerBound(boolean[] areNullsSmallest, Table valueTable, boolean[] descFlags) { assertForBounds(valueTable); return new ColumnVector(bound(this.nativeHandle, valueTable.nativeHandle, descFlags, areNullsSmallest, false)); } /** * Find smallest indices in a sorted table where values should be inserted to maintain order. * This is a convenience method. It pulls out the columns indicated by the args and sets up the * ordering properly to call `lowerBound`. * @param valueTable the table of values to find insertion locations for * @param args the sort order used to sort this table. * @return ColumnVector with lower bound indices for all rows in valueTable */ public ColumnVector lowerBound(Table valueTable, OrderByArg... args) { boolean[] areNullsSmallest = new boolean[args.length]; boolean[] descFlags = new boolean[args.length]; ColumnVector[] inputColumns = new ColumnVector[args.length]; ColumnVector[] searchColumns = new ColumnVector[args.length]; for (int i = 0; i < args.length; i++) { areNullsSmallest[i] = args[i].isNullSmallest; descFlags[i] = args[i].isDescending; inputColumns[i] = columns[args[i].index]; searchColumns[i] = valueTable.columns[args[i].index]; } try (Table input = new Table(inputColumns); Table search = new Table(searchColumns)) { return input.lowerBound(areNullsSmallest, search, descFlags); } } /** * Find largest indices in a sorted table where values should be inserted to maintain order. * Given a sorted table return the upper bound. * <pre> * Example: * * Single column: * idx 0 1 2 3 4 * inputTable = { 10, 20, 20, 30, 50 } * valuesTable = { 20 } * result = { 3 } * * Multi Column: * idx 0 1 2 3 4 * inputTable = {{ 10, 20, 20, 20, 20 }, * { 5.0, .5, .5, .7, .7 }, * { 90, 77, 78, 61, 61 }} * valuesTable = {{ 20 }, * { .7 }, * { 61 }} * result = { 5 } * </pre> * The input table and the values table need to be non-empty (row count > 0) * @param areNullsSmallest per column, true if nulls are assumed smallest * @param valueTable the table of values to find insertion locations for * @param descFlags per column indicates the ordering, true if descending. * @return ColumnVector with upper bound indices for all rows in valueTable */ public ColumnVector upperBound(boolean[] areNullsSmallest, Table valueTable, boolean[] descFlags) { assertForBounds(valueTable); return new ColumnVector(bound(this.nativeHandle, valueTable.nativeHandle, descFlags, areNullsSmallest, true)); } /** * Find largest indices in a sorted table where values should be inserted to maintain order. * This is a convenience method. It pulls out the columns indicated by the args and sets up the * ordering properly to call `upperBound`. * @param valueTable the table of values to find insertion locations for * @param args the sort order used to sort this table. * @return ColumnVector with upper bound indices for all rows in valueTable */ public ColumnVector upperBound(Table valueTable, OrderByArg... args) { boolean[] areNullsSmallest = new boolean[args.length]; boolean[] descFlags = new boolean[args.length]; ColumnVector[] inputColumns = new ColumnVector[args.length]; ColumnVector[] searchColumns = new ColumnVector[args.length]; for (int i = 0; i < args.length; i++) { areNullsSmallest[i] = args[i].isNullSmallest; descFlags[i] = args[i].isDescending; inputColumns[i] = columns[args[i].index]; searchColumns[i] = valueTable.columns[args[i].index]; } try (Table input = new Table(inputColumns); Table search = new Table(searchColumns)) { return input.upperBound(areNullsSmallest, search, descFlags); } } private void assertForBounds(Table valueTable) { assert this.getRowCount() != 0 : "Input table cannot be empty"; assert valueTable.getRowCount() != 0 : "Value table cannot be empty"; for (int i = 0; i < Math.min(columns.length, valueTable.columns.length); i++) { assert valueTable.columns[i].getType().equals(this.getColumn(i).getType()) : "Input and values tables' data types do not match"; } } /** * Joins two tables all of the left against all of the right. Be careful as this * gets very big and you can easily use up all of the GPUs memory. * @param right the right table * @return the joined table. The order of the columns returned will be left columns, * right columns. */ public Table crossJoin(Table right) { return new Table(Table.crossJoin(this.nativeHandle, right.nativeHandle)); } ///////////////////////////////////////////////////////////////////////////// // TABLE MANIPULATION APIs ///////////////////////////////////////////////////////////////////////////// /** * Get back a gather map that can be used to sort the data. This allows you to sort by data * that does not appear in the final result and not pay the cost of gathering the data that * is only needed for sorting. * @param args what order to sort the data by * @return a gather map */ public ColumnVector sortOrder(OrderByArg... args) { long[] sortKeys = new long[args.length]; boolean[] isDescending = new boolean[args.length]; boolean[] areNullsSmallest = new boolean[args.length]; for (int i = 0; i < args.length; i++) { int index = args[i].index; assert (index >= 0 && index < columns.length) : "index is out of range 0 <= " + index + " < " + columns.length; isDescending[i] = args[i].isDescending; areNullsSmallest[i] = args[i].isNullSmallest; sortKeys[i] = columns[index].getNativeView(); } return new ColumnVector(sortOrder(nativeHandle, sortKeys, isDescending, areNullsSmallest)); } /** * Orders the table using the sortkeys returning a new allocated table. The caller is * responsible for cleaning up * the {@link ColumnVector} returned as part of the output {@link Table} * <p> * Example usage: orderBy(true, OrderByArg.asc(0), OrderByArg.desc(3)...); * @param args Suppliers to initialize sortKeys. * @return Sorted Table */ public Table orderBy(OrderByArg... args) { long[] sortKeys = new long[args.length]; boolean[] isDescending = new boolean[args.length]; boolean[] areNullsSmallest = new boolean[args.length]; for (int i = 0; i < args.length; i++) { int index = args[i].index; assert (index >= 0 && index < columns.length) : "index is out of range 0 <= " + index + " < " + columns.length; isDescending[i] = args[i].isDescending; areNullsSmallest[i] = args[i].isNullSmallest; sortKeys[i] = columns[index].getNativeView(); } return new Table(orderBy(nativeHandle, sortKeys, isDescending, areNullsSmallest)); } /** * Merge multiple already sorted tables keeping the sort order the same. * This is a more efficient version of concatenate followed by orderBy, but requires that * the input already be sorted. * @param tables the tables that should be merged. * @param args the ordering of the tables. Should match how they were sorted * initially. * @return a combined sorted table. */ public static Table merge(Table[] tables, OrderByArg... args) { assert tables.length > 0; long[] tableHandles = new long[tables.length]; Table first = tables[0]; assert args.length <= first.columns.length; for (int i = 0; i < tables.length; i++) { Table t = tables[i]; assert t != null; assert t.columns.length == first.columns.length; tableHandles[i] = t.nativeHandle; } int[] sortKeyIndexes = new int[args.length]; boolean[] isDescending = new boolean[args.length]; boolean[] areNullsSmallest = new boolean[args.length]; for (int i = 0; i < args.length; i++) { int index = args[i].index; assert (index >= 0 && index < first.columns.length) : "index is out of range 0 <= " + index + " < " + first.columns.length; isDescending[i] = args[i].isDescending; areNullsSmallest[i] = args[i].isNullSmallest; sortKeyIndexes[i] = index; } return new Table(merge(tableHandles, sortKeyIndexes, isDescending, areNullsSmallest)); } /** * Merge multiple already sorted tables keeping the sort order the same. * This is a more efficient version of concatenate followed by orderBy, but requires that * the input already be sorted. * @param tables the tables that should be merged. * @param args the ordering of the tables. Should match how they were sorted * initially. * @return a combined sorted table. */ public static Table merge(List<Table> tables, OrderByArg... args) { return merge(tables.toArray(new Table[tables.size()]), args); } /** * Returns aggregate operations grouped by columns provided in indices * @param groupByOptions Options provided in the builder * @param indices columns to be considered for groupBy */ public GroupByOperation groupBy(GroupByOptions groupByOptions, int... indices) { return groupByInternal(groupByOptions, indices); } /** * Returns aggregate operations grouped by columns provided in indices * with default options as below: * - null is considered as key while grouping. * - keys are not presorted. * - empty key order array. * - empty null order array. * @param indices columns to be considered for groupBy */ public GroupByOperation groupBy(int... indices) { return groupByInternal(GroupByOptions.builder().withIgnoreNullKeys(false).build(), indices); } private GroupByOperation groupByInternal(GroupByOptions groupByOptions, int[] indices) { int[] operationIndicesArray = copyAndValidate(indices); return new GroupByOperation(this, groupByOptions, operationIndicesArray); } /** * Round-robin partition a table into the specified number of partitions. The first row is placed * in the specified starting partition, the next row is placed in the next partition, and so on. * When the last partition is reached then next partition is partition 0 and the algorithm * continues until all rows have been placed in partitions, evenly distributing the rows * among the partitions. * @param numberOfPartitions - number of partitions to use * @param startPartition - starting partition index (i.e.: where first row is placed). * @return - {@link PartitionedTable} - Table that exposes a limited functionality of the * {@link Table} class */ public PartitionedTable roundRobinPartition(int numberOfPartitions, int startPartition) { int[] partitionOffsets = new int[numberOfPartitions]; return new PartitionedTable(new Table(Table.roundRobinPartition(nativeHandle, numberOfPartitions, startPartition, partitionOffsets)), partitionOffsets); } public TableOperation onColumns(int... indices) { int[] operationIndicesArray = copyAndValidate(indices); return new TableOperation(this, operationIndicesArray); } private int[] copyAndValidate(int[] indices) { int[] operationIndicesArray = new int[indices.length]; for (int i = 0; i < indices.length; i++) { operationIndicesArray[i] = indices[i]; assert operationIndicesArray[i] >= 0 && operationIndicesArray[i] < columns.length : "operation index is out of range 0 <= " + operationIndicesArray[i] + " < " + columns.length; } return operationIndicesArray; } /** * Filters this table using a column of boolean values as a mask, returning a new one. * <p> * Given a mask column, each element `i` from the input columns * is copied to the output columns if the corresponding element `i` in the mask is * non-null and `true`. This operation is stable: the input order is preserved. * <p> * This table and mask columns must have the same number of rows. * <p> * The output table has size equal to the number of elements in boolean_mask * that are both non-null and `true`. * <p> * If the original table row count is zero, there is no error, and an empty table is returned. * @param mask column of type {@link DType#BOOL8} used as a mask to filter * the input column * @return table containing copy of all elements of this table passing * the filter defined by the boolean mask */ public Table filter(ColumnView mask) { assert mask.getType().equals(DType.BOOL8) : "Mask column must be of type BOOL8"; assert getRowCount() == 0 || getRowCount() == mask.getRowCount() : "Mask column has incorrect size"; return new Table(filter(nativeHandle, mask.getNativeView())); } /** * Enum to specify which of duplicate rows/elements will be copied to the output. */ public enum DuplicateKeepOption { KEEP_ANY(0), KEEP_FIRST(1), KEEP_LAST(2), KEEP_NONE(3); final int keepValue; DuplicateKeepOption(int keepValue) { this.keepValue = keepValue; } } /** * Copy rows of the current table to an output table such that duplicate rows in the key columns * are ignored (i.e., only one row from the duplicate ones will be copied). These keys columns are * a subset of the current table columns and their indices are specified by an input array. * * The order of rows in the output table is not specified. * * @param keyColumns Array of indices representing key columns from the current table. * @param keep Option specifying to keep any, first, last, or none of the found duplicates. * @param nullsEqual Flag to denote whether nulls are treated as equal when comparing rows of the * key columns to check for uniqueness. * * @return Table with unique keys. */ public Table dropDuplicates(int[] keyColumns, DuplicateKeepOption keep, boolean nullsEqual) { assert keyColumns.length >= 1 : "Input keyColumns must contain indices of at least one column"; return new Table(dropDuplicates(nativeHandle, keyColumns, keep.keepValue, nullsEqual)); } /** * Count how many rows in the table are distinct from one another. * @param nullsEqual if nulls should be considered equal to each other or not. */ public int distinctCount(NullEquality nullsEqual) { return distinctCount(nativeHandle, nullsEqual.nullsEqual); } /** * Count how many rows in the table are distinct from one another. * Nulls are considered to be equal to one another. */ public int distinctCount() { return distinctCount(nativeHandle, true); } /** * Split a table at given boundaries, but the result of each split has memory that is laid out * in a contiguous range of memory. This allows for us to optimize copying the data in a single * operation. * * <code> * Example: * input: [{10, 12, 14, 16, 18, 20, 22, 24, 26, 28}, * {50, 52, 54, 56, 58, 60, 62, 64, 66, 68}] * splits: {2, 5, 9} * output: [{{10, 12}, {14, 16, 18}, {20, 22, 24, 26}, {28}}, * {{50, 52}, {54, 56, 58}, {60, 62, 64, 66}, {68}}] * </code> * @param indices A vector of indices where to make the split * @return The tables split at those points. NOTE: It is the responsibility of the caller to * close the result. Each table and column holds a reference to the original buffer. But both * the buffer and the table must be closed for the memory to be released. */ public ContiguousTable[] contiguousSplit(int... indices) { return contiguousSplit(nativeHandle, indices); } /** * Create an instance of `ChunkedPack` which can be used to pack this table * contiguously in memory utilizing a bounce buffer of size `bounceBufferSize`. * * This version of `makeChunkedPack` takes a `RmmDviceMemoryResource`, which can be used * to pre-allocate all scratch and temporary space required for the state of `cudf::chunked_pack`. * * The caller is responsible for calling close on the returned `ChunkedPack` object. * * @param bounceBufferSize The size of bounce buffer that will be utilized to pack into * @param tempMemoryResource A memory resource that is used to satisfy allocations for * temporary and thrust scratch space. * @return An instance of `ChunkedPack` that the caller must use to finish the operation. */ public ChunkedPack makeChunkedPack( long bounceBufferSize, RmmDeviceMemoryResource tempMemoryResource) { long tempMemoryResourceHandle = tempMemoryResource.getHandle(); return new ChunkedPack( makeChunkedPack(nativeHandle, bounceBufferSize, tempMemoryResourceHandle)); } /** * Create an instance of `ChunkedPack` which can be used to pack this table * contiguously in memory utilizing a bounce buffer of size `bounceBufferSize`. * * This version of `makeChunkedPack` makes use of the default per-device memory resource, * for scratch and temporary space required for the state of `cudf::chunked_pack`. * * The caller is responsible for calling close on the returned `ChunkedPack` object. * * @param bounceBufferSize The size of bounce buffer that will be utilized to pack into * @return An instance of `ChunkedPack` that the caller must use to finish the operation. */ public ChunkedPack makeChunkedPack(long bounceBufferSize) { return new ChunkedPack( makeChunkedPack(nativeHandle, bounceBufferSize, 0)); } /** * Explodes a list column's elements. * * Any list is exploded, which means the elements of the list in each row are expanded * into new rows in the output. The corresponding rows for other columns in the input * are duplicated. * * <code> * Example: * input: [[5,10,15], 100], * [[20,25], 200], * [[30], 300] * index: 0 * output: [5, 100], * [10, 100], * [15, 100], * [20, 200], * [25, 200], * [30, 300] * </code> * * Nulls propagate in different ways depending on what is null. * <code> * input: [[5,null,15], 100], * [null, 200] * index: 0 * output: [5, 100], * [null, 100], * [15, 100] * </code> * Note that null lists are completely removed from the output * and nulls inside lists are pulled out and remain. * * @param index Column index to explode inside the table. * @return A new table with explode_col exploded. */ public Table explode(int index) { assert 0 <= index && index < columns.length : "Column index is out of range"; assert columns[index].getType().equals(DType.LIST) : "Column to explode must be of type LIST"; return new Table(explode(nativeHandle, index)); } /** * Explodes a list column's elements and includes a position column. * * Any list is exploded, which means the elements of the list in each row are expanded into new rows * in the output. The corresponding rows for other columns in the input are duplicated. A position * column is added that has the index inside the original list for each row. Example: * <code> * input: [[5,10,15], 100], * [[20,25], 200], * [[30], 300] * index: 0 * output: [0, 5, 100], * [1, 10, 100], * [2, 15, 100], * [0, 20, 200], * [1, 25, 200], * [0, 30, 300] * </code> * * Nulls and empty lists propagate in different ways depending on what is null or empty. * <code> * input: [[5,null,15], 100], * [null, 200] * index: 0 * output: [5, 100], * [null, 100], * [15, 100] * </code> * * Note that null lists are not included in the resulting table, but nulls inside * lists and empty lists will be represented with a null entry for that column in that row. * * @param index Column index to explode inside the table. * @return A new table with exploded value and position. The column order of return table is * [cols before explode_input, explode_position, explode_value, cols after explode_input]. */ public Table explodePosition(int index) { assert 0 <= index && index < columns.length : "Column index is out of range"; assert columns[index].getType().equals(DType.LIST) : "Column to explode must be of type LIST"; return new Table(explodePosition(nativeHandle, index)); } /** * Explodes a list column's elements. * * Any list is exploded, which means the elements of the list in each row are expanded * into new rows in the output. The corresponding rows for other columns in the input * are duplicated. * * <code> * Example: * input: [[5,10,15], 100], * [[20,25], 200], * [[30], 300], * index: 0 * output: [5, 100], * [10, 100], * [15, 100], * [20, 200], * [25, 200], * [30, 300] * </code> * * Nulls propagate in different ways depending on what is null. * <code> * input: [[5,null,15], 100], * [null, 200] * index: 0 * output: [5, 100], * [null, 100], * [15, 100], * [null, 200] * </code> * Note that null lists are completely removed from the output * and nulls inside lists are pulled out and remain. * * @param index Column index to explode inside the table. * @return A new table with explode_col exploded. */ public Table explodeOuter(int index) { assert 0 <= index && index < columns.length : "Column index is out of range"; assert columns[index].getType().equals(DType.LIST) : "Column to explode must be of type LIST"; return new Table(explodeOuter(nativeHandle, index)); } /** * Explodes a list column's elements retaining any null entries or empty lists and includes a * position column. * * Any list is exploded, which means the elements of the list in each row are expanded into new rows * in the output. The corresponding rows for other columns in the input are duplicated. A position * column is added that has the index inside the original list for each row. Example: * * <code> * Example: * input: [[5,10,15], 100], * [[20,25], 200], * [[30], 300], * index: 0 * output: [0, 5, 100], * [1, 10, 100], * [2, 15, 100], * [0, 20, 200], * [1, 25, 200], * [0, 30, 300] * </code> * * Nulls and empty lists propagate as null entries in the result. * <code> * input: [[5,null,15], 100], * [null, 200], * [[], 300] * index: 0 * output: [0, 5, 100], * [1, null, 100], * [2, 15, 100], * [0, null, 200], * [0, null, 300] * </code> * * returns * * @param index Column index to explode inside the table. * @return A new table with exploded value and position. The column order of return table is * [cols before explode_input, explode_position, explode_value, cols after explode_input]. */ public Table explodeOuterPosition(int index) { assert 0 <= index && index < columns.length : "Column index is out of range"; assert columns[index].getType().equals(DType.LIST) : "Column to explode must be of type LIST"; return new Table(explodeOuterPosition(nativeHandle, index)); } /** * Returns an approximate cumulative size in bits of all columns in the `table_view` for each row. * This function counts bits instead of bytes to account for the null mask which only has one * bit per row. Each row in the returned column is the sum of the per-row bit size for each column * in the table. * * In some cases, this is an inexact approximation. Specifically, columns of lists and strings * require N+1 offsets to represent N rows. It is up to the caller to calculate the small * additional overhead of the terminating offset for any group of rows being considered. * * This function returns the per-row bit sizes as the columns are currently formed. This can * end up being larger than the number you would get by gathering the rows. Specifically, * the push-down of struct column validity masks can nullify rows that contain data for * string or list columns. In these cases, the size returned is conservative such that: * row_bit_count(column(x)) >= row_bit_count(gather(column(x))) * * @return INT32 column of bit size per row of the table */ public ColumnVector rowBitCount() { return new ColumnVector(rowBitCount(getNativeView())); } /** * Gathers the rows of this table according to `gatherMap` such that row "i" * in the resulting table's columns will contain row "gatherMap[i]" from this table. * The number of rows in the result table will be equal to the number of elements in * `gatherMap`. * * A negative value `i` in the `gatherMap` is interpreted as `i+n`, where * `n` is the number of rows in this table. * @param gatherMap the map of indexes. Must be non-nullable and integral type. * @return the resulting Table. */ public Table gather(ColumnView gatherMap) { return gather(gatherMap, OutOfBoundsPolicy.NULLIFY); } /** * Gathers the rows of this table according to `gatherMap` such that row "i" * in the resulting table's columns will contain row "gatherMap[i]" from this table. * The number of rows in the result table will be equal to the number of elements in * `gatherMap`. * * A negative value `i` in the `gatherMap` is interpreted as `i+n`, where * `n` is the number of rows in this table. * * @param gatherMap the map of indexes. Must be non-nullable and integral type. * @param outOfBoundsPolicy policy to use when an out-of-range value is in `gatherMap`. * @return the resulting Table. */ public Table gather(ColumnView gatherMap, OutOfBoundsPolicy outOfBoundsPolicy) { boolean checkBounds = outOfBoundsPolicy == OutOfBoundsPolicy.NULLIFY; return new Table(gather(nativeHandle, gatherMap.getNativeView(), checkBounds)); } /** * Scatters values from the source table into the target table out-of-place, returning a new * result table. The scatter is performed according to a scatter map such that row `scatterMap[i]` * of the destination table gets row `i` of the source table. All other rows of the destination * table equal corresponding rows of the target table. * * The number of columns in source must match the number of columns in target and their * corresponding data types must be the same. * * If the same index appears more than once in the scatter map, the result is undefined. * * A negative value `i` in the `scatterMap` is interpreted as `i + n`, where `n` is the number of * rows in the `target` table. * * @param scatterMap The map of indexes. Must be non-nullable and integral type. * @param target The table into which rows from the current table are to be scattered out-of-place. * @return A new table which is the result of out-of-place scattering the source table into the * target table. */ public Table scatter(ColumnView scatterMap, Table target) { return new Table(scatterTable(nativeHandle, scatterMap.getNativeView(), target.getNativeView())); } /** * Scatters values from the source rows into the target table out-of-place, returning a new result * table. The scatter is performed according to a scatter map such that row `scatterMap[i]` of the * destination table is replaced by the source row `i`. All other rows of the destination table * equal corresponding rows of the target table. * * The number of elements in source must match the number of columns in target and their * corresponding data types must be the same. * * If the same index appears more than once in the scatter map, the result is undefined. * * A negative value `i` in the `scatterMap` is interpreted as `i + n`, where `n` is the number of * rows in the `target` table. * * @param source The input scalars containing values to be scattered into the target table. * @param scatterMap The map of indexes. Must be non-nullable and integral type. * @param target The table into which the values from source are to be scattered out-of-place. * @return A new table which is the result of out-of-place scattering the source values into the * target table. */ public static Table scatter(Scalar[] source, ColumnView scatterMap, Table target) { long[] srcScalarHandles = new long[source.length]; for(int i = 0; i < source.length; ++i) { assert source[i] != null : "Scalar vectors passed in should not contain null"; srcScalarHandles[i] = source[i].getScalarHandle(); } return new Table(scatterScalars(srcScalarHandles, scatterMap.getNativeView(), target.getNativeView())); } private static GatherMap[] buildJoinGatherMaps(long[] gatherMapData) { long bufferSize = gatherMapData[0]; long leftAddr = gatherMapData[1]; long leftHandle = gatherMapData[2]; long rightAddr = gatherMapData[3]; long rightHandle = gatherMapData[4]; GatherMap[] maps = new GatherMap[2]; maps[0] = new GatherMap(DeviceMemoryBuffer.fromRmm(leftAddr, bufferSize, leftHandle)); maps[1] = new GatherMap(DeviceMemoryBuffer.fromRmm(rightAddr, bufferSize, rightHandle)); return maps; } /** * Computes the gather maps that can be used to manifest the result of a left equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the table argument represents the key columns from the right table. Two {@link GatherMap} * instances will be returned that can be used to gather the left and right tables, * respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return left and right table gather maps */ public GatherMap[] leftJoinGatherMaps(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = leftJoinGatherMaps(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildJoinGatherMaps(gatherMapData); } /** * Computes a gather map that can be used to manifest the result of a left equi-join between * two tables where the right table is guaranteed to not contain any duplicated join keys. * The left table can be used as-is to produce the left table columns resulting from the join, * i.e.: left table ordering is preserved in the join result, so no gather map is required for * the left table. The resulting gather map can be applied to the right table to produce the * right table columns resulting from the join. It is assumed this table instance holds the * key columns from the left table, and the table argument represents the key columns from the * right table. A {@link GatherMap} instance will be returned that can be used to gather the * right table and that result combined with the left table to produce a left outer join result. * * It is the responsibility of the caller to close the resulting gather map instance. * * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return right table gather map */ public GatherMap leftDistinctJoinGatherMap(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = leftDistinctJoinGatherMap(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the number of rows resulting from a left equi-join between two tables. * It is assumed this table instance holds the key columns from the left table, and the * {@link HashJoin} argument has been constructed from the key columns from the right table. * @param rightHash hash table built from join key columns from the right table * @return row count of the join result */ public long leftJoinRowCount(HashJoin rightHash) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } return leftJoinRowCount(getNativeView(), rightHash.getNativeView()); } /** * Computes the gather maps that can be used to manifest the result of a left equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the {@link HashJoin} argument has been constructed from the key columns from the right table. * Two {@link GatherMap} instances will be returned that can be used to gather the left and right * tables, respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightHash hash table built from join key columns from the right table * @return left and right table gather maps */ public GatherMap[] leftJoinGatherMaps(HashJoin rightHash) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } long[] gatherMapData = leftHashJoinGatherMaps(getNativeView(), rightHash.getNativeView()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of a left equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the {@link HashJoin} argument has been constructed from the key columns from the right table. * Two {@link GatherMap} instances will be returned that can be used to gather the left and right * tables, respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing an output row count that was previously computed from * {@link #leftJoinRowCount(HashJoin)}. * * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * * @param rightHash hash table built from join key columns from the right table * @param outputRowCount number of output rows in the join result * @return left and right table gather maps */ public GatherMap[] leftJoinGatherMaps(HashJoin rightHash, long outputRowCount) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } long[] gatherMapData = leftHashJoinGatherMapsWithCount(getNativeView(), rightHash.getNativeView(), outputRowCount); return buildJoinGatherMaps(gatherMapData); } /** * Computes the number of rows from the result of a left join between two tables when a * conditional expression is true. It is assumed this table instance holds the columns from * the left table, and the table argument represents the columns from the right table. * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @return row count for the join result */ public long conditionalLeftJoinRowCount(Table rightTable, CompiledExpression condition) { return conditionalLeftJoinRowCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); } /** * Computes the gather maps that can be used to manifest the result of a left join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @return left and right table gather maps */ public GatherMap[] conditionalLeftJoinGatherMaps(Table rightTable, CompiledExpression condition) { long[] gatherMapData = conditionalLeftJoinGatherMaps(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of a left join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing an output row count that was previously computed from * {@link #conditionalLeftJoinRowCount(Table, CompiledExpression)}. * * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @param outputRowCount number of output rows in the join result * @return left and right table gather maps */ public GatherMap[] conditionalLeftJoinGatherMaps(Table rightTable, CompiledExpression condition, long outputRowCount) { long[] gatherMapData = conditionalLeftJoinGatherMapsWithCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle(), outputRowCount); return buildJoinGatherMaps(gatherMapData); } /** * Computes output size information for a left join between two tables using a mix of equality * and inequality conditions. The entire join condition is assumed to be a logical AND of the * equality condition and inequality condition. * NOTE: It is the responsibility of the caller to close the resulting size information object * or native resources can be leaked! * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return size information for the join */ public static MixedJoinSize mixedLeftJoinSize(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] mixedSizeInfo = mixedLeftJoinSize( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); assert mixedSizeInfo.length == 2; long outputRowCount = mixedSizeInfo[0]; long matchesColumnHandle = mixedSizeInfo[1]; return new MixedJoinSize(outputRowCount, new ColumnVector(matchesColumnHandle)); } /** * Computes the gather maps that can be used to manifest the result of a left join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return left and right table gather maps */ public static GatherMap[] mixedLeftJoinGatherMaps(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] gatherMapData = mixedLeftJoinGatherMaps( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of a left join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the left join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing the size result from * {@link #mixedLeftJoinSize(Table, Table, Table, Table, CompiledExpression, NullEquality)} * when the output size was computed previously. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @param joinSize mixed join size result * @return left and right table gather maps */ public static GatherMap[] mixedLeftJoinGatherMaps(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality, MixedJoinSize joinSize) { long[] gatherMapData = mixedLeftJoinGatherMapsWithSize( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL, joinSize.getOutputRowCount(), joinSize.getMatches().getNativeView()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of an inner equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the table argument represents the key columns from the right table. Two {@link GatherMap} * instances will be returned that can be used to gather the left and right tables, * respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return left and right table gather maps */ public GatherMap[] innerJoinGatherMaps(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = innerJoinGatherMaps(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of an inner equi-join between * two tables where the right table is guaranteed to not contain any duplicated join keys. It is * assumed this table instance holds the key columns from the left table, and the table argument * represents the key columns from the right table. Two {@link GatherMap} instances will be * returned that can be used to gather the left and right tables, respectively, to produce the * result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return left and right table gather maps */ public GatherMap[] innerDistinctJoinGatherMaps(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = innerDistinctJoinGatherMaps(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildJoinGatherMaps(gatherMapData); } /** * Computes the number of rows resulting from an inner equi-join between two tables. * @param otherHash hash table built from join key columns from the other table * @return row count of the join result */ public long innerJoinRowCount(HashJoin otherHash) { if (getNumberOfColumns() != otherHash.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "otherKeys: " + otherHash.getNumberOfColumns()); } return innerJoinRowCount(getNativeView(), otherHash.getNativeView()); } /** * Computes the gather maps that can be used to manifest the result of an inner equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the {@link HashJoin} argument has been constructed from the key columns from the right table. * Two {@link GatherMap} instances will be returned that can be used to gather the left and right * tables, respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightHash hash table built from join key columns from the right table * @return left and right table gather maps */ public GatherMap[] innerJoinGatherMaps(HashJoin rightHash) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } long[] gatherMapData = innerHashJoinGatherMaps(getNativeView(), rightHash.getNativeView()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of an inner equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the {@link HashJoin} argument has been constructed from the key columns from the right table. * Two {@link GatherMap} instances will be returned that can be used to gather the left and right * tables, respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing an output row count that was previously computed from * {@link #innerJoinRowCount(HashJoin)}. * * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * * @param rightHash hash table built from join key columns from the right table * @param outputRowCount number of output rows in the join result * @return left and right table gather maps */ public GatherMap[] innerJoinGatherMaps(HashJoin rightHash, long outputRowCount) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } long[] gatherMapData = innerHashJoinGatherMapsWithCount(getNativeView(), rightHash.getNativeView(), outputRowCount); return buildJoinGatherMaps(gatherMapData); } /** * Computes the number of rows from the result of an inner join between two tables when a * conditional expression is true. It is assumed this table instance holds the columns from * the left table, and the table argument represents the columns from the right table. * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @return row count for the join result */ public long conditionalInnerJoinRowCount(Table rightTable, CompiledExpression condition) { return conditionalInnerJoinRowCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); } /** * Computes the gather maps that can be used to manifest the result of an inner join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightTable the right side table of the join * @param condition conditional expression to evaluate during the join * @return left and right table gather maps */ public GatherMap[] conditionalInnerJoinGatherMaps(Table rightTable, CompiledExpression condition) { long[] gatherMapData = conditionalInnerJoinGatherMaps(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of an inner join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing an output row count that was previously computed from * {@link #conditionalInnerJoinRowCount(Table, CompiledExpression)}. * * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @param outputRowCount number of output rows in the join result * @return left and right table gather maps */ public GatherMap[] conditionalInnerJoinGatherMaps(Table rightTable, CompiledExpression condition, long outputRowCount) { long[] gatherMapData = conditionalInnerJoinGatherMapsWithCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle(), outputRowCount); return buildJoinGatherMaps(gatherMapData); } /** * Computes output size information for an inner join between two tables using a mix of equality * and inequality conditions. The entire join condition is assumed to be a logical AND of the * equality condition and inequality condition. * NOTE: It is the responsibility of the caller to close the resulting size information object * or native resources can be leaked! * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return size information for the join */ public static MixedJoinSize mixedInnerJoinSize(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] mixedSizeInfo = mixedInnerJoinSize( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); assert mixedSizeInfo.length == 2; long outputRowCount = mixedSizeInfo[0]; long matchesColumnHandle = mixedSizeInfo[1]; return new MixedJoinSize(outputRowCount, new ColumnVector(matchesColumnHandle)); } /** * Computes the gather maps that can be used to manifest the result of an inner join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return left and right table gather maps */ public static GatherMap[] mixedInnerJoinGatherMaps(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] gatherMapData = mixedInnerJoinGatherMaps( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of an inner join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the inner join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing the size result from * {@link #mixedInnerJoinSize(Table, Table, Table, Table, CompiledExpression, NullEquality)} * when the output size was computed previously. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @param joinSize mixed join size result * @return left and right table gather maps */ public static GatherMap[] mixedInnerJoinGatherMaps(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality, MixedJoinSize joinSize) { long[] gatherMapData = mixedInnerJoinGatherMapsWithSize( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL, joinSize.getOutputRowCount(), joinSize.getMatches().getNativeView()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of an full equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the table argument represents the key columns from the right table. Two {@link GatherMap} * instances will be returned that can be used to gather the left and right tables, * respectively, to produce the result of the full join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return left and right table gather maps */ public GatherMap[] fullJoinGatherMaps(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = fullJoinGatherMaps(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildJoinGatherMaps(gatherMapData); } /** * Computes the number of rows resulting from a full equi-join between two tables. * It is assumed this table instance holds the key columns from the left table, and the * {@link HashJoin} argument has been constructed from the key columns from the right table. * Note that unlike {@link #leftJoinRowCount(HashJoin)} and {@link #innerJoinRowCount(HashJoin), * this will perform some redundant calculations compared to * {@link #fullJoinGatherMaps(HashJoin, long)}. * @param rightHash hash table built from join key columns from the right table * @return row count of the join result */ public long fullJoinRowCount(HashJoin rightHash) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } return fullJoinRowCount(getNativeView(), rightHash.getNativeView()); } /** * Computes the gather maps that can be used to manifest the result of a full equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the {@link HashJoin} argument has been constructed from the key columns from the right table. * Two {@link GatherMap} instances will be returned that can be used to gather the left and right * tables, respectively, to produce the result of the full join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightHash hash table built from join key columns from the right table * @return left and right table gather maps */ public GatherMap[] fullJoinGatherMaps(HashJoin rightHash) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } long[] gatherMapData = fullHashJoinGatherMaps(getNativeView(), rightHash.getNativeView()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of a full equi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the {@link HashJoin} argument has been constructed from the key columns from the right table. * Two {@link GatherMap} instances will be returned that can be used to gather the left and right * tables, respectively, to produce the result of the full join. * * It is the responsibility of the caller to close the resulting gather map instances. * * This interface allows passing an output row count that was previously computed from * {@link #fullJoinRowCount(HashJoin)}. * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * @param rightHash hash table built from join key columns from the right table * @param outputRowCount number of output rows in the join result * @return left and right table gather maps */ public GatherMap[] fullJoinGatherMaps(HashJoin rightHash, long outputRowCount) { if (getNumberOfColumns() != rightHash.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightHash.getNumberOfColumns()); } long[] gatherMapData = fullHashJoinGatherMapsWithCount(getNativeView(), rightHash.getNativeView(), outputRowCount); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of a full join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the full join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param rightTable the right side table of the join * @param condition conditional expression to evaluate during the join * @return left and right table gather maps */ public GatherMap[] conditionalFullJoinGatherMaps(Table rightTable, CompiledExpression condition) { long[] gatherMapData = conditionalFullJoinGatherMaps(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); return buildJoinGatherMaps(gatherMapData); } /** * Computes the gather maps that can be used to manifest the result of a full join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * Two {@link GatherMap} instances will be returned that can be used to gather * the left and right tables, respectively, to produce the result of the full join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return left and right table gather maps */ public static GatherMap[] mixedFullJoinGatherMaps(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] gatherMapData = mixedFullJoinGatherMaps( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); return buildJoinGatherMaps(gatherMapData); } private static GatherMap buildSingleJoinGatherMap(long[] gatherMapData) { long bufferSize = gatherMapData[0]; long leftAddr = gatherMapData[1]; long leftHandle = gatherMapData[2]; return new GatherMap(DeviceMemoryBuffer.fromRmm(leftAddr, bufferSize, leftHandle)); } /** * Computes the gather map that can be used to manifest the result of a left semi-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the table argument represents the key columns from the right table. The {@link GatherMap} * instance returned can be used to gather the left table to produce the result of the * left semi-join. * It is the responsibility of the caller to close the resulting gather map instance. * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return left table gather map */ public GatherMap leftSemiJoinGatherMap(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = leftSemiJoinGatherMap(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the number of rows from the result of a left semi join between two tables when a * conditional expression is true. It is assumed this table instance holds the columns from * the left table, and the table argument represents the columns from the right table. * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @return row count for the join result */ public long conditionalLeftSemiJoinRowCount(Table rightTable, CompiledExpression condition) { return conditionalLeftSemiJoinRowCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); } /** * Computes the gather map that can be used to manifest the result of a left semi join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. The {@link GatherMap} instance returned can be used to gather the left table * to produce the result of the left semi join. * It is the responsibility of the caller to close the resulting gather map instance. * @param rightTable the right side table of the join * @param condition conditional expression to evaluate during the join * @return left table gather map */ public GatherMap conditionalLeftSemiJoinGatherMap(Table rightTable, CompiledExpression condition) { long[] gatherMapData = conditionalLeftSemiJoinGatherMap(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the gather map that can be used to manifest the result of a left semi join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. The {@link GatherMap} instance returned can be used to gather the left table * to produce the result of the left semi join. * It is the responsibility of the caller to close the resulting gather map instance. * This interface allows passing an output row count that was previously computed from * {@link #conditionalLeftSemiJoinRowCount(Table, CompiledExpression)}. * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * @param rightTable the right side table of the join * @param condition conditional expression to evaluate during the join * @param outputRowCount number of output rows in the join result * @return left table gather map */ public GatherMap conditionalLeftSemiJoinGatherMap(Table rightTable, CompiledExpression condition, long outputRowCount) { long[] gatherMapData = conditionalLeftSemiJoinGatherMapWithCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle(), outputRowCount); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the gather map that can be used to manifest the result of a left semi join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * A {@link GatherMap} instance will be returned that can be used to gather * the left table to produce the result of the left semi join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return left and right table gather maps */ public static GatherMap mixedLeftSemiJoinGatherMap(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] gatherMapData = mixedLeftSemiJoinGatherMap( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the gather map that can be used to manifest the result of a left anti-join between * two tables. It is assumed this table instance holds the key columns from the left table, and * the table argument represents the key columns from the right table. The {@link GatherMap} * instance returned can be used to gather the left table to produce the result of the * left anti-join. * It is the responsibility of the caller to close the resulting gather map instance. * @param rightKeys join key columns from the right table * @param compareNullsEqual true if null key values should match otherwise false * @return left table gather map */ public GatherMap leftAntiJoinGatherMap(Table rightKeys, boolean compareNullsEqual) { if (getNumberOfColumns() != rightKeys.getNumberOfColumns()) { throw new IllegalArgumentException("Column count mismatch, this: " + getNumberOfColumns() + "rightKeys: " + rightKeys.getNumberOfColumns()); } long[] gatherMapData = leftAntiJoinGatherMap(getNativeView(), rightKeys.getNativeView(), compareNullsEqual); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the number of rows from the result of a left anti join between two tables when a * conditional expression is true. It is assumed this table instance holds the columns from * the left table, and the table argument represents the columns from the right table. * @param rightTable the right side table of the join in the join * @param condition conditional expression to evaluate during the join * @return row count for the join result */ public long conditionalLeftAntiJoinRowCount(Table rightTable, CompiledExpression condition) { return conditionalLeftAntiJoinRowCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); } /** * Computes the gather map that can be used to manifest the result of a left anti join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. The {@link GatherMap} instance returned can be used to gather the left table * to produce the result of the left anti join. * It is the responsibility of the caller to close the resulting gather map instance. * @param rightTable the right side table of the join * @param condition conditional expression to evaluate during the join * @return left table gather map */ public GatherMap conditionalLeftAntiJoinGatherMap(Table rightTable, CompiledExpression condition) { long[] gatherMapData = conditionalLeftAntiJoinGatherMap(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle()); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the gather map that can be used to manifest the result of a left anti join between * two tables when a conditional expression is true. It is assumed this table instance holds * the columns from the left table, and the table argument represents the columns from the * right table. The {@link GatherMap} instance returned can be used to gather the left table * to produce the result of the left anti join. * It is the responsibility of the caller to close the resulting gather map instance. * This interface allows passing an output row count that was previously computed from * {@link #conditionalLeftAntiJoinRowCount(Table, CompiledExpression)}. * WARNING: Passing a row count that is smaller than the actual row count will result * in undefined behavior. * @param rightTable the right side table of the join * @param condition conditional expression to evaluate during the join * @param outputRowCount number of output rows in the join result * @return left table gather map */ public GatherMap conditionalLeftAntiJoinGatherMap(Table rightTable, CompiledExpression condition, long outputRowCount) { long[] gatherMapData = conditionalLeftAntiJoinGatherMapWithCount(getNativeView(), rightTable.getNativeView(), condition.getNativeHandle(), outputRowCount); return buildSingleJoinGatherMap(gatherMapData); } /** * Computes the gather map that can be used to manifest the result of a left anti join between * two tables using a mix of equality and inequality conditions. The entire join condition is * assumed to be a logical AND of the equality condition and inequality condition. * A {@link GatherMap} instance will be returned that can be used to gather * the left table to produce the result of the left anti join. * * It is the responsibility of the caller to close the resulting gather map instances. * * @param leftKeys the left table's key columns for the equality condition * @param rightKeys the right table's key columns for the equality condition * @param leftConditional the left table's columns needed to evaluate the inequality condition * @param rightConditional the right table's columns needed to evaluate the inequality condition * @param condition the inequality condition of the join * @param nullEquality whether nulls should compare as equal * @return left and right table gather maps */ public static GatherMap mixedLeftAntiJoinGatherMap(Table leftKeys, Table rightKeys, Table leftConditional, Table rightConditional, CompiledExpression condition, NullEquality nullEquality) { long[] gatherMapData = mixedLeftAntiJoinGatherMap( leftKeys.getNativeView(), rightKeys.getNativeView(), leftConditional.getNativeView(), rightConditional.getNativeView(), condition.getNativeHandle(), nullEquality == NullEquality.EQUAL); return buildSingleJoinGatherMap(gatherMapData); } /** * Construct a table from a packed representation. * @param metadata host-based metadata for the table * @param data GPU data buffer for the table * @return table which is zero-copy reconstructed from the packed-form */ public static Table fromPackedTable(ByteBuffer metadata, DeviceMemoryBuffer data) { // Ensure the metadata buffer is direct so it can be passed to JNI ByteBuffer directBuffer = metadata; if (!directBuffer.isDirect()) { directBuffer = ByteBuffer.allocateDirect(metadata.remaining()); directBuffer.put(metadata); directBuffer.flip(); } long[] columnViewAddresses = columnViewsFromPacked(directBuffer, data.getAddress()); ColumnVector[] columns = new ColumnVector[columnViewAddresses.length]; Table result = null; try { for (int i = 0; i < columns.length; i++) { long columnViewAddress = columnViewAddresses[i]; // setting address to zero, so we don't clean it in case of an exception as it // will be cleaned up by the ColumnView constructor columnViewAddresses[i] = 0; columns[i] = ColumnVector.fromViewWithContiguousAllocation(columnViewAddress, data); } result = new Table(columns); } catch (Throwable t) { try { ColumnView.cleanupColumnViews(columnViewAddresses, columns, t); } catch (Throwable s){ t.addSuppressed(s); } finally { throw t; } } // close columns to leave the resulting table responsible for freeing underlying columns for (ColumnVector column : columns) { column.close(); } return result; } /** * Gather `n` samples from table randomly * Note: does not preserve the ordering * Example: * input: {col1: {1, 2, 3, 4, 5}, col2: {6, 7, 8, 9, 10}} * n: 3 * replacement: false * * output: {col1: {3, 1, 4}, col2: {8, 6, 9}} * * replacement: true * * output: {col1: {3, 1, 1}, col2: {8, 6, 6}} * * throws "logic_error" if `n` > table rows and `replacement` == FALSE. * throws "logic_error" if `n` < 0. * * @param n non-negative number of samples expected from table * @param replacement Allow or disallow sampling of the same row more than once. * @param seed Seed value to initiate random number generator. * * @return Table containing samples */ public Table sample(long n, boolean replacement, long seed) { return new Table(sample(nativeHandle, n, replacement, seed)); } ///////////////////////////////////////////////////////////////////////////// // HELPER CLASSES ///////////////////////////////////////////////////////////////////////////// /** * class to encapsulate indices and table */ private final static class Operation { final int[] indices; final Table table; Operation(Table table, int... indices) { this.indices = indices; this.table = table; } } /** * Internal class used to keep track of operations on a given column. */ private static final class ColumnOps { private final HashMap<Aggregation, List<Integer>> ops = new HashMap<>(); /** * Add an operation on a given column * @param op the operation * @param index the column index the operation is on. * @return 1 if it was not a duplicate or 0 if it was a duplicate. This is mostly for * bookkeeping so we can easily allocate the correct data size later on. */ public int add(Aggregation op, int index) { int ret = 0; List<Integer> indexes = ops.get(op); if (indexes == null) { ret++; indexes = new ArrayList<>(); ops.put(op, indexes); } indexes.add(index); return ret; } public Set<Aggregation> operations() { return ops.keySet(); } public Collection<List<Integer>> outputIndices() { return ops.values(); } } /** * Internal class used to keep track of operations on a given column. */ private static final class ColumnWindowOps { // Map AggOp -> Output column index. private final HashMap<AggregationOverWindow, List<Integer>> ops = new HashMap<>(); public int add(AggregationOverWindow op, int index) { int ret = 0; List<Integer> indexes = ops.get(op); if (indexes == null) { ret++; indexes = new ArrayList<>(); ops.put(op, indexes); } indexes.add(index); return ret; } public Set<AggregationOverWindow> operations() { return ops.keySet(); } public Collection<List<Integer>> outputIndices() { return ops.values(); } } /** * Class representing groupby operations */ public static final class GroupByOperation { private final Operation operation; private final GroupByOptions groupByOptions; GroupByOperation(final Table table, GroupByOptions groupByOptions, final int... indices) { operation = new Operation(table, indices); this.groupByOptions = groupByOptions; } /** * Aggregates the group of columns represented by indices * Usage: * aggregate(count(), max(2),...); * example: * input : 1, 1, 1 * 1, 2, 1 * 2, 4, 5 * * table.groupBy(0, 2).count() * * col0, col1 * output: 1, 1 * 1, 2 * 2, 1 ==> aggregated count */ public Table aggregate(GroupByAggregationOnColumn... aggregates) { assert aggregates != null; // To improve performance and memory we want to remove duplicate operations // and also group the operations by column so hopefully cudf can do multiple aggregations // in a single pass. // Use a tree map to make debugging simpler (columns are all in the same order) TreeMap<Integer, ColumnOps> groupedOps = new TreeMap<>(); // Total number of operations that will need to be done. int keysLength = operation.indices.length; int totalOps = 0; for (int outputIndex = 0; outputIndex < aggregates.length; outputIndex++) { GroupByAggregationOnColumn agg = aggregates[outputIndex]; ColumnOps ops = groupedOps.computeIfAbsent(agg.getColumnIndex(), (idx) -> new ColumnOps()); totalOps += ops.add(agg.getWrapped().getWrapped(), outputIndex + keysLength); } int[] aggColumnIndexes = new int[totalOps]; long[] aggOperationInstances = new long[totalOps]; try { int opIndex = 0; for (Map.Entry<Integer, ColumnOps> entry: groupedOps.entrySet()) { int columnIndex = entry.getKey(); for (Aggregation operation: entry.getValue().operations()) { aggColumnIndexes[opIndex] = columnIndex; aggOperationInstances[opIndex] = operation.createNativeInstance(); opIndex++; } } assert opIndex == totalOps : opIndex + " == " + totalOps; try (Table aggregate = new Table(groupByAggregate( operation.table.nativeHandle, operation.indices, aggColumnIndexes, aggOperationInstances, groupByOptions.getIgnoreNullKeys(), groupByOptions.getKeySorted(), groupByOptions.getKeysDescending(), groupByOptions.getKeysNullSmallest()))) { // prepare the final table ColumnVector[] finalCols = new ColumnVector[keysLength + aggregates.length]; // get the key columns for (int aggIndex = 0; aggIndex < keysLength; aggIndex++) { finalCols[aggIndex] = aggregate.getColumn(aggIndex); } int inputColumn = keysLength; // Now get the aggregation columns for (ColumnOps ops: groupedOps.values()) { for (List<Integer> indices: ops.outputIndices()) { for (int outIndex: indices) { finalCols[outIndex] = aggregate.getColumn(inputColumn); } inputColumn++; } } return new Table(finalCols); } } finally { Aggregation.close(aggOperationInstances); } } /** * Computes row-based window aggregation functions on the Table/projection, * based on windows specified in the argument. * * This method enables queries such as the following SQL: * * SELECT user_id, * MAX(sales_amt) OVER(PARTITION BY user_id ORDER BY date * ROWS BETWEEN 1 PRECEDING and 1 FOLLOWING) * FROM my_sales_table WHERE ... * * Each window-aggregation is represented by a different {@link AggregationOverWindow} argument, * indicating: * 1. the {@link Aggregation.Kind}, * 2. the number of rows preceding and following the current row, within a window, * 3. the minimum number of observations within the defined window * * This method returns a {@link Table} instance, with one result column for each specified * window aggregation. * * In this example, for the following input: * * [ // user_id, sales_amt * { "user1", 10 }, * { "user2", 20 }, * { "user1", 20 }, * { "user1", 10 }, * { "user2", 30 }, * { "user2", 80 }, * { "user1", 50 }, * { "user1", 60 }, * { "user2", 40 } * ] * * Partitioning (grouping) by `user_id` yields the following `sales_amt` vector * (with 2 groups, one for each distinct `user_id`): * * [ 10, 20, 10, 50, 60, 20, 30, 80, 40 ] * <-------user1-------->|<------user2-------> * * The SUM aggregation is applied with 1 preceding and 1 following * row, with a minimum of 1 period. The aggregation window is thus 3 rows wide, * yielding the following column: * * [ 30, 40, 80, 120, 110, 50, 130, 150, 120 ] * * @param windowAggregates the window-aggregations to be performed * @return Table instance, with each column containing the result of each aggregation. * @throws IllegalArgumentException if the window arguments are not of type * {@link WindowOptions.FrameType#ROWS}, * i.e. a timestamp column is specified for a window-aggregation. */ public Table aggregateWindows(AggregationOverWindow... windowAggregates) { // To improve performance and memory we want to remove duplicate operations // and also group the operations by column so hopefully cudf can do multiple aggregations // in a single pass. // Use a tree map to make debugging simpler (columns are all in the same order) TreeMap<Integer, ColumnWindowOps> groupedOps = new TreeMap<>(); // Map agg-col-id -> Agg ColOp. // Total number of operations that will need to be done. int totalOps = 0; for (int outputIndex = 0; outputIndex < windowAggregates.length; outputIndex++) { AggregationOverWindow agg = windowAggregates[outputIndex]; if (agg.getWindowOptions().getFrameType() != WindowOptions.FrameType.ROWS) { throw new IllegalArgumentException("Expected ROWS-based window specification. Unexpected window type: " + agg.getWindowOptions().getFrameType()); } ColumnWindowOps ops = groupedOps.computeIfAbsent(agg.getColumnIndex(), (idx) -> new ColumnWindowOps()); totalOps += ops.add(agg, outputIndex); } int[] aggColumnIndexes = new int[totalOps]; long[] aggInstances = new long[totalOps]; try { int[] aggPrecedingWindows = new int[totalOps]; int[] aggFollowingWindows = new int[totalOps]; boolean[] unboundedPreceding = new boolean[totalOps]; boolean[] unboundedFollowing = new boolean[totalOps]; int[] aggMinPeriods = new int[totalOps]; long[] defaultOutputs = new long[totalOps]; int opIndex = 0; for (Map.Entry<Integer, ColumnWindowOps> entry: groupedOps.entrySet()) { int columnIndex = entry.getKey(); for (AggregationOverWindow operation: entry.getValue().operations()) { aggColumnIndexes[opIndex] = columnIndex; aggInstances[opIndex] = operation.createNativeInstance(); Scalar p = operation.getWindowOptions().getPrecedingScalar(); aggPrecedingWindows[opIndex] = p == null || !p.isValid() ? 0 : p.getInt(); Scalar f = operation.getWindowOptions().getFollowingScalar(); aggFollowingWindows[opIndex] = f == null || ! f.isValid() ? 1 : f.getInt(); unboundedPreceding[opIndex] = operation.getWindowOptions().isUnboundedPreceding(); unboundedFollowing[opIndex] = operation.getWindowOptions().isUnboundedFollowing(); aggMinPeriods[opIndex] = operation.getWindowOptions().getMinPeriods(); defaultOutputs[opIndex] = operation.getDefaultOutput(); opIndex++; } } assert opIndex == totalOps : opIndex + " == " + totalOps; try (Table aggregate = new Table(rollingWindowAggregate( operation.table.nativeHandle, operation.indices, defaultOutputs, aggColumnIndexes, aggInstances, aggMinPeriods, aggPrecedingWindows, aggFollowingWindows, unboundedPreceding, unboundedFollowing, groupByOptions.getIgnoreNullKeys()))) { // prepare the final table ColumnVector[] finalCols = new ColumnVector[windowAggregates.length]; int inputColumn = 0; // Now get the aggregation columns for (ColumnWindowOps ops: groupedOps.values()) { for (List<Integer> indices: ops.outputIndices()) { for (int outIndex: indices) { finalCols[outIndex] = aggregate.getColumn(inputColumn); } inputColumn++; } } return new Table(finalCols); } } finally { Aggregation.close(aggInstances); } } /** * Computes range-based window aggregation functions on the Table/projection, * based on windows specified in the argument. * * This method enables queries such as the following SQL: * * SELECT user_id, * MAX(sales_amt) OVER(PARTITION BY user_id ORDER BY date * RANGE BETWEEN INTERVAL 1 DAY PRECEDING and CURRENT ROW) * FROM my_sales_table WHERE ... * * Each window-aggregation is represented by a different {@link AggregationOverWindow} argument, * indicating: * 1. the {@link Aggregation.Kind}, * 2. the index for the timestamp column to base the window definitions on * 2. the number of DAYS preceding and following the current row's date, to consider in the window * 3. the minimum number of observations within the defined window * * This method returns a {@link Table} instance, with one result column for each specified * window aggregation. * * In this example, for the following input: * * [ // user, sales_amt, YYYYMMDD (date) * { "user1", 10, 20200101 }, * { "user2", 20, 20200101 }, * { "user1", 20, 20200102 }, * { "user1", 10, 20200103 }, * { "user2", 30, 20200101 }, * { "user2", 80, 20200102 }, * { "user1", 50, 20200107 }, * { "user1", 60, 20200107 }, * { "user2", 40, 20200104 } * ] * * Partitioning (grouping) by `user_id`, and ordering by `date` yields the following `sales_amt` vector * (with 2 groups, one for each distinct `user_id`): * * Date :(202001-) [ 01, 02, 03, 07, 07, 01, 01, 02, 04 ] * Input: [ 10, 20, 10, 50, 60, 20, 30, 80, 40 ] * <-------user1-------->|<---------user2---------> * * The SUM aggregation is applied, with 1 day preceding, and 1 day following, with a minimum of 1 period. * The aggregation window is thus 3 *days* wide, yielding the following output column: * * Results: [ 30, 40, 30, 110, 110, 130, 130, 130, 40 ] * * @param windowAggregates the window-aggregations to be performed * @return Table instance, with each column containing the result of each aggregation. * @throws IllegalArgumentException if the window arguments are not of type * {@link WindowOptions.FrameType#RANGE} or the orderBys are not of (Boolean-exclusive) integral type * i.e. the timestamp-column was not specified for the aggregation. */ public Table aggregateWindowsOverRanges(AggregationOverWindow... windowAggregates) { // To improve performance and memory we want to remove duplicate operations // and also group the operations by column so hopefully cudf can do multiple aggregations // in a single pass. // Use a tree map to make debugging simpler (columns are all in the same order) TreeMap<Integer, ColumnWindowOps> groupedOps = new TreeMap<>(); // Map agg-col-id -> Agg ColOp. // Total number of operations that will need to be done. int totalOps = 0; for (int outputIndex = 0; outputIndex < windowAggregates.length; outputIndex++) { AggregationOverWindow agg = windowAggregates[outputIndex]; if (agg.getWindowOptions().getFrameType() != WindowOptions.FrameType.RANGE) { throw new IllegalArgumentException("Expected range-based window specification. Unexpected window type: " + agg.getWindowOptions().getFrameType()); } DType orderByType = operation.table.getColumn(agg.getWindowOptions().getOrderByColumnIndex()).getType(); switch (orderByType.getTypeId()) { case INT8: case INT16: case INT32: case INT64: case UINT8: case UINT16: case UINT32: case UINT64: case FLOAT32: case FLOAT64: case TIMESTAMP_MILLISECONDS: case TIMESTAMP_SECONDS: case TIMESTAMP_DAYS: case TIMESTAMP_NANOSECONDS: case TIMESTAMP_MICROSECONDS: case DECIMAL32: case DECIMAL64: case DECIMAL128: case STRING: break; default: throw new IllegalArgumentException("Expected range-based window orderBy's " + "type: integral (Boolean-exclusive), decimal, timestamp, and string"); } ColumnWindowOps ops = groupedOps.computeIfAbsent(agg.getColumnIndex(), (idx) -> new ColumnWindowOps()); totalOps += ops.add(agg, outputIndex); } int[] aggColumnIndexes = new int[totalOps]; int[] orderByColumnIndexes = new int[totalOps]; boolean[] isOrderByOrderAscending = new boolean[totalOps]; long[] aggInstances = new long[totalOps]; long[] aggPrecedingWindows = new long[totalOps]; long[] aggFollowingWindows = new long[totalOps]; try { int[] aggPrecedingWindowsExtent = new int[totalOps]; int[] aggFollowingWindowsExtent = new int[totalOps]; int[] aggMinPeriods = new int[totalOps]; int opIndex = 0; for (Map.Entry<Integer, ColumnWindowOps> entry: groupedOps.entrySet()) { int columnIndex = entry.getKey(); for (AggregationOverWindow op: entry.getValue().operations()) { aggColumnIndexes[opIndex] = columnIndex; aggInstances[opIndex] = op.createNativeInstance(); WindowOptions windowOptions = op.getWindowOptions(); Scalar p = windowOptions.getPrecedingScalar(); Scalar f = windowOptions.getFollowingScalar(); if ((p == null || !p.isValid()) && !(windowOptions.isUnboundedPreceding() || windowOptions.isCurrentRowPreceding())) { throw new IllegalArgumentException("Some kind of preceding must be set and a preceding column is not currently supported"); } if ((f == null || !f.isValid()) && !(windowOptions.isUnboundedFollowing() || windowOptions.isCurrentRowFollowing())) { throw new IllegalArgumentException("some kind of following must be set and a follow column is not currently supported"); } aggPrecedingWindows[opIndex] = p == null ? 0 : p.getScalarHandle(); aggFollowingWindows[opIndex] = f == null ? 0 : f.getScalarHandle(); aggPrecedingWindowsExtent[opIndex] = windowOptions.getPrecedingBoundsExtent().nominalValue; aggFollowingWindowsExtent[opIndex] = windowOptions.getFollowingBoundsExtent().nominalValue; aggMinPeriods[opIndex] = op.getWindowOptions().getMinPeriods(); assert (op.getWindowOptions().getFrameType() == WindowOptions.FrameType.RANGE); orderByColumnIndexes[opIndex] = op.getWindowOptions().getOrderByColumnIndex(); isOrderByOrderAscending[opIndex] = op.getWindowOptions().isOrderByOrderAscending(); if (op.getDefaultOutput() != 0) { throw new IllegalArgumentException("Operations with a default output are not " + "supported on time based rolling windows"); } opIndex++; } } assert opIndex == totalOps : opIndex + " == " + totalOps; try (Table aggregate = new Table(rangeRollingWindowAggregate( operation.table.nativeHandle, operation.indices, orderByColumnIndexes, isOrderByOrderAscending, aggColumnIndexes, aggInstances, aggMinPeriods, aggPrecedingWindows, aggFollowingWindows, aggPrecedingWindowsExtent, aggFollowingWindowsExtent, groupByOptions.getIgnoreNullKeys()))) { // prepare the final table ColumnVector[] finalCols = new ColumnVector[windowAggregates.length]; int inputColumn = 0; // Now get the aggregation columns for (ColumnWindowOps ops: groupedOps.values()) { for (List<Integer> indices: ops.outputIndices()) { for (int outIndex: indices) { finalCols[outIndex] = aggregate.getColumn(inputColumn); } inputColumn++; } } return new Table(finalCols); } } finally { Aggregation.close(aggInstances); } } public Table scan(GroupByScanAggregationOnColumn... aggregates) { assert aggregates != null; // To improve performance and memory we want to remove duplicate operations // and also group the operations by column so hopefully cudf can do multiple aggregations // in a single pass. // Use a tree map to make debugging simpler (columns are all in the same order) TreeMap<Integer, ColumnOps> groupedOps = new TreeMap<>(); // Total number of operations that will need to be done. int keysLength = operation.indices.length; int totalOps = 0; for (int outputIndex = 0; outputIndex < aggregates.length; outputIndex++) { GroupByScanAggregationOnColumn agg = aggregates[outputIndex]; ColumnOps ops = groupedOps.computeIfAbsent(agg.getColumnIndex(), (idx) -> new ColumnOps()); totalOps += ops.add(agg.getWrapped().getWrapped(), outputIndex + keysLength); } int[] aggColumnIndexes = new int[totalOps]; long[] aggOperationInstances = new long[totalOps]; try { int opIndex = 0; for (Map.Entry<Integer, ColumnOps> entry: groupedOps.entrySet()) { int columnIndex = entry.getKey(); for (Aggregation operation: entry.getValue().operations()) { aggColumnIndexes[opIndex] = columnIndex; aggOperationInstances[opIndex] = operation.createNativeInstance(); opIndex++; } } assert opIndex == totalOps : opIndex + " == " + totalOps; try (Table aggregate = new Table(groupByScan( operation.table.nativeHandle, operation.indices, aggColumnIndexes, aggOperationInstances, groupByOptions.getIgnoreNullKeys(), groupByOptions.getKeySorted(), groupByOptions.getKeysDescending(), groupByOptions.getKeysNullSmallest()))) { // prepare the final table ColumnVector[] finalCols = new ColumnVector[keysLength + aggregates.length]; // get the key columns for (int aggIndex = 0; aggIndex < keysLength; aggIndex++) { finalCols[aggIndex] = aggregate.getColumn(aggIndex); } int inputColumn = keysLength; // Now get the aggregation columns for (ColumnOps ops: groupedOps.values()) { for (List<Integer> indices: ops.outputIndices()) { for (int outIndex: indices) { finalCols[outIndex] = aggregate.getColumn(inputColumn); } inputColumn++; } } return new Table(finalCols); } } finally { Aggregation.close(aggOperationInstances); } } public Table replaceNulls(ReplacePolicyWithColumn... replacements) { assert replacements != null; // TODO in the future perhaps to improve performance and memory we want to // remove duplicate operations. boolean[] isPreceding = new boolean[replacements.length]; int [] columnIndexes = new int[replacements.length]; for (int index = 0; index < replacements.length; index++) { isPreceding[index] = replacements[index].policy.isPreceding; columnIndexes[index] = replacements[index].column; } return new Table(groupByReplaceNulls( operation.table.nativeHandle, operation.indices, columnIndexes, isPreceding, groupByOptions.getIgnoreNullKeys(), groupByOptions.getKeySorted(), groupByOptions.getKeysDescending(), groupByOptions.getKeysNullSmallest())); } /** * Splits the groups in a single table into separate tables according to the grouping keys. * Each split table represents a single group. * * This API will be used by some grouping related operators to process the data * group by group. * * Example: * Grouping column index: 0 * Input: A table of 3 rows (two groups) * a 1 * b 2 * b 3 * * Result: * Two tables, one group one table. * Result[0]: * a 1 * * Result[1]: * b 2 * b 3 * * Note, the order of the groups returned is NOT always the same with that in the input table. * The split is done in native to avoid copying the offset array to JVM. * * @return The tables split according to the groups in the table. NOTE: It is the * responsibility of the caller to close the result. Each table and column holds a * reference to the original buffer. But both the buffer and the table must be closed * for the memory to be released. */ public ContiguousTable[] contiguousSplitGroups() { try (ContigSplitGroupByResult ret = Table.contiguousSplitGroups( operation.table.nativeHandle, operation.indices, groupByOptions.getIgnoreNullKeys(), groupByOptions.getKeySorted(), groupByOptions.getKeysDescending(), groupByOptions.getKeysNullSmallest(), false) // not generate uniq key table ) { // take the ownership of the `groups` in ContigSplitGroupByResult return ret.releaseGroups(); } } /** * Similar to {@link #contiguousSplitGroups}, return an extra uniq key table in which * each row is corresponding to a group split. * * Splits the groups in a single table into separate tables according to the grouping keys. * Each split table represents a single group. * * Example, see the example in {@link #contiguousSplitGroups} * The `uniqKeysTable` in ContigSplitGroupByResult is: * a * b * Note: only 2 rows because of only has 2 split groups * * @return The split groups and uniq key table. */ public ContigSplitGroupByResult contiguousSplitGroupsAndGenUniqKeys() { return Table.contiguousSplitGroups( operation.table.nativeHandle, operation.indices, groupByOptions.getIgnoreNullKeys(), groupByOptions.getKeySorted(), groupByOptions.getKeysDescending(), groupByOptions.getKeysNullSmallest(), true); // generate uniq key table } } public static final class TableOperation { private final Operation operation; TableOperation(final Table table, final int... indices) { operation = new Operation(table, indices); } /** * Hash partition a table into the specified number of partitions. Uses the default MURMUR3 * hashing. * @param numberOfPartitions - number of partitions to use * @return - {@link PartitionedTable} - Table that exposes a limited functionality of the * {@link Table} class */ public PartitionedTable hashPartition(int numberOfPartitions) { return hashPartition(HashType.MURMUR3, numberOfPartitions); } /** * Hash partition a table into the specified number of partitions. * @param type the type of hash to use. Depending on the type of hash different restrictions * on the hash column(s) may exist. Not all hash functions are guaranteed to work * besides IDENTITY and MURMUR3. * @param numberOfPartitions - number of partitions to use * @return {@link PartitionedTable} - Table that exposes a limited functionality of the * {@link Table} class */ public PartitionedTable hashPartition(HashType type, int numberOfPartitions) { final int DEFAULT_HASH_SEED = 0; return hashPartition(type, numberOfPartitions, DEFAULT_HASH_SEED); } /** * Hash partition a table into the specified number of partitions. * @param type the type of hash to use. Depending on the type of hash different restrictions * on the hash column(s) may exist. Not all hash functions are guaranteed to work * besides IDENTITY and MURMUR3. * @param numberOfPartitions number of partitions to use * @param seed the seed value for hashing * @return Table that exposes a limited functionality of the {@link Table} class */ public PartitionedTable hashPartition(HashType type, int numberOfPartitions, int seed) { int[] partitionOffsets = new int[numberOfPartitions]; return new PartitionedTable(new Table(Table.hashPartition( operation.table.nativeHandle, operation.indices, type.nativeId, partitionOffsets.length, seed, partitionOffsets)), partitionOffsets); } } ///////////////////////////////////////////////////////////////////////////// // BUILDER ///////////////////////////////////////////////////////////////////////////// /** * Create a table on the GPU with data from the CPU. This is not fast and intended mostly for * tests. */ public static final class TestBuilder { private final List<DataType> types = new ArrayList<>(); private final List<Object> typeErasedData = new ArrayList<>(); public TestBuilder column(String... values) { types.add(new BasicType(true, DType.STRING)); typeErasedData.add(values); return this; } public TestBuilder column(Boolean... values) { types.add(new BasicType(true, DType.BOOL8)); typeErasedData.add(values); return this; } public TestBuilder column(Byte... values) { types.add(new BasicType(true, DType.INT8)); typeErasedData.add(values); return this; } public TestBuilder column(Short... values) { types.add(new BasicType(true, DType.INT16)); typeErasedData.add(values); return this; } public TestBuilder column(Integer... values) { types.add(new BasicType(true, DType.INT32)); typeErasedData.add(values); return this; } public TestBuilder column(Long... values) { types.add(new BasicType(true, DType.INT64)); typeErasedData.add(values); return this; } public TestBuilder column(Float... values) { types.add(new BasicType(true, DType.FLOAT32)); typeErasedData.add(values); return this; } public TestBuilder column(Double... values) { types.add(new BasicType(true, DType.FLOAT64)); typeErasedData.add(values); return this; } public TestBuilder column(ListType dataType, List<?>... values) { types.add(dataType); typeErasedData.add(values); return this; } public TestBuilder column(String[]... values) { types.add(new ListType(true, new BasicType(true, DType.STRING))); typeErasedData.add(values); return this; } public TestBuilder column(Boolean[]... values) { types.add(new ListType(true, new BasicType(true, DType.BOOL8))); typeErasedData.add(values); return this; } public TestBuilder column(Byte[]... values) { types.add(new ListType(true, new BasicType(true, DType.INT8))); typeErasedData.add(values); return this; } public TestBuilder column(Short[]... values) { types.add(new ListType(true, new BasicType(true, DType.INT16))); typeErasedData.add(values); return this; } public TestBuilder column(Integer[]... values) { types.add(new ListType(true, new BasicType(true, DType.INT32))); typeErasedData.add(values); return this; } public TestBuilder column(Long[]... values) { types.add(new ListType(true, new BasicType(true, DType.INT64))); typeErasedData.add(values); return this; } public TestBuilder column(Float[]... values) { types.add(new ListType(true, new BasicType(true, DType.FLOAT32))); typeErasedData.add(values); return this; } public TestBuilder column(Double[]... values) { types.add(new ListType(true, new BasicType(true, DType.FLOAT64))); typeErasedData.add(values); return this; } public TestBuilder column(StructType dataType, StructData... values) { types.add(dataType); typeErasedData.add(values); return this; } public TestBuilder column(StructType dataType, StructData[]... values) { types.add(new ListType(true, dataType)); typeErasedData.add(values); return this; } public TestBuilder timestampDayColumn(Integer... values) { types.add(new BasicType(true, DType.TIMESTAMP_DAYS)); typeErasedData.add(values); return this; } public TestBuilder timestampNanosecondsColumn(Long... values) { types.add(new BasicType(true, DType.TIMESTAMP_NANOSECONDS)); typeErasedData.add(values); return this; } public TestBuilder timestampMillisecondsColumn(Long... values) { types.add(new BasicType(true, DType.TIMESTAMP_MILLISECONDS)); typeErasedData.add(values); return this; } public TestBuilder timestampMicrosecondsColumn(Long... values) { types.add(new BasicType(true, DType.TIMESTAMP_MICROSECONDS)); typeErasedData.add(values); return this; } public TestBuilder timestampSecondsColumn(Long... values) { types.add(new BasicType(true, DType.TIMESTAMP_SECONDS)); typeErasedData.add(values); return this; } public TestBuilder decimal32Column(int scale, Integer... unscaledValues) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL32, scale))); typeErasedData.add(unscaledValues); return this; } public TestBuilder decimal32Column(int scale, RoundingMode mode, Double... values) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL32, scale))); BigDecimal[] data = Arrays.stream(values).map((x) -> { if (x == null) return null; return BigDecimal.valueOf(x).setScale(-scale, mode); }).toArray(BigDecimal[]::new); typeErasedData.add(data); return this; } public TestBuilder decimal32Column(int scale, RoundingMode mode, String... values) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL32, scale))); BigDecimal[] data = Arrays.stream(values).map((x) -> { if (x == null) return null; return new BigDecimal(x).setScale(-scale, mode); }).toArray(BigDecimal[]::new); typeErasedData.add(data); return this; } public TestBuilder decimal64Column(int scale, Long... unscaledValues) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL64, scale))); typeErasedData.add(unscaledValues); return this; } public TestBuilder decimal64Column(int scale, RoundingMode mode, Double... values) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL64, scale))); BigDecimal[] data = Arrays.stream(values).map((x) -> { if (x == null) return null; return BigDecimal.valueOf(x).setScale(-scale, mode); }).toArray(BigDecimal[]::new); typeErasedData.add(data); return this; } public TestBuilder decimal64Column(int scale, RoundingMode mode, String... values) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL64, scale))); BigDecimal[] data = Arrays.stream(values).map((x) -> { if (x == null) return null; return new BigDecimal(x).setScale(-scale, mode); }).toArray(BigDecimal[]::new); typeErasedData.add(data); return this; } public TestBuilder decimal128Column(int scale, RoundingMode mode, BigInteger... values) { types.add(new BasicType(true, DType.create(DType.DTypeEnum.DECIMAL128, scale))); BigDecimal[] data = Arrays.stream(values).map((x) -> { if (x == null) return null; return new BigDecimal(x, scale, new MathContext(38, mode)); }).toArray(BigDecimal[]::new); typeErasedData.add(data); return this; } private static ColumnVector from(DType type, Object dataArray) { ColumnVector ret = null; switch (type.typeId) { case STRING: ret = ColumnVector.fromStrings((String[]) dataArray); break; case BOOL8: ret = ColumnVector.fromBoxedBooleans((Boolean[]) dataArray); break; case INT8: ret = ColumnVector.fromBoxedBytes((Byte[]) dataArray); break; case INT16: ret = ColumnVector.fromBoxedShorts((Short[]) dataArray); break; case INT32: ret = ColumnVector.fromBoxedInts((Integer[]) dataArray); break; case INT64: ret = ColumnVector.fromBoxedLongs((Long[]) dataArray); break; case TIMESTAMP_DAYS: ret = ColumnVector.timestampDaysFromBoxedInts((Integer[]) dataArray); break; case TIMESTAMP_SECONDS: ret = ColumnVector.timestampSecondsFromBoxedLongs((Long[]) dataArray); break; case TIMESTAMP_MILLISECONDS: ret = ColumnVector.timestampMilliSecondsFromBoxedLongs((Long[]) dataArray); break; case TIMESTAMP_MICROSECONDS: ret = ColumnVector.timestampMicroSecondsFromBoxedLongs((Long[]) dataArray); break; case TIMESTAMP_NANOSECONDS: ret = ColumnVector.timestampNanoSecondsFromBoxedLongs((Long[]) dataArray); break; case FLOAT32: ret = ColumnVector.fromBoxedFloats((Float[]) dataArray); break; case FLOAT64: ret = ColumnVector.fromBoxedDoubles((Double[]) dataArray); break; case DECIMAL32: case DECIMAL64: case DECIMAL128: int scale = type.getScale(); if (dataArray instanceof Integer[]) { BigDecimal[] data = Arrays.stream(((Integer[]) dataArray)) .map((i) -> i == null ? null : BigDecimal.valueOf(i, -scale)) .toArray(BigDecimal[]::new); ret = ColumnVector.build(type, data.length, (b) -> b.appendBoxed(data)); } else if (dataArray instanceof Long[]) { BigDecimal[] data = Arrays.stream(((Long[]) dataArray)) .map((i) -> i == null ? null : BigDecimal.valueOf(i, -scale)) .toArray(BigDecimal[]::new); ret = ColumnVector.build(type, data.length, (b) -> b.appendBoxed(data)); } else if (dataArray instanceof BigDecimal[]) { BigDecimal[] data = (BigDecimal[]) dataArray; ret = ColumnVector.build(type, data.length, (b) -> b.appendBoxed(data)); } else { throw new IllegalArgumentException( "Data array of invalid type(" + dataArray.getClass() + ") to build decimal column"); } break; default: throw new IllegalArgumentException(type + " is not supported yet"); } return ret; } @SuppressWarnings("unchecked") private static <T> ColumnVector fromLists(DataType dataType, Object[] dataArray) { List[] dataLists = new List[dataArray.length]; for (int i = 0; i < dataLists.length; ++i) { // The element in dataArray can be an array or list, because the below overloaded // version accepts a List of Array as rows. // `public TestBuilder column(ListType dataType, List<?>... values)` Object dataList = dataArray[i]; dataLists[i] = dataList == null ? null : (dataList instanceof List ? (List)dataList : Arrays.asList((Object[])dataList)); } return ColumnVector.fromLists(dataType, dataLists); } private static ColumnVector fromStructs(DataType dataType, StructData[] dataArray) { return ColumnVector.fromStructs(dataType, dataArray); } public Table build() { List<ColumnVector> columns = new ArrayList<>(types.size()); try { for (int i = 0; i < types.size(); i++) { DataType dataType = types.get(i); DType dtype = dataType.getType(); Object dataArray = typeErasedData.get(i); if (dtype.isNestedType()) { if (dtype.equals(DType.LIST)) { columns.add(fromLists(dataType, (Object[]) dataArray)); } else if (dtype.equals(DType.STRUCT)) { columns.add(fromStructs(dataType, (StructData[]) dataArray)); } else { throw new IllegalStateException("Unexpected nested type: " + dtype); } } else { columns.add(from(dtype, dataArray)); } } return new Table(columns.toArray(new ColumnVector[columns.size()])); } finally { for (ColumnVector cv : columns) { cv.close(); } } } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/TableDebug.java
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Locale; import java.util.function.Consumer; public class TableDebug { /** * Specify one of * -Dai.rapids.cudf.debug.output=stderr to print directly to standard error (default) * -Dai.rapids.cudf.debug.output=stdout to print directly to standard output * -Dai.rapids.cudf.debug.output=log[_level] to redirect to a logging subsystem that can * further be * configured. * Supported log levels: * debug (default) * info * warn * error */ public static final String OUTPUT_STREAM = "ai.rapids.cudf.debug.output"; private static final Logger log = LoggerFactory.getLogger(TableDebug.class); public enum Output { STDOUT(System.out::println), STDERR(System.err::println), LOG(log::debug), LOG_DEBUG(log::debug), LOG_INFO(log::info), LOG_WARN(log::warn), LOG_ERROR(log::error); private final Consumer<String> printFunc; Output(Consumer<String> pf) { this.printFunc = pf; } final void println(String s) { printFunc.accept(s); } } public static class Builder { private Output outputMode = Output.STDERR; public Builder() { try { outputMode = Output.valueOf( System.getProperty(OUTPUT_STREAM, Output.STDERR.name()) .toUpperCase(Locale.US)); } catch (Throwable e) { log.warn("Failed to parse the output mode", e); } } public Builder withOutput(Output outputMode) { this.outputMode = outputMode; return this; } public final TableDebug build() { return new TableDebug(outputMode); } } public static Builder builder() { return new Builder(); } private static final TableDebug DEFAULT_DEBUG = builder().build(); public static TableDebug get() { return DEFAULT_DEBUG; } private final Output output; private TableDebug(Output output) { this.output = output; } /** * Print the contents of a table. Note that this should never be * called from production code, as it is very slow. Also note that this is not production * code. You might need/want to update how the data shows up or add in support for more * types as this really is just for debugging. * @param name the name of the table to print out. * @param table the table to print out. */ public synchronized void debug(String name, Table table) { output.println("DEBUG " + name + " " + table); for (int col = 0; col < table.getNumberOfColumns(); col++) { debug(String.valueOf(col), table.getColumn(col)); } } /** * Print the contents of a column. Note that this should never be * called from production code, as it is very slow. Also note that this is not production * code. You might need/want to update how the data shows up or add in support for more * types as this really is just for debugging. * @param name the name of the column to print out. * @param col the column to print out. */ public synchronized void debug(String name, ColumnView col) { debugGPUAddrs(name, col); try (HostColumnVector hostCol = col.copyToHost()) { debug(name, hostCol); } } private synchronized void debugGPUAddrs(String name, ColumnView col) { try (BaseDeviceMemoryBuffer data = col.getData(); BaseDeviceMemoryBuffer validity = col.getValid()) { output.println("GPU COLUMN " + name + " - NC: " + col.getNullCount() + " DATA: " + data + " VAL: " + validity); } if (col.getType() == DType.STRUCT) { for (int i = 0; i < col.getNumChildren(); i++) { try (ColumnView child = col.getChildColumnView(i)) { debugGPUAddrs(name + ":CHILD_" + i, child); } } } else if (col.getType() == DType.LIST) { try (ColumnView child = col.getChildColumnView(0)) { debugGPUAddrs(name + ":DATA", child); } } } /** * Print the contents of a column. Note that this should never be * called from production code, as it is very slow. Also note that this is not production * code. You might need/want to update how the data shows up or add in support for more * types as this really is just for debugging. * @param name the name of the column to print out. * @param hostCol the column to print out. */ public synchronized void debug(String name, HostColumnVectorCore hostCol) { DType type = hostCol.getType(); output.println("COLUMN " + name + " - " + type); if (type.isDecimalType()) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { output.println(i + " " + hostCol.getBigDecimal(i)); } } } else if (DType.STRING.equals(type)) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { output.println(i + " \"" + hostCol.getJavaString(i) + "\" " + hexString(hostCol.getUTF8(i))); } } } else if (DType.INT32.equals(type) || DType.INT8.equals(type) || DType.INT16.equals(type) || DType.INT64.equals(type) || DType.TIMESTAMP_DAYS.equals(type) || DType.TIMESTAMP_SECONDS.equals(type) || DType.TIMESTAMP_MICROSECONDS.equals(type) || DType.TIMESTAMP_MILLISECONDS.equals(type) || DType.TIMESTAMP_NANOSECONDS.equals(type) || DType.UINT8.equals(type) || DType.UINT16.equals(type) || DType.UINT32.equals(type) || DType.UINT64.equals(type)) { debugInteger(hostCol, type); } else if (DType.BOOL8.equals(type)) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { output.println(i + " " + hostCol.getBoolean(i)); } } } else if (DType.FLOAT64.equals(type)) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { output.println(i + " " + hostCol.getDouble(i)); } } } else if (DType.FLOAT32.equals(type)) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { output.println(i + " " + hostCol.getFloat(i)); } } } else if (DType.STRUCT.equals(type)) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } // The struct child columns are printed out later on. } for (int i = 0; i < hostCol.getNumChildren(); i++) { debug(name + ":CHILD_" + i, hostCol.getChildColumnView(i)); } } else if (DType.LIST.equals(type)) { output.println("OFFSETS"); for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { output.println(i + " [" + hostCol.getStartListOffset(i) + " - " + hostCol.getEndListOffset(i) + ")"); } } debug(name + ":DATA", hostCol.getChildColumnView(0)); } else { output.println("TYPE " + type + " NOT SUPPORTED FOR DEBUG PRINT"); } } private void debugInteger(HostColumnVectorCore hostCol, DType intType) { for (int i = 0; i < hostCol.getRowCount(); i++) { if (hostCol.isNull(i)) { output.println(i + " NULL"); } else { final int sizeInBytes = intType.getSizeInBytes(); final Object value; switch (sizeInBytes) { case Byte.BYTES: value = hostCol.getByte(i); break; case Short.BYTES: value = hostCol.getShort(i); break; case Integer.BYTES: value = hostCol.getInt(i); break; case Long.BYTES: value = hostCol.getLong(i); break; default: throw new IllegalArgumentException("INFEASIBLE: Unsupported integer-like type " + intType); } output.println(i + " " + value); } } } private static String hexString(byte[] bytes) { StringBuilder str = new StringBuilder(); for (byte b : bytes) { str.append(String.format("%02x", b & 0xff)); } return str.toString(); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/TableWithMeta.java
/* * * Copyright (c) 2022-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * A table along with some metadata about the table. This is typically returned when * reading data from an input file where the metadata can be important. */ public class TableWithMeta implements AutoCloseable { private long handle; private NestedChildren children = null; public static class NestedChildren { private final String[] names; private final NestedChildren[] children; private NestedChildren(String[] names, NestedChildren[] children) { this.names = names; this.children = children; } public String[] getNames() { return names; } public NestedChildren getChild(int i) { return children[i]; } public boolean isChildNested(int i) { return (getChild(i) != null); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (names != null) { for (int i = 0; i < names.length; i++) { if (i != 0) { sb.append(", "); } sb.append(names[i]); sb.append(": "); if (children != null) { sb.append(children[i]); } } } sb.append("}"); return sb.toString(); } } TableWithMeta(long handle) { this.handle = handle; } /** * Get the table out of this metadata. Note that this can only be called once. Later calls * will return a null. */ public Table releaseTable() { long[] ptr = releaseTable(handle); if (ptr == null || ptr.length == 0) { return null; } else { return new Table(ptr); } } private static class ChildAndOffset { public NestedChildren child; public int newOffset; } private ChildAndOffset unflatten(int startOffset, String[] flatNames, int[] flatCounts) { ChildAndOffset ret = new ChildAndOffset(); int length = flatCounts[startOffset]; if (length == 0) { ret.newOffset = startOffset + 1; return ret; } else { String[] names = new String[length]; NestedChildren[] children = new NestedChildren[length]; int currentOffset = startOffset + 1; for (int i = 0; i < length; i++) { names[i] = flatNames[currentOffset]; ChildAndOffset tmp = unflatten(currentOffset, flatNames, flatCounts); children[i] = tmp.child; currentOffset = tmp.newOffset; } ret.newOffset = currentOffset; ret.child = new NestedChildren(names, children); return ret; } } NestedChildren getChildren() { if (children == null) { int[] flatCount = getFlattenedChildCounts(handle); String[] flatNames = getFlattenedColumnNames(handle); ChildAndOffset tmp = unflatten(0, flatNames, flatCount); children = tmp.child; if (children == null) { children = new NestedChildren(new String[0], new NestedChildren[0]); } } return children; } /** * Get the names of the top level columns. In the future new APIs can be added to get * names of child columns. */ public String[] getColumnNames() { return getChildren().getNames(); } public NestedChildren getChild(int i) { return getChildren().getChild(i); } public boolean isChildNested(int i) { return getChildren().isChildNested(i); } @Override public void close() { if (handle != 0) { close(handle); handle = 0; } } private static native void close(long handle); private static native long[] releaseTable(long handle); private static native String[] getFlattenedColumnNames(long handle); private static native int[] getFlattenedChildCounts(long handle); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/TableWriter.java
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Provides an interface for writing out Table information in multiple steps. * A TableWriter will be returned from one of various factory functions in the Table class that * let you set the format of the data and its destination. After that write can be called one or * more times. When you are done writing call close to finish. */ public abstract class TableWriter implements AutoCloseable { protected long writerHandle; TableWriter(long writerHandle) { this.writerHandle = writerHandle; } /** * Write out a table. Note that all columns must be in the same order each time this is called * and the format of each table cannot change. * @param table what to write out. */ abstract public void write(Table table) throws CudfException; @Override abstract public void close() throws CudfException; public static class WriteStatistics { public final long numCompressedBytes; // The number of bytes that were successfully compressed public final long numFailedBytes; // The number of bytes that failed to compress public final long numSkippedBytes; // The number of bytes that were skipped during compression public final double compressionRatio; // The compression ratio for the successfully compressed data public WriteStatistics(long numCompressedBytes, long numFailedBytes, long numSkippedBytes, double compressionRatio) { this.numCompressedBytes = numCompressedBytes; this.numFailedBytes = numFailedBytes; this.numSkippedBytes = numSkippedBytes; this.compressionRatio = compressionRatio; } } /** * Get the write statistics for the writer up to the last write call. * Currently, only ORC and Parquet writers support write statistics. * Calling this method on other writers will return null. * @return The write statistics. */ public WriteStatistics getWriteStatistics() { double[] statsData = getWriteStatistics(writerHandle); assert statsData.length == 4 : "Unexpected write statistics data length"; return new WriteStatistics((long) statsData[0], (long) statsData[1], (long) statsData[2], statsData[3]); } /** * Get the write statistics for the writer up to the last write call. * The data returned from native method is encoded as an array of doubles. * @param writerHandle The handle to the writer. * @return The write statistics. */ private static native double[] getWriteStatistics(long writerHandle); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/UnaryOp.java
/* * Copyright (c) 2019-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Mathematical unary operations. */ public enum UnaryOp { SIN(0), COS(1), TAN(2), ARCSIN(3), ARCCOS(4), ARCTAN(5), SINH(6), COSH(7), TANH(8), ARCSINH(9), ARCCOSH(10), ARCTANH(11), EXP(12), LOG(13), SQRT(14), CBRT(15), CEIL(16), FLOOR(17), ABS(18), RINT(19), BIT_COUNT(20), BIT_INVERT(21), NOT(22); private static final UnaryOp[] OPS = UnaryOp.values(); final int nativeId; UnaryOp(int nativeId) { this.nativeId = nativeId; } static UnaryOp fromNative(int nativeId) { for (UnaryOp type : OPS) { if (type.nativeId == nativeId) { return type; } } throw new IllegalArgumentException("Could not translate " + nativeId + " into a UnaryOp"); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/UnsafeMemoryAccessor.java
/* * * Copyright (c) 2019-2025, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; /** * UnsafeMemory Accessor for accessing memory on host */ class UnsafeMemoryAccessor { public static final long BYTE_ARRAY_OFFSET; public static final long SHORT_ARRAY_OFFSET; public static final long INT_ARRAY_OFFSET; public static final long LONG_ARRAY_OFFSET; public static final long FLOAT_ARRAY_OFFSET; public static final long DOUBLE_ARRAY_OFFSET; private static final sun.misc.Unsafe UNSAFE; /** * Limits the number of bytes to copy per {@link sun.misc.Unsafe#copyMemory(long, long, long)} to * allow safepoint polling during a large copy. */ private static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L; private static Logger log = LoggerFactory.getLogger(UnsafeMemoryAccessor.class); static { sun.misc.Unsafe unsafe = null; try { Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); unsafe = (sun.misc.Unsafe) unsafeField.get(null); BYTE_ARRAY_OFFSET = unsafe.arrayBaseOffset(byte[].class); SHORT_ARRAY_OFFSET = unsafe.arrayBaseOffset(short[].class); INT_ARRAY_OFFSET = unsafe.arrayBaseOffset(int[].class); LONG_ARRAY_OFFSET = unsafe.arrayBaseOffset(long[].class); FLOAT_ARRAY_OFFSET = unsafe.arrayBaseOffset(float[].class); DOUBLE_ARRAY_OFFSET = unsafe.arrayBaseOffset(double[].class); } catch (Throwable t) { log.error("Failed to get unsafe object, got this error: ", t); UNSAFE = null; throw new NullPointerException("Failed to get unsafe object, got this error: " + t.getMessage()); } UNSAFE = unsafe; } /** * Get the system memory page size. * @return system memory page size in bytes */ public static int pageSize() { return UNSAFE.pageSize(); } /** * Allocate bytes on host * @param bytes - number of bytes to allocate * @return - allocated address */ public static long allocate(long bytes) { return UNSAFE.allocateMemory(bytes); } /** * Free memory at that location * @param address - memory location */ public static void free(long address) { UNSAFE.freeMemory(address); } /** * Sets the values at this address repeatedly * @param address - memory location * @param size - number of bytes to set * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setMemory(long address, long size, byte value) { UNSAFE.setMemory(address, size, value); } /** * Sets the Byte value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setByte(long address, byte value) { UNSAFE.putByte(address, value); } /** * Sets an array of bytes. * @param address - memory address * @param values to be set * @param offset index into values to start at. * @param len the number of bytes to copy * @throws IndexOutOfBoundsException */ public static void setBytes(long address, byte[] values, long offset, long len) { copyMemory(values, UnsafeMemoryAccessor.BYTE_ARRAY_OFFSET + offset, null, address, len); } /** * Returns the Byte value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static byte getByte(long address) { return UNSAFE.getByte(address); } /** * Copy out an array of bytes. * @param dst where to write the data * @param dstOffset index into values to start writing at. * @param address src memory address * @param len the number of bytes to copy * @throws IndexOutOfBoundsException */ public static void getBytes(byte[] dst, long dstOffset, long address, long len) { copyMemory(null, address, dst, UnsafeMemoryAccessor.BYTE_ARRAY_OFFSET + dstOffset, len); } /** * Returns the Integer value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static int getInt(long address) { return UNSAFE.getInt(address); } /** * Copy out an array of ints. * @param dst where to write the data * @param dstIndex index into values to start writing at. * @param address src memory address * @param count the number of ints to copy * @throws IndexOutOfBoundsException */ public static void getInts(int[] dst, long dstIndex, long address, int count) { copyMemory(null, address, dst, UnsafeMemoryAccessor.INT_ARRAY_OFFSET + (dstIndex * 4), count * 4); } /** * Sets the Integer value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setInt(long address, int value) { UNSAFE.putInt(address, value); } /** * Sets an array of ints. * @param address memory address * @param values to be set * @param offset index into values to start at. * @param len the number of ints to copy * @throws IndexOutOfBoundsException */ public static void setInts(long address, int[] values, long offset, long len) { copyMemory(values, UnsafeMemoryAccessor.INT_ARRAY_OFFSET + (offset * 4), null, address, len * 4); } /** * Sets the Long value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setLong(long address, long value) { UNSAFE.putLong(address, value); } /** * Sets an array of longs. * @param address memory address * @param values to be set * @param offset index into values to start at * @param len the number of longs to copy * @throws IndexOutOfBoundsException */ public static void setLongs(long address, long[] values, long offset, long len) { copyMemory(values, UnsafeMemoryAccessor.LONG_ARRAY_OFFSET + (offset * 8), null, address, len * 8); } /** * Returns the Long value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static long getLong(long address) { return UNSAFE.getLong(address); } /** * Copy out an array of longs. * @param dst where to write the data * @param dstIndex index into values to start writing at. * @param address src memory address * @param count the number of longs to copy * @throws IndexOutOfBoundsException */ public static void getLongs(long[] dst, long dstIndex, long address, int count) { copyMemory(null, address, dst, UnsafeMemoryAccessor.LONG_ARRAY_OFFSET + (dstIndex * 8), count * 8); } /** * Returns the Short value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static short getShort(long address) { return UNSAFE.getShort(address); } /** * Sets the Short value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setShort(long address, short value) { UNSAFE.putShort(address, value); } /** * Sets an array of shorts. * @param address memory address * @param values to be set * @param offset index into values to start at * @param len the number of shorts to copy * @throws IndexOutOfBoundsException */ public static void setShorts(long address, short[] values, long offset, long len) { copyMemory(values, UnsafeMemoryAccessor.SHORT_ARRAY_OFFSET + (offset * 2), null, address, len * 2); } /** * Sets the Double value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setDouble(long address, double value) { UNSAFE.putDouble(address, value); } /** * Sets an array of doubles. * @param address memory address * @param values to be set * @param offset index into values to start at * @param len the number of doubles to copy * @throws IndexOutOfBoundsException */ public static void setDoubles(long address, double[] values, long offset, long len) { copyMemory(values, UnsafeMemoryAccessor.DOUBLE_ARRAY_OFFSET + (offset * 8), null, address, len * 8); } /** * Returns the Double value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static double getDouble(long address) { return UNSAFE.getDouble(address); } /** * Returns the Float value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static float getFloat(long address) { return UNSAFE.getFloat(address); } /** * Sets the Float value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setFloat(long address, float value) { UNSAFE.putFloat(address, value); } /** * Sets an array of floats. * @param address memory address * @param values to be set * @param offset the index in values to start at * @param len the number of floats to copy * @throws IndexOutOfBoundsException */ public static void setFloats(long address, float[] values, long offset, long len) { copyMemory(values, UnsafeMemoryAccessor.FLOAT_ARRAY_OFFSET + (offset * 4), null, address, len * 4); } /** * Returns the Boolean value at this address * @param address - memory address * @return - value * @throws IndexOutOfBoundsException */ public static boolean getBoolean(long address) { return getByte(address) != 0 ? true : false; } /** * Sets the Boolean value at that address * @param address - memory address * @param value - value to be set * @throws IndexOutOfBoundsException */ public static void setBoolean(long address, boolean value) { setByte(address, (byte) (value ? 1 : 0)); } /** * Copy memory from one address to the other. */ public static void copyMemory(Object src, long srcOffset, Object dst, long dstOffset, long length) { // Check if dstOffset is before or after srcOffset to determine if we should copy // forward or backwards. This is necessary in case src and dst overlap. if (dstOffset < srcOffset) { while (length > 0) { long size = Math.min(length, UNSAFE_COPY_THRESHOLD); UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size); length -= size; srcOffset += size; dstOffset += size; } } else { srcOffset += length; dstOffset += length; while (length > 0) { long size = Math.min(length, UNSAFE_COPY_THRESHOLD); srcOffset -= size; dstOffset -= size; UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size); length -= size; } } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/WindowOptions.java
/* * * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; /** * Options for rolling windows. */ public class WindowOptions implements AutoCloseable { enum FrameType {ROWS, RANGE} /** * Extent of (range) window bounds. * Analogous to cudf::range_window_bounds::extent_type. */ enum RangeExtentType { CURRENT_ROW(0), // Bounds defined as the first/last row that matches the current row. BOUNDED(1), // Bounds defined as the first/last row that falls within // a specified range from the current row. UNBOUNDED(2); // Bounds stretching to the first/last row in the entire group. public final int nominalValue; RangeExtentType(int n) { this.nominalValue = n; } } private final int minPeriods; private final Scalar precedingScalar; private final Scalar followingScalar; private final ColumnVector precedingCol; private final ColumnVector followingCol; private final int orderByColumnIndex; private final boolean orderByOrderAscending; private final FrameType frameType; private final RangeExtentType precedingBoundsExtent; private final RangeExtentType followingBoundsExtent; private WindowOptions(Builder builder) { this.minPeriods = builder.minPeriods; this.precedingScalar = builder.precedingScalar; if (precedingScalar != null) { precedingScalar.incRefCount(); } this.followingScalar = builder.followingScalar; if (followingScalar != null) { followingScalar.incRefCount(); } this.precedingCol = builder.precedingCol; if (precedingCol != null) { precedingCol.incRefCount(); } this.followingCol = builder.followingCol; if (followingCol != null) { followingCol.incRefCount(); } this.orderByColumnIndex = builder.orderByColumnIndex; this.orderByOrderAscending = builder.orderByOrderAscending; this.frameType = orderByColumnIndex == -1? FrameType.ROWS : FrameType.RANGE; this.precedingBoundsExtent = builder.precedingBoundsExtent; this.followingBoundsExtent = builder.followingBoundsExtent; } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof WindowOptions) { WindowOptions o = (WindowOptions) other; boolean ret = this.minPeriods == o.minPeriods && this.orderByColumnIndex == o.orderByColumnIndex && this.orderByOrderAscending == o.orderByOrderAscending && this.frameType == o.frameType && this.precedingBoundsExtent == o.precedingBoundsExtent && this.followingBoundsExtent == o.followingBoundsExtent; if (precedingCol != null) { ret = ret && precedingCol.equals(o.precedingCol); } if (followingCol != null) { ret = ret && followingCol.equals(o.followingCol); } if (precedingScalar != null) { ret = ret && precedingScalar.equals(o.precedingScalar); } if (followingScalar != null) { ret = ret && followingScalar.equals(o.followingScalar); } return ret; } return false; } @Override public int hashCode() { int ret = 7; ret = 31 * ret + minPeriods; ret = 31 * ret + orderByColumnIndex; ret = 31 * ret + Boolean.hashCode(orderByOrderAscending); ret = 31 * ret + frameType.hashCode(); if (precedingCol != null) { ret = 31 * ret + precedingCol.hashCode(); } if (followingCol != null) { ret = 31 * ret + followingCol.hashCode(); } if (precedingScalar != null) { ret = 31 * ret + precedingScalar.hashCode(); } if (followingScalar != null) { ret = 31 * ret + followingScalar.hashCode(); } ret = 31 * ret + precedingBoundsExtent.hashCode(); ret = 31 * ret + followingBoundsExtent.hashCode(); return ret; } public static Builder builder(){ return new Builder(); } int getMinPeriods() { return this.minPeriods; } Scalar getPrecedingScalar() { return this.precedingScalar; } Scalar getFollowingScalar() { return this.followingScalar; } ColumnVector getPrecedingCol() { return precedingCol; } ColumnVector getFollowingCol() { return this.followingCol; } @Deprecated int getTimestampColumnIndex() { return getOrderByColumnIndex(); } int getOrderByColumnIndex() { return this.orderByColumnIndex; } @Deprecated boolean isTimestampOrderAscending() { return isOrderByOrderAscending(); } boolean isOrderByOrderAscending() { return this.orderByOrderAscending; } boolean isUnboundedPreceding() { return this.precedingBoundsExtent == RangeExtentType.UNBOUNDED; } boolean isUnboundedFollowing() { return this.followingBoundsExtent == RangeExtentType.UNBOUNDED; } boolean isCurrentRowPreceding() { return this.precedingBoundsExtent == RangeExtentType.CURRENT_ROW; } boolean isCurrentRowFollowing() { return this.followingBoundsExtent == RangeExtentType.CURRENT_ROW; } RangeExtentType getPrecedingBoundsExtent() { return this.precedingBoundsExtent; } RangeExtentType getFollowingBoundsExtent() { return this.followingBoundsExtent; } FrameType getFrameType() { return frameType; } public static class Builder { private int minPeriods = 1; // for range window private Scalar precedingScalar = null; private Scalar followingScalar = null; private ColumnVector precedingCol = null; private ColumnVector followingCol = null; private int orderByColumnIndex = -1; private boolean orderByOrderAscending = true; private RangeExtentType precedingBoundsExtent = RangeExtentType.BOUNDED; private RangeExtentType followingBoundsExtent = RangeExtentType.BOUNDED; /** * Set the minimum number of observation required to evaluate an element. If there are not * enough elements for a given window a null is placed in the result instead. */ public Builder minPeriods(int minPeriods) { if (minPeriods < 0 ) { throw new IllegalArgumentException("Minimum observations must be non negative"); } this.minPeriods = minPeriods; return this; } /** * Set the size of the window, one entry per row. This does not take ownership of the * columns passed in so you have to be sure that the lifetime of the column outlives * this operation. * @param precedingCol the number of rows preceding the current row and * precedingCol will be live outside of WindowOptions. * @param followingCol the number of rows following the current row and * following will be live outside of WindowOptions. */ public Builder window(ColumnVector precedingCol, ColumnVector followingCol) { if (precedingCol == null || precedingCol.hasNulls()) { throw new IllegalArgumentException("preceding cannot be null or have nulls"); } if (followingCol == null || followingCol.hasNulls()) { throw new IllegalArgumentException("following cannot be null or have nulls"); } if (precedingBoundsExtent != RangeExtentType.BOUNDED || precedingScalar != null) { throw new IllegalStateException("preceding has already been set a different way"); } if (followingBoundsExtent != RangeExtentType.BOUNDED || followingScalar != null) { throw new IllegalStateException("following has already been set a different way"); } this.precedingCol = precedingCol; this.followingCol = followingCol; return this; } /** * Set the size of the range window. * @param precedingScalar the relative number preceding the current row and * the precedingScalar will be live outside of WindowOptions. * @param followingScalar the relative number following the current row and * the followingScalar will be live outside of WindowOptions */ public Builder window(Scalar precedingScalar, Scalar followingScalar) { return preceding(precedingScalar).following(followingScalar); } /** * @deprecated Use orderByColumnIndex(int index) */ @Deprecated public Builder timestampColumnIndex(int index) { return orderByColumnIndex(index); } public Builder orderByColumnIndex(int index) { this.orderByColumnIndex = index; return this; } /** * @deprecated Use orderByAscending() */ @Deprecated public Builder timestampAscending() { return orderByAscending(); } public Builder orderByAscending() { this.orderByOrderAscending = true; return this; } public Builder orderByDescending() { this.orderByOrderAscending = false; return this; } /** * @deprecated Use orderByDescending() */ @Deprecated public Builder timestampDescending() { return orderByDescending(); } public Builder currentRowPreceding() { if (precedingCol != null || precedingScalar != null) { throw new IllegalStateException("preceding has already been set a different way"); } this.precedingBoundsExtent = RangeExtentType.CURRENT_ROW; return this; } public Builder currentRowFollowing() { if (followingCol != null || followingScalar != null) { throw new IllegalStateException("following has already been set a different way"); } this.followingBoundsExtent = RangeExtentType.CURRENT_ROW; return this; } public Builder unboundedPreceding() { if (precedingCol != null || precedingScalar != null) { throw new IllegalStateException("preceding has already been set a different way"); } this.precedingBoundsExtent = RangeExtentType.UNBOUNDED; return this; } public Builder unboundedFollowing() { if (followingCol != null || followingScalar != null) { throw new IllegalStateException("following has already been set a different way"); } this.followingBoundsExtent = RangeExtentType.UNBOUNDED; return this; } /** * Set the relative number preceding the current row for range window * @return this for chaining */ public Builder preceding(Scalar preceding) { if (preceding == null || !preceding.isValid()) { throw new IllegalArgumentException("preceding cannot be null"); } if (precedingBoundsExtent != RangeExtentType.BOUNDED || precedingCol != null) { throw new IllegalStateException("preceding has already been set a different way"); } this.precedingScalar = preceding; return this; } /** * Set the relative number following the current row for range window * @return this for chaining */ public Builder following(Scalar following) { if (following == null || !following.isValid()) { throw new IllegalArgumentException("following cannot be null"); } if (followingBoundsExtent != RangeExtentType.BOUNDED || followingCol != null) { throw new IllegalStateException("following has already been set a different way"); } this.followingScalar = following; return this; } public WindowOptions build() { return new WindowOptions(this); } } public synchronized WindowOptions incRefCount() { if (precedingScalar != null) { precedingScalar.incRefCount(); } if (followingScalar != null) { followingScalar.incRefCount(); } if (precedingCol != null) { precedingCol.incRefCount(); } if (followingCol != null) { followingCol.incRefCount(); } return this; } @Override public void close() { if (precedingScalar != null) { precedingScalar.close(); } if (followingScalar != null) { followingScalar.close(); } if (precedingCol != null) { precedingCol.close(); } if (followingCol != null) { followingCol.close(); } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/WriterOptions.java
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf; import java.util.ArrayList; import java.util.Arrays; import java.util.List; class WriterOptions { private final String[] columnNames; private final boolean[] columnNullability; <T extends WriterBuilder> WriterOptions(T builder) { columnNames = (String[]) builder.columnNames.toArray(new String[builder.columnNames.size()]); columnNullability = new boolean[builder.columnNullability.size()]; for (int i = 0; i < builder.columnNullability.size(); i++) { columnNullability[i] = (boolean)builder.columnNullability.get(i); } } public String[] getColumnNames() { return columnNames; } public boolean[] getColumnNullability() { return columnNullability; } protected static class WriterBuilder<T extends WriterBuilder> { final List<String> columnNames = new ArrayList<>(); final List<Boolean> columnNullability = new ArrayList<>(); /** * Add column name(s). For Parquet column names are not optional. * @param columnNames */ public T withColumnNames(String... columnNames) { this.columnNames.addAll(Arrays.asList(columnNames)); for (int i = 0; i < columnNames.length; i++) { this.columnNullability.add(true); } return (T) this; } /** * Add column name that is not nullable * @param columnNames */ public T withNotNullableColumnNames(String... columnNames) { this.columnNames.addAll(Arrays.asList(columnNames)); for (int i = 0; i < columnNames.length; i++) { this.columnNullability.add(false); } return (T) this; } } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/AstExpression.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** Base class of every node in an AST */ public abstract class AstExpression { /** * Enumeration for the types of AST nodes that can appear in a serialized AST. * NOTE: This must be kept in sync with the `jni_serialized_node_type` in CompiledExpression.cpp! */ protected enum ExpressionType { VALID_LITERAL(0), NULL_LITERAL(1), COLUMN_REFERENCE(2), UNARY_EXPRESSION(3), BINARY_EXPRESSION(4); private final byte nativeId; ExpressionType(int nativeId) { this.nativeId = (byte) nativeId; assert this.nativeId == nativeId; } /** Get the size in bytes to serialize this node type */ int getSerializedSize() { return Byte.BYTES; } /** Serialize this node type to the specified buffer */ void serialize(ByteBuffer bb) { bb.put(nativeId); } } public CompiledExpression compile() { int size = getSerializedSize(); ByteBuffer bb = ByteBuffer.allocate(size); bb.order(ByteOrder.nativeOrder()); serialize(bb); return new CompiledExpression(bb.array()); } /** Get the size in bytes of the serialized form of this node and all child nodes */ abstract int getSerializedSize(); /** * Serialize this node and all child nodes. * @param bb buffer to receive the serialized data */ abstract void serialize(ByteBuffer bb); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/BinaryOperation.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; /** A binary operation consisting of an operator and two operands. */ public class BinaryOperation extends AstExpression { private final BinaryOperator op; private final AstExpression leftInput; private final AstExpression rightInput; public BinaryOperation(BinaryOperator op, AstExpression leftInput, AstExpression rightInput) { this.op = op; this.leftInput = leftInput; this.rightInput = rightInput; } @Override int getSerializedSize() { return ExpressionType.BINARY_EXPRESSION.getSerializedSize() + op.getSerializedSize() + leftInput.getSerializedSize() + rightInput.getSerializedSize(); } @Override void serialize(ByteBuffer bb) { ExpressionType.BINARY_EXPRESSION.serialize(bb); op.serialize(bb); leftInput.serialize(bb); rightInput.serialize(bb); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/BinaryOperator.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; /** * Enumeration of AST operators that can appear in a binary operation. * NOTE: This must be kept in sync with `jni_to_binary_operator` in CompiledExpression.cpp! */ public enum BinaryOperator { ADD(0), // operator + SUB(1), // operator - MUL(2), // operator * DIV(3), // operator / using common type of lhs and rhs TRUE_DIV(4), // operator / after promoting type to floating point FLOOR_DIV(5), // operator / after promoting to 64 bit floating point and then flooring the result MOD(6), // operator % PYMOD(7), // operator % using Python's sign rules for negatives POW(8), // lhs ^ rhs EQUAL(9), // operator == NULL_EQUAL(10), // operator == using Spark rules for null inputs NOT_EQUAL(11), // operator != LESS(12), // operator < GREATER(13), // operator > LESS_EQUAL(14), // operator <= GREATER_EQUAL(15), // operator >= BITWISE_AND(16), // operator & BITWISE_OR(17), // operator | BITWISE_XOR(18), // operator ^ LOGICAL_AND(19), // operator && NULL_LOGICAL_AND(20), // operator && using Spark rules for null inputs LOGICAL_OR(21), // operator || NULL_LOGICAL_OR(22); // operator || using Spark rules for null inputs private final byte nativeId; BinaryOperator(int nativeId) { this.nativeId = (byte) nativeId; assert this.nativeId == nativeId; } /** Get the size in bytes to serialize this operator */ int getSerializedSize() { return Byte.BYTES; } /** Serialize this operator to the specified buffer */ void serialize(ByteBuffer bb) { bb.put(nativeId); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/ColumnReference.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; /** A reference to a column in an input table. */ public final class ColumnReference extends AstExpression { private final int columnIndex; private final TableReference tableSource; /** Construct a column reference to either the only or leftmost input table */ public ColumnReference(int columnIndex) { this(columnIndex, TableReference.LEFT); } /** Construct a column reference to the specified column index in the specified table */ public ColumnReference(int columnIndex, TableReference tableSource) { this.columnIndex = columnIndex; this.tableSource = tableSource; } @Override int getSerializedSize() { // node type + table ref + column index return ExpressionType.COLUMN_REFERENCE.getSerializedSize() + tableSource.getSerializedSize() + Integer.BYTES; } @Override void serialize(ByteBuffer bb) { ExpressionType.COLUMN_REFERENCE.serialize(bb); tableSource.serialize(bb); bb.putInt(columnIndex); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/CompiledExpression.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import ai.rapids.cudf.ColumnVector; import ai.rapids.cudf.MemoryCleaner; import ai.rapids.cudf.NativeDepsLoader; import ai.rapids.cudf.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** This class wraps a native compiled AST and must be closed to avoid native memory leaks. */ public class CompiledExpression implements AutoCloseable { static { NativeDepsLoader.loadNativeDeps(); } private static final Logger log = LoggerFactory.getLogger(CompiledExpression.class); private static class CompiledExpressionCleaner extends MemoryCleaner.Cleaner { private long nativeHandle; CompiledExpressionCleaner(long nativeHandle) { this.nativeHandle = nativeHandle; } @Override protected synchronized boolean cleanImpl(boolean logErrorIfNotClean) { long origAddress = nativeHandle; boolean neededCleanup = nativeHandle != 0; if (neededCleanup) { try { destroy(nativeHandle); } finally { nativeHandle = 0; } if (logErrorIfNotClean) { log.error("AN AST COMPILED EXPRESSION WAS LEAKED (ID: " + id + " " + Long.toHexString(origAddress)); } } return neededCleanup; } @Override public boolean isClean() { return nativeHandle == 0; } } private final CompiledExpressionCleaner cleaner; private boolean isClosed = false; /** Construct a compiled expression from a serialized AST */ CompiledExpression(byte[] serializedExpression) { this(compile(serializedExpression)); } /** Construct a compiled expression from a native compiled AST pointer */ CompiledExpression(long nativeHandle) { this.cleaner = new CompiledExpressionCleaner(nativeHandle); MemoryCleaner.register(this, cleaner); cleaner.addRef(); } /** * Compute a new column by applying this AST expression to the specified table. All * {@link ColumnReference} instances within the expression will use the sole input table, * even if they try to specify a non-existent table, e.g.: {@link TableReference#RIGHT}. * @param table input table for this expression * @return new column computed from this expression applied to the input table */ public ColumnVector computeColumn(Table table) { return new ColumnVector(computeColumn(cleaner.nativeHandle, table.getNativeView())); } @Override public synchronized void close() { cleaner.delRef(); if (isClosed) { cleaner.logRefCountDebug("double free " + this); throw new IllegalStateException("Close called too many times " + this); } cleaner.clean(false); isClosed = true; } /** Returns the native address of a compiled expression. Intended for internal cudf use only. */ public long getNativeHandle() { return cleaner.nativeHandle; } private static native long compile(byte[] serializedExpression); private static native long computeColumn(long astHandle, long tableHandle); private static native void destroy(long handle); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/Literal.java
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import ai.rapids.cudf.DType; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; /** A literal value in an AST expression. */ public final class Literal extends AstExpression { private final DType type; private final byte[] serializedValue; /** Construct a null literal of the specified type. */ public static Literal ofNull(DType type) { return new Literal(type, null); } /** Construct a boolean literal with the specified value. */ public static Literal ofBoolean(boolean value) { return new Literal(DType.BOOL8, new byte[] { value ? (byte) 1 : (byte) 0 }); } /** Construct a boolean literal with the specified value or null. */ public static Literal ofBoolean(Boolean value) { if (value == null) { return ofNull(DType.BOOL8); } return ofBoolean(value.booleanValue()); } /** Construct a byte literal with the specified value. */ public static Literal ofByte(byte value) { return new Literal(DType.INT8, new byte[] { value }); } /** Construct a byte literal with the specified value or null. */ public static Literal ofByte(Byte value) { if (value == null) { return ofNull(DType.INT8); } return ofByte(value.byteValue()); } /** Construct a short literal with the specified value. */ public static Literal ofShort(short value) { byte[] serializedValue = new byte[Short.BYTES]; ByteBuffer.wrap(serializedValue).order(ByteOrder.nativeOrder()).putShort(value); return new Literal(DType.INT16, serializedValue); } /** Construct a short literal with the specified value or null. */ public static Literal ofShort(Short value) { if (value == null) { return ofNull(DType.INT16); } return ofShort(value.shortValue()); } /** Construct an integer literal with the specified value. */ public static Literal ofInt(int value) { return ofIntBasedType(DType.INT32, value); } /** Construct an integer literal with the specified value or null. */ public static Literal ofInt(Integer value) { if (value == null) { return ofNull(DType.INT32); } return ofInt(value.intValue()); } /** Construct a long literal with the specified value. */ public static Literal ofLong(long value) { return ofLongBasedType(DType.INT64, value); } /** Construct a long literal with the specified value or null. */ public static Literal ofLong(Long value) { if (value == null) { return ofNull(DType.INT64); } return ofLong(value.longValue()); } /** Construct a float literal with the specified value. */ public static Literal ofFloat(float value) { byte[] serializedValue = new byte[Float.BYTES]; ByteBuffer.wrap(serializedValue).order(ByteOrder.nativeOrder()).putFloat(value); return new Literal(DType.FLOAT32, serializedValue); } /** Construct a float literal with the specified value or null. */ public static Literal ofFloat(Float value) { if (value == null) { return ofNull(DType.FLOAT32); } return ofFloat(value.floatValue()); } /** Construct a double literal with the specified value. */ public static Literal ofDouble(double value) { byte[] serializedValue = new byte[Double.BYTES]; ByteBuffer.wrap(serializedValue).order(ByteOrder.nativeOrder()).putDouble(value); return new Literal(DType.FLOAT64, serializedValue); } /** Construct a double literal with the specified value or null. */ public static Literal ofDouble(Double value) { if (value == null) { return ofNull(DType.FLOAT64); } return ofDouble(value.doubleValue()); } /** Construct a timestamp days literal with the specified value. */ public static Literal ofTimestampDaysFromInt(int value) { return ofIntBasedType(DType.TIMESTAMP_DAYS, value); } /** Construct a timestamp days literal with the specified value or null. */ public static Literal ofTimestampDaysFromInt(Integer value) { if (value == null) { return ofNull(DType.TIMESTAMP_DAYS); } return ofTimestampDaysFromInt(value.intValue()); } /** Construct a long-based timestamp literal with the specified value. */ public static Literal ofTimestampFromLong(DType type, long value) { if (!type.isTimestampType()) { throw new IllegalArgumentException("type is not a timestamp: " + type); } if (type.equals(DType.TIMESTAMP_DAYS)) { int intValue = (int)value; if (value != intValue) { throw new IllegalArgumentException("value too large for type " + type + ": " + value); } return ofTimestampDaysFromInt(intValue); } return ofLongBasedType(type, value); } /** Construct a long-based timestamp literal with the specified value or null. */ public static Literal ofTimestampFromLong(DType type, Long value) { if (value == null) { return ofNull(type); } return ofTimestampFromLong(type, value.longValue()); } /** Construct a duration days literal with the specified value. */ public static Literal ofDurationDaysFromInt(int value) { return ofIntBasedType(DType.DURATION_DAYS, value); } /** Construct a duration days literal with the specified value or null. */ public static Literal ofDurationDaysFromInt(Integer value) { if (value == null) { return ofNull(DType.DURATION_DAYS); } return ofDurationDaysFromInt(value.intValue()); } /** Construct a long-based duration literal with the specified value. */ public static Literal ofDurationFromLong(DType type, long value) { if (!type.isDurationType()) { throw new IllegalArgumentException("type is not a timestamp: " + type); } if (type.equals(DType.DURATION_DAYS)) { int intValue = (int)value; if (value != intValue) { throw new IllegalArgumentException("value too large for type " + type + ": " + value); } return ofDurationDaysFromInt(intValue); } return ofLongBasedType(type, value); } /** Construct a long-based duration literal with the specified value or null. */ public static Literal ofDurationFromLong(DType type, Long value) { if (value == null) { return ofNull(type); } return ofDurationFromLong(type, value.longValue()); } /** Construct a string literal with the specified value or null. */ public static Literal ofString(String value) { if (value == null) { return ofNull(DType.STRING); } return ofUTF8String(value.getBytes(StandardCharsets.UTF_8)); } /** Construct a string literal directly with byte array to skip transcoding. */ public static Literal ofUTF8String(byte[] stringBytes) { if (stringBytes == null) { return ofNull(DType.STRING); } byte[] serializedValue = new byte[stringBytes.length + Integer.BYTES]; ByteBuffer.wrap(serializedValue).order(ByteOrder.nativeOrder()).putInt(stringBytes.length); System.arraycopy(stringBytes, 0, serializedValue, Integer.BYTES, stringBytes.length); return new Literal(DType.STRING, serializedValue); } Literal(DType type, byte[] serializedValue) { this.type = type; this.serializedValue = serializedValue; } @Override int getSerializedSize() { ExpressionType nodeType = serializedValue != null ? ExpressionType.VALID_LITERAL : ExpressionType.NULL_LITERAL; int size = nodeType.getSerializedSize() + getDataTypeSerializedSize(); if (serializedValue != null) { size += serializedValue.length; } return size; } @Override void serialize(ByteBuffer bb) { ExpressionType nodeType = serializedValue != null ? ExpressionType.VALID_LITERAL : ExpressionType.NULL_LITERAL; nodeType.serialize(bb); serializeDataType(bb); if (serializedValue != null) { bb.put(serializedValue); } } private int getDataTypeSerializedSize() { int nativeTypeId = type.getTypeId().getNativeId(); assert nativeTypeId == (byte) nativeTypeId : "Type ID does not fit in a byte"; if (type.isDecimalType()) { assert type.getScale() == (byte) type.getScale() : "Decimal scale does not fit in a byte"; return 2; } return 1; } private void serializeDataType(ByteBuffer bb) { byte nativeTypeId = (byte) type.getTypeId().getNativeId(); assert nativeTypeId == type.getTypeId().getNativeId() : "DType ID does not fit in a byte"; bb.put(nativeTypeId); if (type.isDecimalType()) { byte scale = (byte) type.getScale(); assert scale == (byte) type.getScale() : "Decimal scale does not fit in a byte"; bb.put(scale); } } private static Literal ofIntBasedType(DType type, int value) { assert type.getSizeInBytes() == Integer.BYTES; byte[] serializedValue = new byte[Integer.BYTES]; ByteBuffer.wrap(serializedValue).order(ByteOrder.nativeOrder()).putInt(value); return new Literal(type, serializedValue); } private static Literal ofLongBasedType(DType type, long value) { assert type.getSizeInBytes() == Long.BYTES; byte[] serializedValue = new byte[Long.BYTES]; ByteBuffer.wrap(serializedValue).order(ByteOrder.nativeOrder()).putLong(value); return new Literal(type, serializedValue); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/TableReference.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; /** * Enumeration of tables that can be referenced in an AST. * NOTE: This must be kept in sync with `jni_to_table_reference` code in CompiledExpression.cpp! */ public enum TableReference { LEFT(0), RIGHT(1); // OUTPUT is an AST implementation detail and should not appear in user-built expressions. private final byte nativeId; TableReference(int nativeId) { this.nativeId = (byte) nativeId; assert this.nativeId == nativeId; } /** Get the size in bytes to serialize this table reference */ int getSerializedSize() { return Byte.BYTES; } /** Serialize this table reference to the specified buffer */ void serialize(ByteBuffer bb) { bb.put(nativeId); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/UnaryOperation.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; /** A unary operation consisting of an operator and an operand. */ public final class UnaryOperation extends AstExpression { private final UnaryOperator op; private final AstExpression input; public UnaryOperation(UnaryOperator op, AstExpression input) { this.op = op; this.input = input; } @Override int getSerializedSize() { return ExpressionType.UNARY_EXPRESSION.getSerializedSize() + op.getSerializedSize() + input.getSerializedSize(); } @Override void serialize(ByteBuffer bb) { ExpressionType.UNARY_EXPRESSION.serialize(bb); op.serialize(bb); input.serialize(bb); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/ast/UnaryOperator.java
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.ast; import java.nio.ByteBuffer; /** * Enumeration of AST operators that can appear in a unary operation. * NOTE: This must be kept in sync with `jni_to_unary_operator` in CompiledExpression.cpp! */ public enum UnaryOperator { IDENTITY(0), // Identity function IS_NULL(1), // Check if operand is null SIN(2), // Trigonometric sine COS(3), // Trigonometric cosine TAN(4), // Trigonometric tangent ARCSIN(5), // Trigonometric sine inverse ARCCOS(6), // Trigonometric cosine inverse ARCTAN(7), // Trigonometric tangent inverse SINH(8), // Hyperbolic sine COSH(9), // Hyperbolic cosine TANH(10), // Hyperbolic tangent ARCSINH(11), // Hyperbolic sine inverse ARCCOSH(12), // Hyperbolic cosine inverse ARCTANH(13), // Hyperbolic tangent inverse EXP(14), // Exponential (base e, Euler number) LOG(15), // Natural Logarithm (base e) SQRT(16), // Square-root (x^0.5) CBRT(17), // Cube-root (x^(1.0/3)) CEIL(18), // Smallest integer value not less than arg FLOOR(19), // largest integer value not greater than arg ABS(20), // Absolute value RINT(21), // Rounds the floating-point argument arg to an integer value BIT_INVERT(22), // Bitwise Not (~) NOT(23), // Logical Not (!) CAST_TO_INT64(24), // Cast value to int64_t CAST_TO_UINT64(25), // Cast value to uint64_t CAST_TO_FLOAT64(26); // Cast value to double private final byte nativeId; UnaryOperator(int nativeId) { this.nativeId = (byte) nativeId; assert this.nativeId == nativeId; } /** Get the size in bytes to serialize this operator */ int getSerializedSize() { return Byte.BYTES; } /** Serialize this operator to the specified buffer */ void serialize(ByteBuffer bb) { bb.put(nativeId); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/BatchedCompressor.java
/* * Copyright (c) 2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; import ai.rapids.cudf.BaseDeviceMemoryBuffer; import ai.rapids.cudf.CloseableArray; import ai.rapids.cudf.Cuda; import ai.rapids.cudf.DeviceMemoryBuffer; import ai.rapids.cudf.HostMemoryBuffer; import ai.rapids.cudf.MemoryBuffer; import ai.rapids.cudf.NvtxColor; import ai.rapids.cudf.NvtxRange; /** Multi-buffer compressor */ public abstract class BatchedCompressor { static final long MAX_CHUNK_SIZE = 16777216; // 16MiB in bytes // each chunk has a 64-bit integer value as metadata containing the compressed size static final long METADATA_BYTES_PER_CHUNK = 8; private final long chunkSize; private final long maxIntermediateBufferSize; private final long maxOutputChunkSize; /** * Construct a batched compressor instance * @param chunkSize maximum amount of uncompressed data to compress as a single chunk. * Inputs larger than this will be compressed in multiple chunks. * @param maxIntermediateBufferSize desired maximum size of intermediate device * buffers used during compression. */ public BatchedCompressor(long chunkSize, long maxOutputChunkSize, long maxIntermediateBufferSize) { validateChunkSize(chunkSize); assert maxOutputChunkSize < Integer.MAX_VALUE; this.chunkSize = chunkSize; this.maxOutputChunkSize = maxOutputChunkSize; this.maxIntermediateBufferSize = Math.max(maxOutputChunkSize, maxIntermediateBufferSize); } /** * Compress a batch of buffers. The input buffers will be closed. * @param origInputs buffers to compress * @param stream CUDA stream to use * @return compressed buffers corresponding to the input buffers */ public DeviceMemoryBuffer[] compress(BaseDeviceMemoryBuffer[] origInputs, Cuda.Stream stream) { try (CloseableArray<BaseDeviceMemoryBuffer> inputs = CloseableArray.wrap(origInputs)) { if (chunkSize <= 0) { throw new IllegalArgumentException("Illegal chunk size: " + chunkSize); } final int numInputs = inputs.size(); if (numInputs == 0) { return new DeviceMemoryBuffer[0]; } // Each buffer is broken up into chunkSize chunks for compression. Calculate how many // chunks are needed for each input buffer. int[] chunksPerInput = new int[numInputs]; int numChunks = 0; for (int i = 0; i < numInputs; i++) { BaseDeviceMemoryBuffer buffer = inputs.get(i); int numBufferChunks = getNumChunksInBuffer(buffer); chunksPerInput[i] = numBufferChunks; numChunks += numBufferChunks; } // Allocate buffers for each chunk and generate parallel lists of chunk source addresses, // chunk destination addresses, and sizes. try (CloseableArray<DeviceMemoryBuffer> compressedBuffers = allocCompressedBuffers(numChunks, stream); DeviceMemoryBuffer compressedChunkSizes = DeviceMemoryBuffer.allocate(numChunks * 8L, stream)) { long[] inputChunkAddrs = new long[numChunks]; long[] inputChunkSizes = new long[numChunks]; long[] outputChunkAddrs = new long[numChunks]; buildAddrsAndSizes(inputs, inputChunkAddrs, inputChunkSizes, compressedBuffers, outputChunkAddrs); final long tempBufferSize = batchedCompressGetTempSize(numChunks, chunkSize); try (DeviceMemoryBuffer addrsAndSizes = putAddrsAndSizesOnDevice(inputChunkAddrs, inputChunkSizes, outputChunkAddrs, stream); DeviceMemoryBuffer tempBuffer = DeviceMemoryBuffer.allocate(tempBufferSize, stream)) { final long devOutputAddrsPtr = addrsAndSizes.getAddress() + numChunks * 8L; final long devInputSizesPtr = devOutputAddrsPtr + numChunks * 8L; batchedCompressAsync(addrsAndSizes.getAddress(), devInputSizesPtr, chunkSize, numChunks, tempBuffer.getAddress(), tempBufferSize, devOutputAddrsPtr, compressedChunkSizes.getAddress(), stream.getStream()); } // Synchronously copy the resulting compressed sizes per chunk. long[] outputChunkSizes = getOutputChunkSizes(compressedChunkSizes, stream); // inputs are no longer needed at this point, so free them early inputs.close(); // Combine compressed chunks into output buffers corresponding to each original input return stitchOutput(chunksPerInput, compressedChunkSizes, outputChunkAddrs, outputChunkSizes, stream); } } } static void validateChunkSize(long chunkSize) { if (chunkSize <= 0 || chunkSize > MAX_CHUNK_SIZE) { throw new IllegalArgumentException("Invalid chunk size: " + chunkSize + " Max chunk size is: " + MAX_CHUNK_SIZE + " bytes"); } } private static long ceilingDivide(long x, long y) { return (x + y - 1) / y; } private int getNumChunksInBuffer(MemoryBuffer buffer) { return (int) ceilingDivide(buffer.getLength(), chunkSize); } private CloseableArray<DeviceMemoryBuffer> allocCompressedBuffers(long numChunks, Cuda.Stream stream) { final long chunksPerBuffer = maxIntermediateBufferSize / maxOutputChunkSize; final long numBuffers = ceilingDivide(numChunks, chunksPerBuffer); if (numBuffers > Integer.MAX_VALUE) { throw new IllegalStateException("Too many chunks"); } try (NvtxRange range = new NvtxRange("allocCompressedBuffers", NvtxColor.YELLOW)) { CloseableArray<DeviceMemoryBuffer> buffers = CloseableArray.wrap( new DeviceMemoryBuffer[(int) numBuffers]); try { // allocate all of the max-chunks intermediate compressed buffers for (int i = 0; i < buffers.size() - 1; ++i) { buffers.set(i, DeviceMemoryBuffer.allocate(chunksPerBuffer * maxOutputChunkSize, stream)); } // allocate the tail intermediate compressed buffer that may be smaller than the others buffers.set(buffers.size() - 1, DeviceMemoryBuffer.allocate( (numChunks - chunksPerBuffer * (buffers.size() - 1)) * maxOutputChunkSize, stream)); return buffers; } catch (Exception e) { buffers.close(e); throw e; } } } // Fill in the inputChunkAddrs, inputChunkSizes, and outputChunkAddrs arrays to point // into the chunks in the input and output buffers. private void buildAddrsAndSizes(CloseableArray<BaseDeviceMemoryBuffer> inputs, long[] inputChunkAddrs, long[] inputChunkSizes, CloseableArray<DeviceMemoryBuffer> compressedBuffers, long[] outputChunkAddrs) { // setup the input addresses and sizes int chunkIdx = 0; for (BaseDeviceMemoryBuffer input : inputs.getArray()) { final int numChunksInBuffer = getNumChunksInBuffer(input); for (int i = 0; i < numChunksInBuffer; i++) { inputChunkAddrs[chunkIdx] = input.getAddress() + i * chunkSize; inputChunkSizes[chunkIdx] = (i != numChunksInBuffer - 1) ? chunkSize : (input.getLength() - (long) i * chunkSize); ++chunkIdx; } } assert chunkIdx == inputChunkAddrs.length; assert chunkIdx == inputChunkSizes.length; // setup output addresses chunkIdx = 0; for (DeviceMemoryBuffer buffer : compressedBuffers.getArray()) { assert buffer.getLength() % maxOutputChunkSize == 0; long numChunksInBuffer = buffer.getLength() / maxOutputChunkSize; long baseAddr = buffer.getAddress(); for (int i = 0; i < numChunksInBuffer; i++) { outputChunkAddrs[chunkIdx++] = baseAddr + i * maxOutputChunkSize; } } assert chunkIdx == outputChunkAddrs.length; } // Write input addresses, output addresses and sizes contiguously into a DeviceMemoryBuffer. private DeviceMemoryBuffer putAddrsAndSizesOnDevice(long[] inputAddrs, long[] inputSizes, long[] outputAddrs, Cuda.Stream stream) { final long totalSize = inputAddrs.length * 8L * 3; // space for input, output, and size arrays final long outputAddrsOffset = inputAddrs.length * 8L; final long sizesOffset = outputAddrsOffset + inputAddrs.length * 8L; try (NvtxRange range = new NvtxRange("putAddrsAndSizesOnDevice", NvtxColor.YELLOW)) { try (HostMemoryBuffer hostbuf = HostMemoryBuffer.allocate(totalSize); DeviceMemoryBuffer result = DeviceMemoryBuffer.allocate(totalSize)) { hostbuf.setLongs(0, inputAddrs, 0, inputAddrs.length); hostbuf.setLongs(outputAddrsOffset, outputAddrs, 0, outputAddrs.length); for (int i = 0; i < inputSizes.length; i++) { hostbuf.setLong(sizesOffset + i * 8L, inputSizes[i]); } result.copyFromHostBuffer(hostbuf, stream); result.incRefCount(); return result; } } } // Synchronously copy the resulting compressed sizes from device memory to host memory. private long[] getOutputChunkSizes(BaseDeviceMemoryBuffer devChunkSizes, Cuda.Stream stream) { try (NvtxRange range = new NvtxRange("getOutputChunkSizes", NvtxColor.YELLOW)) { try (HostMemoryBuffer hostbuf = HostMemoryBuffer.allocate(devChunkSizes.getLength())) { hostbuf.copyFromDeviceBuffer(devChunkSizes, stream); int numChunks = (int) (devChunkSizes.getLength() / 8); long[] result = new long[numChunks]; for (int i = 0; i < numChunks; i++) { long size = hostbuf.getLong(i * 8L); assert size < Integer.MAX_VALUE : "output size is too big"; result[i] = size; } return result; } } } // Stitch together the individual chunks into the result buffers. // Each result buffer has metadata at the beginning, followed by compressed chunks. // This is done by building up parallel lists of source addr, dest addr and size and // then calling multiBufferCopyAsync() private DeviceMemoryBuffer[] stitchOutput(int[] chunksPerInput, DeviceMemoryBuffer compressedChunkSizes, long[] outputChunkAddrs, long[] outputChunkSizes, Cuda.Stream stream) { try (NvtxRange range = new NvtxRange("stitchOutput", NvtxColor.YELLOW)) { final int numOutputs = chunksPerInput.length; final long chunkSizesAddr = compressedChunkSizes.getAddress(); long[] outputBufferSizes = calcOutputBufferSizes(chunksPerInput, outputChunkSizes); try (CloseableArray<DeviceMemoryBuffer> outputs = CloseableArray.wrap(new DeviceMemoryBuffer[numOutputs])) { // Each chunk needs to be copied, and each output needs a copy of the // compressed chunk size vector representing the metadata. final int totalBuffersToCopy = numOutputs + outputChunkAddrs.length; long[] destAddrs = new long[totalBuffersToCopy]; long[] srcAddrs = new long[totalBuffersToCopy]; long[] sizes = new long[totalBuffersToCopy]; int copyBufferIdx = 0; int chunkIdx = 0; for (int outputIdx = 0; outputIdx < numOutputs; outputIdx++) { DeviceMemoryBuffer outputBuffer = DeviceMemoryBuffer.allocate(outputBufferSizes[outputIdx]); outputs.set(outputIdx, outputBuffer); final long outputBufferAddr = outputBuffer.getAddress(); final long numChunks = chunksPerInput[outputIdx]; final long metadataSize = numChunks * METADATA_BYTES_PER_CHUNK; // setup a copy of the metadata at the front of the output buffer srcAddrs[copyBufferIdx] = chunkSizesAddr + chunkIdx * 8; destAddrs[copyBufferIdx] = outputBufferAddr; sizes[copyBufferIdx] = metadataSize; ++copyBufferIdx; // setup copies of the compressed chunks for this output buffer long nextChunkAddr = outputBufferAddr + metadataSize; for (int i = 0; i < numChunks; ++i) { srcAddrs[copyBufferIdx] = outputChunkAddrs[chunkIdx]; destAddrs[copyBufferIdx] = nextChunkAddr; final long chunkSize = outputChunkSizes[chunkIdx]; sizes[copyBufferIdx] = chunkSize; copyBufferIdx++; chunkIdx++; nextChunkAddr += chunkSize; } } assert copyBufferIdx == totalBuffersToCopy; assert chunkIdx == outputChunkAddrs.length; assert chunkIdx == outputChunkSizes.length; Cuda.multiBufferCopyAsync(destAddrs, srcAddrs, sizes, stream); return outputs.release(); } } } // Calculate the sizes for each output buffer (metadata plus size of compressed chunks) private long[] calcOutputBufferSizes(int[] chunksPerInput, long[] outputChunkSizes) { long[] sizes = new long[chunksPerInput.length]; int chunkIdx = 0; for (int i = 0; i < sizes.length; i++) { final int chunksInBuffer = chunksPerInput[i]; final int chunkEndIdx = chunkIdx + chunksInBuffer; // metadata stored in front of compressed data long bufferSize = METADATA_BYTES_PER_CHUNK * chunksInBuffer; // add in the compressed chunk sizes to get the total size while (chunkIdx < chunkEndIdx) { bufferSize += outputChunkSizes[chunkIdx++]; } sizes[i] = bufferSize; } assert chunkIdx == outputChunkSizes.length; return sizes; } /** * Get the temporary workspace size required to perform compression of an entire batch. * @param batchSize number of chunks in the batch * @param maxChunkSize maximum size of an uncompressed chunk in bytes * @return The size of required temporary workspace in bytes to compress the batch. */ protected abstract long batchedCompressGetTempSize(long batchSize, long maxChunkSize); /** * Asynchronously compress a batch of buffers. Note that compressedSizesOutPtr must * point to pinned memory for this operation to be asynchronous. * @param devInPtrs device address of uncompressed buffer addresses vector * @param devInSizes device address of uncompressed buffer sizes vector * @param chunkSize maximum size of an uncompressed chunk in bytes * @param batchSize number of chunks in the batch * @param tempPtr device address of the temporary workspace buffer * @param tempSize size of the temporary workspace buffer in bytes * @param devOutPtrs device address of output buffer addresses vector * @param compressedSizesOutPtr device address where to write the sizes of the * compressed data written to the corresponding * output buffers. Must point to a buffer with * at least 8 bytes of memory per output buffer * in the batch. * @param stream CUDA stream to use */ protected abstract void batchedCompressAsync(long devInPtrs, long devInSizes, long chunkSize, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long compressedSizesOutPtr, long stream); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/BatchedDecompressor.java
/* * Copyright (c) 2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; import ai.rapids.cudf.CloseableArray; import ai.rapids.cudf.Cuda; import ai.rapids.cudf.BaseDeviceMemoryBuffer; import ai.rapids.cudf.DeviceMemoryBuffer; import ai.rapids.cudf.HostMemoryBuffer; import ai.rapids.cudf.NvtxColor; import ai.rapids.cudf.NvtxRange; import java.util.Arrays; /** Decompressor that operates on multiple input buffers in a batch */ public abstract class BatchedDecompressor { private final long chunkSize; /** * Construct a batched decompressor instance * @param chunkSize maximum uncompressed block size, must match value used * during compression */ public BatchedDecompressor(long chunkSize) { this.chunkSize = chunkSize; } /** * Asynchronously decompress a batch of buffers * @param origInputs buffers to decompress, will be closed by this operation * @param outputs output buffers that will contain the decompressed results, each must * be sized to the exact decompressed size of the corresponding input * @param stream CUDA stream to use */ public void decompressAsync(BaseDeviceMemoryBuffer[] origInputs, BaseDeviceMemoryBuffer[] outputs, Cuda.Stream stream) { try (CloseableArray<BaseDeviceMemoryBuffer> inputs = CloseableArray.wrap(Arrays.copyOf(origInputs, origInputs.length))) { BatchedCompressor.validateChunkSize(chunkSize); if (origInputs.length != outputs.length) { throw new IllegalArgumentException("number of inputs must match number of outputs"); } final int numInputs = inputs.size(); if (numInputs == 0) { return; } int[] chunksPerInput = new int[numInputs]; long totalChunks = 0; for (int i = 0; i < numInputs; i++) { // use output size to determine number of chunks in the input, as the output buffer // must be exactly sized to the uncompressed data BaseDeviceMemoryBuffer buffer = outputs[i]; int numBufferChunks = getNumChunksInBuffer(chunkSize, buffer); chunksPerInput[i] = numBufferChunks; totalChunks += numBufferChunks; } final long tempBufferSize = batchedDecompressGetTempSize(totalChunks, chunkSize); try (DeviceMemoryBuffer devAddrsSizes = buildAddrsSizesBuffer(chunkSize, totalChunks, inputs.getArray(), chunksPerInput, outputs, stream); DeviceMemoryBuffer devTemp = DeviceMemoryBuffer.allocate(tempBufferSize)) { // buffer containing addresses and sizes contains four vectors of longs in this order: // - compressed chunk input addresses // - chunk output buffer addresses // - compressed chunk sizes // - uncompressed chunk sizes final long inputAddrsPtr = devAddrsSizes.getAddress(); final long outputAddrsPtr = inputAddrsPtr + totalChunks * 8; final long inputSizesPtr = outputAddrsPtr + totalChunks * 8; final long outputSizesPtr = inputSizesPtr + totalChunks * 8; batchedDecompressAsync(inputAddrsPtr, inputSizesPtr, outputSizesPtr, totalChunks, devTemp.getAddress(), devTemp.getLength(), outputAddrsPtr, stream.getStream()); } } } private static int getNumChunksInBuffer(long chunkSize, BaseDeviceMemoryBuffer buffer) { return (int) ((buffer.getLength() + chunkSize - 1) / chunkSize); } /** * Build a device memory buffer containing four vectors of longs in the following order: * <ul> * <li>compressed chunk input addresses</li> * <li>uncompressed chunk output addresses</li> * <li>compressed chunk sizes</li> * <li>uncompressed chunk sizes</li> * </ul> * Each vector contains as many longs as the number of chunks being decompressed * @param chunkSize maximum uncompressed size of a chunk * @param totalChunks total number of chunks to be decompressed * @param inputs device buffers containing the compressed data * @param chunksPerInput number of compressed chunks per input buffer * @param outputs device buffers that will hold the uncompressed output * @param stream CUDA stream to use * @return device buffer containing address and size vectors */ private static DeviceMemoryBuffer buildAddrsSizesBuffer(long chunkSize, long totalChunks, BaseDeviceMemoryBuffer[] inputs, int[] chunksPerInput, BaseDeviceMemoryBuffer[] outputs, Cuda.Stream stream) { final long totalBufferSize = totalChunks * 8L * 4L; try (NvtxRange range = new NvtxRange("buildAddrSizesBuffer", NvtxColor.YELLOW)) { try (HostMemoryBuffer metadata = fetchMetadata(totalChunks, inputs, chunksPerInput, stream); HostMemoryBuffer hostAddrsSizes = HostMemoryBuffer.allocate(totalBufferSize); DeviceMemoryBuffer devAddrsSizes = DeviceMemoryBuffer.allocate(totalBufferSize)) { // Build four long vectors in the AddrsSizes buffer: // - compressed input address (one per chunk) // - uncompressed output address (one per chunk) // - compressed input size (one per chunk) // - uncompressed input size (one per chunk) final long srcAddrsOffset = 0; final long destAddrsOffset = srcAddrsOffset + totalChunks * 8L; final long srcSizesOffset = destAddrsOffset + totalChunks * 8L; final long destSizesOffset = srcSizesOffset + totalChunks * 8L; long chunkIdx = 0; for (int inputIdx = 0; inputIdx < inputs.length; inputIdx++) { final BaseDeviceMemoryBuffer input = inputs[inputIdx]; final BaseDeviceMemoryBuffer output = outputs[inputIdx]; final int numChunksInInput = chunksPerInput[inputIdx]; long srcAddr = input.getAddress() + BatchedCompressor.METADATA_BYTES_PER_CHUNK * numChunksInInput; long destAddr = output.getAddress(); final long chunkIdxEnd = chunkIdx + numChunksInInput; while (chunkIdx < chunkIdxEnd) { final long srcChunkSize = metadata.getLong(chunkIdx * 8); final long destChunkSize = (chunkIdx < chunkIdxEnd - 1) ? chunkSize : output.getAddress() + output.getLength() - destAddr; hostAddrsSizes.setLong(srcAddrsOffset + chunkIdx * 8, srcAddr); hostAddrsSizes.setLong(destAddrsOffset + chunkIdx * 8, destAddr); hostAddrsSizes.setLong(srcSizesOffset + chunkIdx * 8, srcChunkSize); hostAddrsSizes.setLong(destSizesOffset + chunkIdx * 8, destChunkSize); srcAddr += srcChunkSize; destAddr += destChunkSize; ++chunkIdx; } } devAddrsSizes.copyFromHostBuffer(hostAddrsSizes, stream); devAddrsSizes.incRefCount(); return devAddrsSizes; } } } /** * Fetch the metadata at the front of each input in a single, contiguous host buffer. * @param totalChunks total number of compressed chunks * @param inputs buffers containing the compressed data * @param chunksPerInput number of compressed chunks for the corresponding input * @param stream CUDA stream to use * @return host buffer containing all of the metadata */ private static HostMemoryBuffer fetchMetadata(long totalChunks, BaseDeviceMemoryBuffer[] inputs, int[] chunksPerInput, Cuda.Stream stream) { try (NvtxRange range = new NvtxRange("fetchMetadata", NvtxColor.PURPLE)) { // one long per chunk containing the compressed size final long totalMetadataSize = totalChunks * BatchedCompressor.METADATA_BYTES_PER_CHUNK; // Build corresponding vectors of destination addresses, source addresses and sizes. long[] destAddrs = new long[inputs.length]; long[] srcAddrs = new long[inputs.length]; long[] sizes = new long[inputs.length]; try (HostMemoryBuffer hostMetadata = HostMemoryBuffer.allocate(totalMetadataSize); DeviceMemoryBuffer devMetadata = DeviceMemoryBuffer.allocate(totalMetadataSize)) { long destCopyAddr = devMetadata.getAddress(); for (int inputIdx = 0; inputIdx < inputs.length; inputIdx++) { final BaseDeviceMemoryBuffer input = inputs[inputIdx]; final long copySize = chunksPerInput[inputIdx] * BatchedCompressor.METADATA_BYTES_PER_CHUNK; destAddrs[inputIdx] = destCopyAddr; srcAddrs[inputIdx] = input.getAddress(); sizes[inputIdx] = copySize; destCopyAddr += copySize; } Cuda.multiBufferCopyAsync(destAddrs, srcAddrs, sizes, stream); hostMetadata.copyFromDeviceBuffer(devMetadata, stream); hostMetadata.incRefCount(); return hostMetadata; } } } /** * Computes the temporary storage size in bytes needed to decompress a compressed batch. * @param numChunks number of chunks in the batch * @param maxUncompressedChunkBytes maximum uncompressed size of any chunk in bytes * @return number of temporary storage bytes needed to decompress the batch */ protected abstract long batchedDecompressGetTempSize(long numChunks, long maxUncompressedChunkBytes); /** * Asynchronously decompress a batch of compressed data buffers. * @param devInPtrs device address of compressed input buffer addresses vector * @param devInSizes device address of compressed input buffer sizes vector * @param devOutSizes device address of uncompressed buffer sizes vector * @param batchSize number of buffers in the batch * @param tempPtr device address of the temporary decompression space * @param tempSize size of the temporary decompression space in bytes * @param devOutPtrs device address of uncompressed output buffer addresses vector * @param stream CUDA stream to use */ protected abstract void batchedDecompressAsync(long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long stream); }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/BatchedLZ4Compressor.java
/* * Copyright (c) 2020-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; /** Multi-buffer LZ4 compressor */ public class BatchedLZ4Compressor extends BatchedCompressor { /** * Construct a batched LZ4 compressor instance * @param chunkSize maximum amount of uncompressed data to compress as a single chunk. * Inputs larger than this will be compressed in multiple chunks. * @param maxIntermediateBufferSize desired maximum size of intermediate device buffers * used during compression. */ public BatchedLZ4Compressor(long chunkSize, long maxIntermediateBufferSize) { super(chunkSize, NvcompJni.batchedLZ4CompressGetMaxOutputChunkSize(chunkSize), maxIntermediateBufferSize); } @Override protected long batchedCompressGetTempSize(long batchSize, long maxChunkSize) { return NvcompJni.batchedLZ4CompressGetTempSize(batchSize, maxChunkSize); } @Override protected void batchedCompressAsync(long devInPtrs, long devInSizes, long chunkSize, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long compressedSizesOutPtr, long stream) { NvcompJni.batchedLZ4CompressAsync(devInPtrs, devInSizes, chunkSize, batchSize, tempPtr, tempSize, devOutPtrs, compressedSizesOutPtr, stream); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/BatchedLZ4Decompressor.java
/* * Copyright (c) 2020-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; import ai.rapids.cudf.Cuda; import ai.rapids.cudf.BaseDeviceMemoryBuffer; /** LZ4 decompressor that operates on multiple input buffers in a batch */ public class BatchedLZ4Decompressor extends BatchedDecompressor { public BatchedLZ4Decompressor(long chunkSize) { super(chunkSize); } /** * Asynchronously decompress a batch of buffers * @param chunkSize maximum uncompressed block size, must match value used during compression * @param origInputs buffers to decompress, will be closed by this operation * @param outputs output buffers that will contain the compressed results, each must be sized * to the exact decompressed size of the corresponding input * @param stream CUDA stream to use * * Deprecated: Use the non-static version in the parent class instead. */ public static void decompressAsync(long chunkSize, BaseDeviceMemoryBuffer[] origInputs, BaseDeviceMemoryBuffer[] outputs, Cuda.Stream stream) { new BatchedLZ4Decompressor(chunkSize).decompressAsync(origInputs, outputs, stream); } @Override protected long batchedDecompressGetTempSize(long numChunks, long maxUncompressedChunkBytes) { return NvcompJni.batchedLZ4DecompressGetTempSize(numChunks, maxUncompressedChunkBytes); } @Override protected void batchedDecompressAsync(long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long stream) { NvcompJni.batchedLZ4DecompressAsync(devInPtrs, devInSizes, devOutSizes, batchSize, tempPtr, tempSize, devOutPtrs, stream); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/BatchedZstdCompressor.java
/* * Copyright (c) 2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; /** Multi-buffer ZSTD compressor */ public class BatchedZstdCompressor extends BatchedCompressor { /** * Construct a batched ZSTD compressor instance * @param chunkSize maximum amount of uncompressed data to compress as a single chunk. * Inputs larger than this will be compressed in multiple chunks. * @param maxIntermediateBufferSize desired maximum size of intermediate device buffers * used during compression. */ public BatchedZstdCompressor(long chunkSize, long maxIntermediateBufferSize) { super(chunkSize, NvcompJni.batchedZstdCompressGetMaxOutputChunkSize(chunkSize), maxIntermediateBufferSize); } @Override protected long batchedCompressGetTempSize(long batchSize, long maxChunkSize) { return NvcompJni.batchedZstdCompressGetTempSize(batchSize, maxChunkSize); } @Override protected void batchedCompressAsync(long devInPtrs, long devInSizes, long chunkSize, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long compressedSizesOutPtr, long stream) { NvcompJni.batchedZstdCompressAsync(devInPtrs, devInSizes, chunkSize, batchSize, tempPtr, tempSize, devOutPtrs, compressedSizesOutPtr, stream); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/BatchedZstdDecompressor.java
/* * Copyright (c) 2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; /** ZSTD decompressor that operates on multiple input buffers in a batch */ public class BatchedZstdDecompressor extends BatchedDecompressor { public BatchedZstdDecompressor(long chunkSize) { super(chunkSize); } @Override protected long batchedDecompressGetTempSize(long numChunks, long maxUncompressedChunkBytes) { return NvcompJni.batchedZstdDecompressGetTempSize(numChunks, maxUncompressedChunkBytes); } @Override protected void batchedDecompressAsync(long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long stream) { NvcompJni.batchedZstdDecompressAsync(devInPtrs, devInSizes, devOutSizes, batchSize, tempPtr, tempSize, devOutPtrs, stream); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/CompressionType.java
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; /** Enumeration of data types that can be compressed. */ public enum CompressionType { CHAR(0), UCHAR(1), SHORT(2), USHORT(3), INT(4), UINT(5), LONGLONG(6), ULONGLONG(7), BITS(0xff); private static final CompressionType[] types = CompressionType.values(); final int nativeId; CompressionType(int nativeId) { this.nativeId = nativeId; } /** Lookup the CompressionType that corresponds to the specified native identifier */ public static CompressionType fromNativeId(int id) { for (CompressionType type : types) { if (type.nativeId == id) { return type; } } throw new IllegalArgumentException("Unknown compression type ID: " + id); } /** Get the native code identifier for the type */ public final int toNativeId() { return nativeId; } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/NvcompCudaException.java
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; /** Exception thrown from nvcomp indicating a CUDA error occurred. */ public class NvcompCudaException extends NvcompException { NvcompCudaException(String message) { super(message); } NvcompCudaException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/NvcompException.java
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; /** Base class for all nvcomp-specific exceptions */ public class NvcompException extends RuntimeException { NvcompException(String message) { super(message); } NvcompException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf
java-sources/ai/rapids/cudf/25.08.0/ai/rapids/cudf/nvcomp/NvcompJni.java
/* * Copyright (c) 2020-2024, NVIDIA CORPORATION. * * Licensed 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 ai.rapids.cudf.nvcomp; import ai.rapids.cudf.NativeDepsLoader; /** Raw JNI interface to the nvcomp library. */ class NvcompJni { static { NativeDepsLoader.loadNativeDeps(); } // For lz4 /** * Get the temporary workspace size required to perform compression of entire LZ4 batch. * @param batchSize number of chunks in the batch * @param maxChunkSize maximum size of an uncompressed chunk in bytes * @return The size of required temporary workspace in bytes to compress the batch. */ static native long batchedLZ4CompressGetTempSize(long batchSize, long maxChunkSize); /** * Get the maximum size any chunk could compress to in a LZ4 batch. This is the minimum amount of * output memory to allocate per chunk when batch compressing. * @param maxChunkSize maximum size of an uncompressed chunk size in bytes * @return maximum compressed output size of a chunk */ static native long batchedLZ4CompressGetMaxOutputChunkSize(long maxChunkSize); /** * Asynchronously compress a batch of buffers with LZ4. Note that * compressedSizesOutPtr must point to pinned memory for this operation * to be asynchronous. * @param devInPtrs device address of uncompressed buffer addresses vector * @param devInSizes device address of uncompressed buffer sizes vector * @param chunkSize maximum size of an uncompressed chunk in bytes * @param batchSize number of chunks in the batch * @param tempPtr device address of the temporary workspace buffer * @param tempSize size of the temporary workspace buffer in bytes * @param devOutPtrs device address of output buffer addresses vector * @param compressedSizesOutPtr device address where to write the sizes of the * compressed data written to the corresponding * output buffers. Must point to a buffer with * at least 8 bytes of memory per output buffer * in the batch. * @param stream CUDA stream to use */ static native void batchedLZ4CompressAsync( long devInPtrs, long devInSizes, long chunkSize, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long compressedSizesOutPtr, long stream); /** * Computes the temporary storage size in bytes needed to decompress a LZ4-compressed batch. * @param numChunks number of chunks in the batch * @param maxUncompressedChunkBytes maximum uncompressed size of any chunk in bytes * @return number of temporary storage bytes needed to decompress the batch */ static native long batchedLZ4DecompressGetTempSize( long numChunks, long maxUncompressedChunkBytes); /** * Asynchronously decompress a batch of LZ4-compressed data buffers. * @param devInPtrs device address of compressed input buffer addresses vector * @param devInSizes device address of compressed input buffer sizes vector * @param devOutSizes device address of uncompressed buffer sizes vector * @param batchSize number of buffers in the batch * @param tempPtr device address of the temporary decompression space * @param tempSize size of the temporary decompression space in bytes * @param devOutPtrs device address of uncompressed output buffer addresses vector * @param stream CUDA stream to use */ static native void batchedLZ4DecompressAsync( long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long stream); /** * Asynchronously calculates the decompressed size needed for each chunk. * @param devInPtrs device address of compressed input buffer addresses vector * @param devInSizes device address of compressed input buffer sizes vector * @param devOutSizes device address of calculated decompress sizes vector * @param batchSize number of buffers in the batch * @param stream CUDA stream to use */ static native void batchedLZ4GetDecompressSizeAsync( long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long stream); // For zstd /** * Get the temporary workspace size required to perform compression of entire zstd batch. * @param batchSize number of chunks in the batch * @param maxChunkSize maximum size of an uncompressed chunk in bytes * @return The size of required temporary workspace in bytes to compress the batch. */ static native long batchedZstdCompressGetTempSize(long batchSize, long maxChunkSize); /** * Get the maximum size any chunk could compress to in a ZSTD batch. This is the minimum * amount of output memory to allocate per chunk when batch compressing. * @param maxChunkSize maximum size of an uncompressed chunk size in bytes * @return maximum compressed output size of a chunk */ static native long batchedZstdCompressGetMaxOutputChunkSize(long maxChunkSize); /** * Asynchronously compress a batch of buffers with ZSTD. Note that * compressedSizesOutPtr must point to pinned memory for this operation * to be asynchronous. * @param devInPtrs device address of uncompressed buffer addresses vector * @param devInSizes device address of uncompressed buffer sizes vector * @param chunkSize maximum size of an uncompressed chunk in bytes * @param batchSize number of chunks in the batch * @param tempPtr device address of the temporary workspace buffer * @param tempSize size of the temporary workspace buffer in bytes * @param devOutPtrs device address of output buffer addresses vector * @param compressedSizesOutPtr device address where to write the sizes of the * compressed data written to the corresponding * output buffers. Must point to a buffer with * at least 8 bytes of memory per output buffer * in the batch. * @param stream CUDA stream to use */ static native void batchedZstdCompressAsync( long devInPtrs, long devInSizes, long chunkSize, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long compressedSizesOutPtr, long stream); /** * Computes the temporary storage size in bytes needed to decompress a * ZSTD-compressed batch. * @param numChunks number of chunks in the batch * @param maxUncompressedChunkBytes maximum uncompressed size of any chunk in bytes * @return number of temporary storage bytes needed to decompress the batch */ static native long batchedZstdDecompressGetTempSize( long numChunks, long maxUncompressedChunkBytes); /** * Asynchronously decompress a batch of ZSTD-compressed data buffers. * @param devInPtrs device address of compressed input buffer addresses vector * @param devInSizes device address of compressed input buffer sizes vector * @param devOutSizes device address of uncompressed buffer sizes vector * @param batchSize number of buffers in the batch * @param tempPtr device address of the temporary decompression space * @param tempSize size of the temporary decompression space in bytes * @param devOutPtrs device address of uncompressed output buffer addresses vector * @param stream CUDA stream to use */ static native void batchedZstdDecompressAsync( long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long tempPtr, long tempSize, long devOutPtrs, long stream); /** * Asynchronously calculates the decompressed size needed for each chunk. * @param devInPtrs device address of compressed input buffer addresses vector * @param devInSizes device address of compressed input buffer sizes vector * @param devOutSizes device address of calculated decompress sizes vector * @param batchSize number of buffers in the batch * @param stream CUDA stream to use */ static native void batchedZstdGetDecompressSizeAsync( long devInPtrs, long devInSizes, long devOutSizes, long batchSize, long stream); }
0
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j/java/Booster.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.*; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Booster for xgboost, this is a model API that support interactive build of a XGBoost Model */ public class Booster implements Serializable, KryoSerializable { private static final Log logger = LogFactory.getLog(Booster.class); // handle to the booster. private long handle = 0; private int version = 0; /** * Create a new Booster with empty stage. * * @param params Model parameters * @param cacheMats Cached DMatrix entries, * the prediction of these DMatrices will become faster than not-cached data. * @throws XGBoostError native error */ Booster(Map<String, Object> params, DMatrix[] cacheMats) throws XGBoostError { init(cacheMats); setParam("seed", "0"); setParams(params); } /** * Load a new Booster model from modelPath * @param modelPath The path to the model. * @return The created Booster. * @throws XGBoostError */ static Booster loadModel(String modelPath) throws XGBoostError { if (modelPath == null) { throw new NullPointerException("modelPath : null"); } Booster ret = new Booster(new HashMap<String, Object>(), new DMatrix[0]); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModel(ret.handle, modelPath)); return ret; } /** * Load a new Booster model from a file opened as input stream. * The assumption is the input stream only contains one XGBoost Model. * This can be used to load existing booster models saved by other xgboost bindings. * * @param in The input stream of the file. * @return The create boosted * @throws XGBoostError * @throws IOException */ static Booster loadModel(InputStream in) throws XGBoostError, IOException { int size; byte[] buf = new byte[1<<20]; ByteArrayOutputStream os = new ByteArrayOutputStream(); while ((size = in.read(buf)) != -1) { os.write(buf, 0, size); } in.close(); Booster ret = new Booster(new HashMap<String, Object>(), new DMatrix[0]); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModelFromBuffer(ret.handle,os.toByteArray())); return ret; } /** * Set parameter to the Booster. * * @param key param name * @param value param value * @throws XGBoostError native error */ public final void setParam(String key, Object value) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSetParam(handle, key, value.toString())); } /** * Set parameters to the Booster. * * @param params parameters key-value map * @throws XGBoostError native error */ public void setParams(Map<String, Object> params) throws XGBoostError { if (params != null) { for (Map.Entry<String, Object> entry : params.entrySet()) { setParam(entry.getKey(), entry.getValue().toString()); } } } /** * Get attributes stored in the Booster as a Map. * * @return A map contain attribute pairs. * @throws XGBoostError native error */ public final Map<String, String> getAttrs() throws XGBoostError { String[][] attrNames = new String[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterGetAttrNames(handle, attrNames)); Map<String, String> attrMap = new HashMap<>(); for (String name: attrNames[0]) { attrMap.put(name, this.getAttr(name)); } return attrMap; } /** * Get attribute from the Booster. * * @param key attribute key * @return attribute value * @throws XGBoostError native error */ public final String getAttr(String key) throws XGBoostError { String[] attrValue = new String[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterGetAttr(handle, key, attrValue)); return attrValue[0]; } /** * Set attribute to the Booster. * * @param key attribute key * @param value attribute value * @throws XGBoostError native error */ public final void setAttr(String key, String value) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSetAttr(handle, key, value)); } /** * Set attributes to the Booster. * * @param attrs attributes key-value map * @throws XGBoostError native error */ public void setAttrs(Map<String, String> attrs) throws XGBoostError { if (attrs != null) { for (Map.Entry<String, String> entry : attrs.entrySet()) { setAttr(entry.getKey(), entry.getValue()); } } } /** * Update the booster for one iteration. * * @param dtrain training data * @param iter current iteration number * @throws XGBoostError native error */ public void update(DMatrix dtrain, int iter) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterUpdateOneIter(handle, iter, dtrain.getHandle())); } /** * Update with customize obj func * * @param dtrain training data * @param obj customized objective class * @throws XGBoostError native error */ public void update(DMatrix dtrain, IObjective obj) throws XGBoostError { float[][] predicts = this.predict(dtrain, true, 0, false, false); List<float[]> gradients = obj.getGradient(predicts, dtrain); boost(dtrain, gradients.get(0), gradients.get(1)); } /** * update with give grad and hess * * @param dtrain training data * @param grad first order of gradient * @param hess seconde order of gradient * @throws XGBoostError native error */ public void boost(DMatrix dtrain, float[] grad, float[] hess) throws XGBoostError { if (grad.length != hess.length) { throw new AssertionError(String.format("grad/hess length mismatch %s / %s", grad.length, hess.length)); } XGBoostJNI.checkCall(XGBoostJNI.XGBoosterBoostOneIter(handle, dtrain.getHandle(), grad, hess)); } /** * evaluate with given dmatrixs. * * @param evalMatrixs dmatrixs for evaluation * @param evalNames name for eval dmatrixs, used for check results * @param iter current eval iteration * @return eval information * @throws XGBoostError native error */ public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, int iter) throws XGBoostError { long[] handles = dmatrixsToHandles(evalMatrixs); String[] evalInfo = new String[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterEvalOneIter(handle, iter, handles, evalNames, evalInfo)); return evalInfo[0]; } /** * evaluate with given dmatrixs. * * @param evalMatrixs dmatrixs for evaluation * @param evalNames name for eval dmatrixs, used for check results * @param iter current eval iteration * @param metricsOut output array containing the evaluation metrics for each evalMatrix * @return eval information * @throws XGBoostError native error */ public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, int iter, float[] metricsOut) throws XGBoostError { String stringFormat = evalSet(evalMatrixs, evalNames, iter); String[] metricPairs = stringFormat.split("\t"); for (int i = 1; i < metricPairs.length; i++) { metricsOut[i - 1] = Float.valueOf(metricPairs[i].split(":")[1]); } return stringFormat; } /** * evaluate with given customized Evaluation class * * @param evalMatrixs evaluation matrix * @param evalNames evaluation names * @param eval custom evaluator * @return eval information * @throws XGBoostError native error */ public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, IEvaluation eval) throws XGBoostError { // Hopefully, a tiny redundant allocation wouldn't hurt. return evalSet(evalMatrixs, evalNames, eval, new float[evalNames.length]); } public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, IEvaluation eval, float[] metricsOut) throws XGBoostError { String evalInfo = ""; for (int i = 0; i < evalNames.length; i++) { String evalName = evalNames[i]; DMatrix evalMat = evalMatrixs[i]; float evalResult = eval.eval(predict(evalMat), evalMat); String evalMetric = eval.getMetric(); evalInfo += String.format("\t%s-%s:%f", evalName, evalMetric, evalResult); metricsOut[i] = evalResult; } return evalInfo; } /** * Advanced predict function with all the options. * * @param data data * @param outputMargin output margin * @param treeLimit limit number of trees, 0 means all trees. * @param predLeaf prediction minimum to keep leafs * @param predContribs prediction feature contributions * @return predict results */ private synchronized float[][] predict(DMatrix data, boolean outputMargin, int treeLimit, boolean predLeaf, boolean predContribs) throws XGBoostError { int optionMask = 0; if (outputMargin) { optionMask = 1; } if (predLeaf) { optionMask = 2; } if (predContribs) { optionMask = 4; } float[][] rawPredicts = new float[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterPredict(handle, data.getHandle(), optionMask, treeLimit, rawPredicts)); int row = (int) data.rowNum(); int col = rawPredicts[0].length / row; float[][] predicts = new float[row][col]; int r, c; for (int i = 0; i < rawPredicts[0].length; i++) { r = i / col; c = i % col; predicts[r][c] = rawPredicts[0][i]; } return predicts; } /** * Predict leaf indices given the data * * @param data The input data. * @param treeLimit Number of trees to include, 0 means all trees. * @return The leaf indices of the instance. * @throws XGBoostError */ public float[][] predictLeaf(DMatrix data, int treeLimit) throws XGBoostError { return this.predict(data, false, treeLimit, true, false); } /** * Output feature contributions toward predictions of given data * * @param data The input data. * @param treeLimit Number of trees to include, 0 means all trees. * @return The feature contributions and bias. * @throws XGBoostError */ public float[][] predictContrib(DMatrix data, int treeLimit) throws XGBoostError { return this.predict(data, false, treeLimit, true, true); } /** * Predict with data * * @param data dmatrix storing the input * @return predict result * @throws XGBoostError native error */ public float[][] predict(DMatrix data) throws XGBoostError { return this.predict(data, false, 0, false, false); } /** * Predict with data * * @param data data * @param outputMargin output margin * @return predict results */ public float[][] predict(DMatrix data, boolean outputMargin) throws XGBoostError { return this.predict(data, outputMargin, 0, false, false); } /** * Advanced predict function with all the options. * * @param data data * @param outputMargin output margin * @param treeLimit limit number of trees, 0 means all trees. * @return predict results */ public float[][] predict(DMatrix data, boolean outputMargin, int treeLimit) throws XGBoostError { return this.predict(data, outputMargin, treeLimit, false, false); } /** * Save model to modelPath * * @param modelPath model path */ public void saveModel(String modelPath) throws XGBoostError{ XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSaveModel(handle, modelPath)); } /** * Save the model to file opened as output stream. * The model format is compatible with other xgboost bindings. * The output stream can only save one xgboost model. * This function will close the OutputStream after the save. * * @param out The output stream */ public void saveModel(OutputStream out) throws XGBoostError, IOException { out.write(this.toByteArray()); out.close(); } /** * Get the dump of the model as a string array * * @param withStats Controls whether the split statistics are output. * @return dumped model information * @throws XGBoostError native error */ public String[] getModelDump(String featureMap, boolean withStats) throws XGBoostError { return getModelDump(featureMap, withStats, "text"); } public String[] getModelDump(String featureMap, boolean withStats, String format) throws XGBoostError { int statsFlag = 0; if (featureMap == null) { featureMap = ""; } if (withStats) { statsFlag = 1; } if (format == null) { format = "text"; } String[][] modelInfos = new String[1][]; XGBoostJNI.checkCall( XGBoostJNI.XGBoosterDumpModelEx(handle, featureMap, statsFlag, format, modelInfos)); return modelInfos[0]; } /** * Get the dump of the model as a string array with specified feature names. * * @param featureNames Names of the features. * @return dumped model information * @throws XGBoostError */ public String[] getModelDump(String[] featureNames, boolean withStats) throws XGBoostError { return getModelDump(featureNames, withStats, "text"); } public String[] getModelDump(String[] featureNames, boolean withStats, String format) throws XGBoostError { int statsFlag = 0; if (withStats) { statsFlag = 1; } if (format == null) { format = "text"; } String[][] modelInfos = new String[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterDumpModelExWithFeatures( handle, featureNames, statsFlag, format, modelInfos)); return modelInfos[0]; } /** * Supported feature importance types * * WEIGHT = Number of nodes that a feature was used to determine a split * GAIN = Average information gain per split for a feature * COVER = Average cover per split for a feature * TOTAL_GAIN = Total information gain over all splits of a feature * TOTAL_COVER = Total cover over all splits of a feature */ public static class FeatureImportanceType { public static final String WEIGHT = "weight"; public static final String GAIN = "gain"; public static final String COVER = "cover"; public static final String TOTAL_GAIN = "total_gain"; public static final String TOTAL_COVER = "total_cover"; public static final Set<String> ACCEPTED_TYPES = new HashSet<>( Arrays.asList(WEIGHT, GAIN, COVER, TOTAL_GAIN, TOTAL_COVER)); } /** * Get importance of each feature with specified feature names. * * @return featureScoreMap key: feature name, value: feature importance score, can be nill. * @throws XGBoostError native error */ public Map<String, Integer> getFeatureScore(String[] featureNames) throws XGBoostError { String[] modelInfos = getModelDump(featureNames, false); return getFeatureWeightsFromModel(modelInfos); } /** * Get importance of each feature * * @return featureScoreMap key: feature index, value: feature importance score, can be nill * @throws XGBoostError native error */ public Map<String, Integer> getFeatureScore(String featureMap) throws XGBoostError { String[] modelInfos = getModelDump(featureMap, false); return getFeatureWeightsFromModel(modelInfos); } /** * Get the importance of each feature based purely on weights (number of splits) * * @return featureScoreMap key: feature index, * value: feature importance score based on weight * @throws XGBoostError native error */ private Map<String, Integer> getFeatureWeightsFromModel(String[] modelInfos) throws XGBoostError { Map<String, Integer> featureScore = new HashMap<>(); for (String tree : modelInfos) { for (String node : tree.split("\n")) { String[] array = node.split("\\["); if (array.length == 1) { continue; } String fid = array[1].split("\\]")[0]; fid = fid.split("<")[0]; if (featureScore.containsKey(fid)) { featureScore.put(fid, 1 + featureScore.get(fid)); } else { featureScore.put(fid, 1); } } } return featureScore; } /** * Get the feature importances for gain or cover (average or total) * * @return featureImportanceMap key: feature index, * values: feature importance score based on gain or cover * @throws XGBoostError native error */ public Map<String, Double> getScore( String[] featureNames, String importanceType) throws XGBoostError { String[] modelInfos = getModelDump(featureNames, true); return getFeatureImportanceFromModel(modelInfos, importanceType); } /** * Get the feature importances for gain or cover (average or total), with feature names * * @return featureImportanceMap key: feature name, * values: feature importance score based on gain or cover * @throws XGBoostError native error */ public Map<String, Double> getScore( String featureMap, String importanceType) throws XGBoostError { String[] modelInfos = getModelDump(featureMap, true); return getFeatureImportanceFromModel(modelInfos, importanceType); } /** * Get the importance of each feature based on information gain or cover * * @return featureImportanceMap key: feature index, value: feature importance score * based on information gain or cover * @throws XGBoostError native error */ private Map<String, Double> getFeatureImportanceFromModel( String[] modelInfos, String importanceType) throws XGBoostError { if (!FeatureImportanceType.ACCEPTED_TYPES.contains(importanceType)) { throw new AssertionError(String.format("Importance type %s is not supported", importanceType)); } Map<String, Double> importanceMap = new HashMap<>(); Map<String, Double> weightMap = new HashMap<>(); if (importanceType == FeatureImportanceType.WEIGHT) { Map<String, Integer> importanceWeights = getFeatureWeightsFromModel(modelInfos); for (String feature: importanceWeights.keySet()) { importanceMap.put(feature, new Double(importanceWeights.get(feature))); } return importanceMap; } /* Each split in the tree has this text form: "0:[f28<-9.53674316e-07] yes=1,no=2,missing=1,gain=4000.53101,cover=1628.25" So the line has to be split according to whether cover or gain is desired */ String splitter = "gain="; if (importanceType == FeatureImportanceType.COVER || importanceType == FeatureImportanceType.TOTAL_COVER) { splitter = "cover="; } for (String tree: modelInfos) { for (String node: tree.split("\n")) { String[] array = node.split("\\["); if (array.length == 1) { continue; } String[] fidWithImportance = array[1].split("\\]"); // Extract gain or cover from string after closing bracket Double importance = Double.parseDouble( fidWithImportance[1].split(splitter)[1].split(",")[0] ); String fid = fidWithImportance[0].split("<")[0]; if (importanceMap.containsKey(fid)) { importanceMap.put(fid, importance + importanceMap.get(fid)); weightMap.put(fid, 1d + weightMap.get(fid)); } else { importanceMap.put(fid, importance); weightMap.put(fid, 1d); } } } /* By default we calculate total gain and total cover. Divide by the number of nodes per feature to get gain / cover */ if (importanceType == FeatureImportanceType.COVER || importanceType == FeatureImportanceType.GAIN) { for (String fid: importanceMap.keySet()) { importanceMap.put(fid, importanceMap.get(fid)/weightMap.get(fid)); } } return importanceMap; } /** * Save the model as byte array representation. * Write these bytes to a file will give compatible format with other xgboost bindings. * * If java natively support HDFS file API, use toByteArray and write the ByteArray * * @param withStats Controls whether the split statistics are output. * @return dumped model information * @throws XGBoostError native error */ private String[] getDumpInfo(boolean withStats) throws XGBoostError { int statsFlag = 0; if (withStats) { statsFlag = 1; } String[][] modelInfos = new String[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterDumpModelEx(handle, "", statsFlag, "text", modelInfos)); return modelInfos[0]; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } /** * * @return the saved byte array. * @throws XGBoostError native error */ public byte[] toByteArray() throws XGBoostError { byte[][] bytes = new byte[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterGetModelRaw(this.handle, bytes)); return bytes[0]; } /** * Load the booster model from thread-local rabit checkpoint. * This is only used in distributed training. * @return the stored version number of the checkpoint. * @throws XGBoostError */ int loadRabitCheckpoint() throws XGBoostError { int[] out = new int[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadRabitCheckpoint(this.handle, out)); version = out[0]; return version; } /** * Save the booster model into thread-local rabit checkpoint and increment the version. * This is only used in distributed training. * @throws XGBoostError */ void saveRabitCheckpoint() throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSaveRabitCheckpoint(this.handle)); version += 1; } /** * Internal initialization function. * @param cacheMats The cached DMatrix. * @throws XGBoostError */ private void init(DMatrix[] cacheMats) throws XGBoostError { long[] handles = null; if (cacheMats != null) { handles = dmatrixsToHandles(cacheMats); } long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterCreate(handles, out)); handle = out[0]; } /** * transfer DMatrix array to handle array (used for native functions) * * @param dmatrixs * @return handle array for input dmatrixs */ private static long[] dmatrixsToHandles(DMatrix[] dmatrixs) { long[] handles = new long[dmatrixs.length]; for (int i = 0; i < dmatrixs.length; i++) { handles[i] = dmatrixs[i].getHandle(); } return handles; } // making Booster serializable private void writeObject(java.io.ObjectOutputStream out) throws IOException { try { out.writeInt(version); out.writeObject(this.toByteArray()); } catch (XGBoostError ex) { ex.printStackTrace(); logger.error(ex.getMessage()); } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { try { this.init(null); this.version = in.readInt(); byte[] bytes = (byte[])in.readObject(); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModelFromBuffer(this.handle, bytes)); } catch (XGBoostError ex) { ex.printStackTrace(); logger.error(ex.getMessage()); } } @Override protected void finalize() throws Throwable { super.finalize(); dispose(); } public synchronized void dispose() { if (handle != 0L) { XGBoostJNI.XGBoosterFree(handle); handle = 0; } } @Override public void write(Kryo kryo, Output output) { try { byte[] serObj = this.toByteArray(); int serObjSize = serObj.length; output.writeInt(serObjSize); output.writeInt(version); output.write(serObj); } catch (XGBoostError ex) { logger.error(ex.getMessage(), ex); } } @Override public void read(Kryo kryo, Input input) { try { this.init(null); int serObjSize = input.readInt(); this.version = input.readInt(); byte[] bytes = new byte[serObjSize]; input.readBytes(bytes); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModelFromBuffer(this.handle, bytes)); } catch (XGBoostError ex) { logger.error(ex.getMessage(), ex); } } }
0
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j/java/DMatrix.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.util.Iterator; import ml.dmlc.xgboost4j.LabeledPoint; /** * DMatrix for xgboost. * * @author hzx */ public class DMatrix { protected long handle = 0; private int gpu_id = 0; /** * sparse matrix type (CSR or CSC) */ public static enum SparseType { CSR, CSC; } /** * Create DMatrix from iterator. * * @param iter The data iterator of mini batch to provide the data. * @param cacheInfo Cache path information, used for external memory setting, can be null. * @throws XGBoostError */ public DMatrix(Iterator<LabeledPoint> iter, String cacheInfo) throws XGBoostError { if (iter == null) { throw new NullPointerException("iter: null"); } // 32k as batch size int batchSize = 32 << 10; Iterator<DataBatch> batchIter = new DataBatch.BatchIterator(iter, batchSize); long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromDataIter(batchIter, cacheInfo, out)); handle = out[0]; } /** * Create DMatrix by loading libsvm file from dataPath * * @param dataPath The path to the data. * @throws XGBoostError */ public DMatrix(String dataPath) throws XGBoostError { if (dataPath == null) { throw new NullPointerException("dataPath: null"); } long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromFile(dataPath, 1, out)); handle = out[0]; } /** * Create DMatrix from Sparse matrix in CSR/CSC format. * @param headers The row index of the matrix. * @param indices The indices of presenting entries. * @param data The data content. * @param st Type of sparsity. * @throws XGBoostError */ @Deprecated public DMatrix(long[] headers, int[] indices, float[] data, SparseType st) throws XGBoostError { long[] out = new long[1]; if (st == SparseType.CSR) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSREx(headers, indices, data, 0, out)); } else if (st == SparseType.CSC) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSCEx(headers, indices, data, 0, out)); } else { throw new UnknownError("unknow sparsetype"); } handle = out[0]; } /** * Create DMatrix from Sparse matrix in CSR/CSC format. * @param headers The row index of the matrix. * @param indices The indices of presenting entries. * @param data The data content. * @param st Type of sparsity. * @param shapeParam when st is CSR, it specifies the column number, otherwise it is taken as * row number * @throws XGBoostError */ public DMatrix(long[] headers, int[] indices, float[] data, SparseType st, int shapeParam) throws XGBoostError { long[] out = new long[1]; if (st == SparseType.CSR) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSREx(headers, indices, data, shapeParam, out)); } else if (st == SparseType.CSC) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSCEx(headers, indices, data, shapeParam, out)); } else { throw new UnknownError("unknow sparsetype"); } handle = out[0]; } /** * create DMatrix from dense matrix * * @param data data values * @param nrow number of rows * @param ncol number of columns * @throws XGBoostError native error */ public DMatrix(float[] data, int nrow, int ncol) throws XGBoostError { long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromMat(data, nrow, ncol, 0.0f, out)); handle = out[0]; } /** * create DMatrix from dense matrix * @param data data values * @param nrow number of rows * @param ncol number of columns * @param missing the specified value to represent the missing value */ public DMatrix(float[] data, int nrow, int ncol, float missing) throws XGBoostError { long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromMat(data, nrow, ncol, missing, out)); handle = out[0]; } /** * used for DMatrix slice */ protected DMatrix(long handle) { this.handle = handle; } //START CUDF Support /** * Create DMatrix from cuDF. * * @param gdf_cols The native handles of GDF columns * @throws XGBoostError native error */ public DMatrix(long[] gdf_cols) throws XGBoostError { this(gdf_cols, 0); } /** * Create DMatrix from cuDF. * * @param gdf_cols The native handles of GDF columns * @param gpu_id The gpu id to use * @throws XGBoostError native error */ public DMatrix(long[] gdf_cols, int gpu_id) throws XGBoostError { if (gdf_cols == null) { throw new NullPointerException("gdf_cols: null"); } long[] out = new long[1]; this.gpu_id = gpu_id; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCUDF(gdf_cols, out, gpu_id)); handle = out[0]; } /** * Set CUDF information for DMatrix. * * @param field The name of this info, such as "label" or "weight" * @param cols The native handles of GDF columns * @throws XGBoostError native error */ public void setCUDFInfo(String field, long[] cols) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetCUDFInfo(handle, field, cols, gpu_id)); } // END CUDF Support /** * set label of dmatrix * * @param labels labels * @throws XGBoostError native error */ public void setLabel(float[] labels) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetFloatInfo(handle, "label", labels)); } /** * set weight of each instance * * @param weights weights * @throws XGBoostError native error */ public void setWeight(float[] weights) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetFloatInfo(handle, "weight", weights)); } /** * Set base margin (initial prediction). * * The margin must have the same number of elements as the number of * rows in this matrix. */ public void setBaseMargin(float[] baseMargin) throws XGBoostError { if (baseMargin.length != rowNum()) { throw new IllegalArgumentException(String.format( "base margin must have exactly %s elements, got %s", rowNum(), baseMargin.length)); } XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetFloatInfo(handle, "base_margin", baseMargin)); } /** * Set base margin (initial prediction). */ public void setBaseMargin(float[][] baseMargin) throws XGBoostError { setBaseMargin(flatten(baseMargin)); } /** * Set group sizes of DMatrix (used for ranking) * * @param group group size as array * @throws XGBoostError native error */ public void setGroup(int[] group) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetGroup(handle, group)); } private float[] getFloatInfo(String field) throws XGBoostError { float[][] infos = new float[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixGetFloatInfo(handle, field, infos)); return infos[0]; } private int[] getIntInfo(String field) throws XGBoostError { int[][] infos = new int[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixGetUIntInfo(handle, field, infos)); return infos[0]; } /** * get label values * * @return label * @throws XGBoostError native error */ public float[] getLabel() throws XGBoostError { return getFloatInfo("label"); } /** * get weight of the DMatrix * * @return weights * @throws XGBoostError native error */ public float[] getWeight() throws XGBoostError { return getFloatInfo("weight"); } /** * Get base margin of the DMatrix. */ public float[] getBaseMargin() throws XGBoostError { return getFloatInfo("base_margin"); } /** * Slice the DMatrix and return a new DMatrix that only contains `rowIndex`. * * @param rowIndex row index * @return sliced new DMatrix * @throws XGBoostError native error */ public DMatrix slice(int[] rowIndex) throws XGBoostError { long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSliceDMatrix(handle, rowIndex, out)); long sHandle = out[0]; DMatrix sMatrix = new DMatrix(sHandle); return sMatrix; } /** * get the row number of DMatrix * * @return number of rows * @throws XGBoostError native error */ public long rowNum() throws XGBoostError { long[] rowNum = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixNumRow(handle, rowNum)); return rowNum[0]; } /** * save DMatrix to filePath */ public void saveBinary(String filePath) { XGBoostJNI.XGDMatrixSaveBinary(handle, filePath, 1); } /** * Get the handle */ public long getHandle() { return handle; } /** * flatten a mat to array */ private static float[] flatten(float[][] mat) { int size = 0; for (float[] array : mat) size += array.length; float[] result = new float[size]; int pos = 0; for (float[] ar : mat) { System.arraycopy(ar, 0, result, pos, ar.length); pos += ar.length; } return result; } @Override protected void finalize() { dispose(); } public synchronized void dispose() { if (handle != 0) { XGBoostJNI.XGDMatrixFree(handle); handle = 0; } } }
0
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j/java/NativeLibLoader.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.*; import java.lang.reflect.Field; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * class to load native library * * @author hzx */ class NativeLibLoader { private static final Log logger = LogFactory.getLog(NativeLibLoader.class); private static boolean initialized = false; private static final String nativeResourcePath = "/lib/"; private static final String[] libNames = new String[]{"xgboost4j"}; static synchronized void initXGBoost() throws IOException { if (!initialized) { for (String libName : libNames) { try { String libraryFromJar = nativeResourcePath + System.mapLibraryName(libName); loadLibraryFromJar(libraryFromJar); } catch (IOException ioe) { logger.error("failed to load " + libName + " library from jar"); throw ioe; } } initialized = true; } } /** * Loads library from current JAR archive * <p/> * The file from JAR is copied into system temporary directory and then loaded. * The temporary file is deleted after exiting. * Method uses String as filename because the pathname is "abstract", not system-dependent. * <p/> * The restrictions of {@link File#createTempFile(java.lang.String, java.lang.String)} apply to * {@code path}. * * @param path The filename inside JAR as absolute path (beginning with '/'), * e.g. /package/File.ext * @throws IOException If temporary file creation or read/write operation fails * @throws IllegalArgumentException If source file (param path) does not exist * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than * three characters */ private static void loadLibraryFromJar(String path) throws IOException, IllegalArgumentException{ String temp = createTempFileFromResource(path); // Finally, load the library System.load(temp); } /** * Create a temp file that copies the resource from current JAR archive * <p/> * The file from JAR is copied into system temp file. * The temporary file is deleted after exiting. * Method uses String as filename because the pathname is "abstract", not system-dependent. * <p/> * The restrictions of {@link File#createTempFile(java.lang.String, java.lang.String)} apply to * {@code path}. * @param path Path to the resources in the jar * @return The created temp file. * @throws IOException * @throws IllegalArgumentException */ static String createTempFileFromResource(String path) throws IOException, IllegalArgumentException { // Obtain filename from path if (!path.startsWith("/")) { throw new IllegalArgumentException("The path has to be absolute (start with '/')."); } String[] parts = path.split("/"); String filename = (parts.length > 1) ? parts[parts.length - 1] : null; // Split filename to prexif and suffix (extension) String prefix = ""; String suffix = null; if (filename != null) { parts = filename.split("\\.", 2); prefix = parts[0]; suffix = (parts.length > 1) ? "." + parts[parts.length - 1] : null; // Thanks, davs! :-) } // Check if the filename is okay if (filename == null || prefix.length() < 3) { throw new IllegalArgumentException("The filename has to be at least 3 characters long."); } // Prepare temporary file File temp = File.createTempFile(prefix, suffix); temp.deleteOnExit(); if (!temp.exists()) { throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist."); } // Prepare buffer for data copying byte[] buffer = new byte[1024]; int readBytes; // Open and check input stream InputStream is = NativeLibLoader.class.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("File " + path + " was not found inside JAR."); } // Open output stream and copy data between source file in JAR and the temporary file OutputStream os = new FileOutputStream(temp); try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { // If read/write fails, close streams safely before throwing an exception os.close(); is.close(); } return temp.getAbsolutePath(); } }
0
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j/java/XGBoost.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.IOException; import java.io.InputStream; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * trainer for xgboost * * @author hzx */ public class XGBoost { private static final Log logger = LogFactory.getLog(XGBoost.class); /** * load model from modelPath * * @param modelPath booster modelPath (model generated by booster.saveModel) * @throws XGBoostError native error */ public static Booster loadModel(String modelPath) throws XGBoostError { return Booster.loadModel(modelPath); } /** * Load a new Booster model from a file opened as input stream. * The assumption is the input stream only contains one XGBoost Model. * This can be used to load existing booster models saved by other xgboost bindings. * * @param in The input stream of the file, * will be closed after this function call. * @return The create boosted * @throws XGBoostError * @throws IOException */ public static Booster loadModel(InputStream in) throws XGBoostError, IOException { return Booster.loadModel(in); } /** * Train a booster given parameters. * * @param dtrain Data to be trained. * @param params Parameters. * @param round Number of boosting iterations. * @param watches a group of items to be evaluated during training, this allows user to watch * performance on the validation set. * @param obj customized objective * @param eval customized evaluation * @return The trained booster. */ public static Booster train( DMatrix dtrain, Map<String, Object> params, int round, Map<String, DMatrix> watches, IObjective obj, IEvaluation eval) throws XGBoostError { return train(dtrain, params, round, watches, null, obj, eval, 0); } /** * Train a booster given parameters. * * @param dtrain Data to be trained. * @param params Parameters. * @param round Number of boosting iterations. * @param watches a group of items to be evaluated during training, this allows user to watch * performance on the validation set. * @param metrics array containing the evaluation metrics for each matrix in watches for each * iteration * @param earlyStoppingRound if non-zero, training would be stopped * after a specified number of consecutive * increases in any evaluation metric. * @param obj customized objective * @param eval customized evaluation * @return The trained booster. */ public static Booster train( DMatrix dtrain, Map<String, Object> params, int round, Map<String, DMatrix> watches, float[][] metrics, IObjective obj, IEvaluation eval, int earlyStoppingRound) throws XGBoostError { return train(dtrain, params, round, watches, metrics, obj, eval, earlyStoppingRound, null); } /** * Train a booster given parameters. * * @param dtrain Data to be trained. * @param params Parameters. * @param round Number of boosting iterations. * @param watches a group of items to be evaluated during training, this allows user to watch * performance on the validation set. * @param metrics array containing the evaluation metrics for each matrix in watches for each * iteration * @param earlyStoppingRounds if non-zero, training would be stopped * after a specified number of consecutive * goes to the unexpected direction in any evaluation metric. * @param obj customized objective * @param eval customized evaluation * @param booster train from scratch if set to null; train from an existing booster if not null. * @return The trained booster. */ public static Booster train( DMatrix dtrain, Map<String, Object> params, int round, Map<String, DMatrix> watches, float[][] metrics, IObjective obj, IEvaluation eval, int earlyStoppingRounds, Booster booster) throws XGBoostError { //collect eval matrixs String[] evalNames; DMatrix[] evalMats; float bestScore; int bestIteration; List<String> names = new ArrayList<String>(); List<DMatrix> mats = new ArrayList<DMatrix>(); for (Map.Entry<String, DMatrix> evalEntry : watches.entrySet()) { names.add(evalEntry.getKey()); mats.add(evalEntry.getValue()); } evalNames = names.toArray(new String[names.size()]); evalMats = mats.toArray(new DMatrix[mats.size()]); if (isMaximizeEvaluation(params)) { bestScore = -Float.MAX_VALUE; } else { bestScore = Float.MAX_VALUE; } bestIteration = 0; metrics = metrics == null ? new float[evalNames.length][round] : metrics; //collect all data matrixs DMatrix[] allMats; if (evalMats.length > 0) { allMats = new DMatrix[evalMats.length + 1]; allMats[0] = dtrain; System.arraycopy(evalMats, 0, allMats, 1, evalMats.length); } else { allMats = new DMatrix[1]; allMats[0] = dtrain; } //initialize booster if (booster == null) { // Start training on a new booster booster = new Booster(params, allMats); booster.loadRabitCheckpoint(); } else { // Start training on an existing booster booster.setParams(params); } //begin to train for (int iter = booster.getVersion() / 2; iter < round; iter++) { if (booster.getVersion() % 2 == 0) { if (obj != null) { booster.update(dtrain, obj); } else { booster.update(dtrain, iter); } booster.saveRabitCheckpoint(); } //evaluation if (evalMats.length > 0) { float[] metricsOut = new float[evalMats.length]; String evalInfo; if (eval != null) { evalInfo = booster.evalSet(evalMats, evalNames, eval, metricsOut); } else { evalInfo = booster.evalSet(evalMats, evalNames, iter, metricsOut); } for (int i = 0; i < metricsOut.length; i++) { metrics[i][iter] = metricsOut[i]; } // If there is more than one evaluation datasets, the last one would be used // to determinate early stop. float score = metricsOut[metricsOut.length - 1]; if (isMaximizeEvaluation(params)) { // Update best score if the current score is better (no update when equal) if (score > bestScore) { bestScore = score; bestIteration = iter; } } else { if (score < bestScore) { bestScore = score; bestIteration = iter; } } if (earlyStoppingRounds > 0) { if (shouldEarlyStop(earlyStoppingRounds, iter, bestIteration)) { Rabit.trackerPrint(String.format( "early stopping after %d rounds away from the best iteration", earlyStoppingRounds)); break; } } if (Rabit.getRank() == 0 && shouldPrint(params, iter)) { if (shouldPrint(params, iter)){ Rabit.trackerPrint(evalInfo + '\n'); } } } booster.saveRabitCheckpoint(); } return booster; } private static Integer tryGetIntFromObject(Object o) { if (o instanceof Integer) { return (int)o; } else if (o instanceof String) { try { return Integer.parseInt((String)o); } catch (NumberFormatException e) { return null; } } else { return null; } } private static boolean shouldPrint(Map<String, Object> params, int iter) { Object silent = params.get("silent"); Integer silentInt = tryGetIntFromObject(silent); if (silent != null) { if (silent.equals("true") || silent.equals("True") || (silentInt != null && silentInt != 0)) { return false; // "silent" will stop printing, otherwise go look at "verbose_eval" } } Object verboseEval = params.get("verbose_eval"); Integer verboseEvalInt = tryGetIntFromObject(verboseEval); if (verboseEval == null) { return true; // Default to printing evalInfo } else if (verboseEval.equals("false") || verboseEval.equals("False")) { return false; } else if (verboseEvalInt != null) { if (verboseEvalInt == 0) { return false; } else { return iter % verboseEvalInt == 0; } } else { return true; // Don't understand the option, default to printing } } static boolean shouldEarlyStop(int earlyStoppingRounds, int iter, int bestIteration) { return iter - bestIteration >= earlyStoppingRounds; } private static boolean isMaximizeEvaluation(Map<String, Object> params) { try { String maximize = String.valueOf(params.get("maximize_evaluation_metrics")); assert(maximize != null); return Boolean.valueOf(maximize); } catch (Exception ex) { logger.error("maximize_evaluation_metrics has to be specified for enabling early stop," + " allowed value: true/false", ex); throw ex; } } /** * Cross-validation with given parameters. * * @param data Data to be trained. * @param params Booster params. * @param round Number of boosting iterations. * @param nfold Number of folds in CV. * @param metrics Evaluation metrics to be watched in CV. * @param obj customized objective (set to null if not used) * @param eval customized evaluation (set to null if not used) * @return evaluation history * @throws XGBoostError native error */ public static String[] crossValidation( DMatrix data, Map<String, Object> params, int round, int nfold, String[] metrics, IObjective obj, IEvaluation eval) throws XGBoostError { CVPack[] cvPacks = makeNFold(data, nfold, params, metrics); String[] evalHist = new String[round]; String[] results = new String[cvPacks.length]; for (int i = 0; i < round; i++) { for (CVPack cvPack : cvPacks) { if (obj != null) { cvPack.update(obj); } else { cvPack.update(i); } } for (int j = 0; j < cvPacks.length; j++) { if (eval != null) { results[j] = cvPacks[j].eval(eval); } else { results[j] = cvPacks[j].eval(i); } } evalHist[i] = aggCVResults(results); logger.info(evalHist[i]); } return evalHist; } /** * make an n-fold array of CVPack from random indices * * @param data original data * @param nfold num of folds * @param params booster parameters * @param evalMetrics Evaluation metrics * @return CV package array * @throws XGBoostError native error */ private static CVPack[] makeNFold(DMatrix data, int nfold, Map<String, Object> params, String[] evalMetrics) throws XGBoostError { List<Integer> samples = genRandPermutationNums(0, (int) data.rowNum()); int step = samples.size() / nfold; int[] testSlice = new int[step]; int[] trainSlice = new int[samples.size() - step]; int testid, trainid; CVPack[] cvPacks = new CVPack[nfold]; for (int i = 0; i < nfold; i++) { testid = 0; trainid = 0; for (int j = 0; j < samples.size(); j++) { if (j > (i * step) && j < (i * step + step) && testid < step) { testSlice[testid] = samples.get(j); testid++; } else { if (trainid < samples.size() - step) { trainSlice[trainid] = samples.get(j); trainid++; } else { testSlice[testid] = samples.get(j); testid++; } } } DMatrix dtrain = data.slice(trainSlice); DMatrix dtest = data.slice(testSlice); CVPack cvPack = new CVPack(dtrain, dtest, params); //set eval types if (evalMetrics != null) { for (String type : evalMetrics) { cvPack.booster.setParam("eval_metric", type); } } cvPacks[i] = cvPack; } return cvPacks; } private static List<Integer> genRandPermutationNums(int start, int end) { List<Integer> samples = new ArrayList<Integer>(); for (int i = start; i < end; i++) { samples.add(i); } Collections.shuffle(samples); return samples; } /** * Aggregate cross-validation results. * * @param results eval info from each data sample * @return cross-validation eval info */ private static String aggCVResults(String[] results) { Map<String, List<Float>> cvMap = new HashMap<String, List<Float>>(); String aggResult = results[0].split("\t")[0]; for (String result : results) { String[] items = result.split("\t"); for (int i = 1; i < items.length; i++) { String[] tup = items[i].split(":"); String key = tup[0]; Float value = Float.valueOf(tup[1]); if (!cvMap.containsKey(key)) { cvMap.put(key, new ArrayList<Float>()); } cvMap.get(key).add(value); } } for (String key : cvMap.keySet()) { float value = 0f; for (Float tvalue : cvMap.get(key)) { value += tvalue; } value /= cvMap.get(key).size(); aggResult += String.format("\tcv-%s:%f", key, value); } return aggResult; } /** * cross validation package for xgb * * @author hzx */ private static class CVPack { DMatrix dtrain; DMatrix dtest; DMatrix[] dmats; String[] names; Booster booster; /** * create an cross validation package * * @param dtrain train data * @param dtest test data * @param params parameters * @throws XGBoostError native error */ public CVPack(DMatrix dtrain, DMatrix dtest, Map<String, Object> params) throws XGBoostError { dmats = new DMatrix[]{dtrain, dtest}; booster = new Booster(params, dmats); names = new String[]{"train", "test"}; this.dtrain = dtrain; this.dtest = dtest; } /** * update one iteration * * @param iter iteration num * @throws XGBoostError native error */ public void update(int iter) throws XGBoostError { booster.update(dtrain, iter); } /** * update one iteration * * @param obj customized objective * @throws XGBoostError native error */ public void update(IObjective obj) throws XGBoostError { booster.update(dtrain, obj); } /** * evaluation * * @param iter iteration num * @return evaluation * @throws XGBoostError native error */ public String eval(int iter) throws XGBoostError { return booster.evalSet(dmats, names, iter); } /** * evaluation * * @param eval customized eval * @return evaluation * @throws XGBoostError native error */ public String eval(IEvaluation eval) throws XGBoostError { return booster.evalSet(dmats, names, eval); } } }
0
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j/0.90.1-Beta/ml/dmlc/xgboost4j/java/XGBoostJNI.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * xgboost JNI functions * change 2015-7-6: *use a long[] (length=1) as container of handle to get the output DMatrix or Booster * * @author hzx */ class XGBoostJNI { private static final Log logger = LogFactory.getLog(DMatrix.class); static { try { NativeLibLoader.initXGBoost(); } catch (Exception ex) { logger.error("Failed to load native library", ex); throw new RuntimeException(ex); } } /** * Check the return code of the JNI call. * * @throws XGBoostError if the call failed. */ static void checkCall(int ret) throws XGBoostError { if (ret != 0) { throw new XGBoostError(XGBGetLastError()); } } public final static native String XGBGetLastError(); public final static native int XGDMatrixCreateFromFile(String fname, int silent, long[] out); final static native int XGDMatrixCreateFromDataIter(java.util.Iterator<DataBatch> iter, String cache_info, long[] out); public final static native int XGDMatrixCreateFromCSREx(long[] indptr, int[] indices, float[] data, int shapeParam, long[] out); public final static native int XGDMatrixCreateFromCSCEx(long[] colptr, int[] indices, float[] data, int shapeParam, long[] out); public final static native int XGDMatrixCreateFromMat(float[] data, int nrow, int ncol, float missing, long[] out); // CUDF support: Suppose gdf_columns are passed as array of native handles public final static native int XGDMatrixCreateFromCUDF(long[] cols, long[] out, int gpu_id); public final static native int XGDMatrixSetCUDFInfo(long handle, String field, long[] cols, int gpu_id); public final static native int XGDMatrixSliceDMatrix(long handle, int[] idxset, long[] out); public final static native int XGDMatrixFree(long handle); public final static native int XGDMatrixSaveBinary(long handle, String fname, int silent); public final static native int XGDMatrixSetFloatInfo(long handle, String field, float[] array); public final static native int XGDMatrixSetUIntInfo(long handle, String field, int[] array); public final static native int XGDMatrixSetGroup(long handle, int[] group); public final static native int XGDMatrixGetFloatInfo(long handle, String field, float[][] info); public final static native int XGDMatrixGetUIntInfo(long handle, String filed, int[][] info); public final static native int XGDMatrixNumRow(long handle, long[] row); public final static native int XGBoosterCreate(long[] handles, long[] out); public final static native int XGBoosterFree(long handle); public final static native int XGBoosterSetParam(long handle, String name, String value); public final static native int XGBoosterUpdateOneIter(long handle, int iter, long dtrain); public final static native int XGBoosterBoostOneIter(long handle, long dtrain, float[] grad, float[] hess); public final static native int XGBoosterEvalOneIter(long handle, int iter, long[] dmats, String[] evnames, String[] eval_info); public final static native int XGBoosterPredict(long handle, long dmat, int option_mask, int ntree_limit, float[][] predicts); public final static native int XGBoosterLoadModel(long handle, String fname); public final static native int XGBoosterSaveModel(long handle, String fname); public final static native int XGBoosterLoadModelFromBuffer(long handle, byte[] bytes); public final static native int XGBoosterGetModelRaw(long handle, byte[][] out_bytes); public final static native int XGBoosterDumpModelEx(long handle, String fmap, int with_stats, String format, String[][] out_strings); public final static native int XGBoosterDumpModelExWithFeatures( long handle, String[] feature_names, int with_stats, String format, String[][] out_strings); public final static native int XGBoosterGetAttrNames(long handle, String[][] out_strings); public final static native int XGBoosterGetAttr(long handle, String key, String[] out_string); public final static native int XGBoosterSetAttr(long handle, String key, String value); public final static native int XGBoosterLoadRabitCheckpoint(long handle, int[] out_version); public final static native int XGBoosterSaveRabitCheckpoint(long handle); // rabit functions public final static native int RabitInit(String[] args); public final static native int RabitFinalize(); public final static native int RabitTrackerPrint(String msg); public final static native int RabitGetRank(int[] out); public final static native int RabitGetWorldSize(int[] out); public final static native int RabitVersionNumber(int[] out); // Perform Allreduce operation on data in sendrecvbuf. // This JNI function does not support the callback function for data preparation yet. final static native int RabitAllreduce(ByteBuffer sendrecvbuf, int count, int enum_dtype, int enum_op); }
0
java-sources/ai/rapids/xgboost4j-spark/0.90.1-Beta/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j-spark/0.90.1-Beta/ml/dmlc/xgboost4j/java/XGBoostSparkJNI.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import ai.rapids.cudf.Cuda; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * JNI functions for XGBoost4J-Spark */ public class XGBoostSparkJNI { private static final Log logger = LogFactory.getLog(XGBoostSparkJNI.class); static { try { NativeLibLoader.initXGBoost(); } catch (Exception ex) { logger.error("Failed to load native library", ex); throw new RuntimeException(ex); } } /** * Build an array of fixed-length Spark UnsafeRow using the GPU. * @param nativeColumnPtrs native address of cudf column pointers * @return native address of the UnsafeRow array * NOTE: It is the responsibility of the caller to free the native memory * returned by this function (e.g.: using Platform.freeMemory). */ public static native long buildUnsafeRows(long[] nativeColumnPtrs); public static native int getGpuDevice(); public static native int allocateGpuDevice(); }
0
java-sources/ai/rapids/xgboost4j-spark/0.90.1-Beta/ml/dmlc/xgboost4j/java/spark
java-sources/ai/rapids/xgboost4j-spark/0.90.1-Beta/ml/dmlc/xgboost4j/java/spark/rapids/GpuColumnBatch.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java.spark.rapids; import ai.rapids.cudf.ColumnVector; import ai.rapids.cudf.Table; import org.apache.spark.sql.types.StructType; public class GpuColumnBatch { private final Table table; private final StructType schema; public GpuColumnBatch(Table table, StructType schema) { this.table = table; this.schema = schema; } public StructType getSchema() { return schema; } public long getNumRows() { return table.getRowCount(); } public int getNumColumns() { return table.getNumberOfColumns(); } public ColumnVector getColumnVector(int index) { return table.getColumn(index); } public long getColumn(int index) { ColumnVector v = table.getColumn(index); return v.getNativeCudfColumnAddress(); } }
0
java-sources/ai/rapids/xgboost4j-spark_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/spark
java-sources/ai/rapids/xgboost4j-spark_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/spark/rapids/GpuColumnBatch.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java.spark.rapids; import java.util.ArrayList; import java.util.List; import ai.rapids.cudf.ColumnVector; import ai.rapids.cudf.DType; import ai.rapids.cudf.Table; import org.apache.spark.sql.types.BooleanType; import org.apache.spark.sql.types.ByteType; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DateType; import org.apache.spark.sql.types.DoubleType; import org.apache.spark.sql.types.FloatType; import org.apache.spark.sql.types.IntegerType; import org.apache.spark.sql.types.LongType; import org.apache.spark.sql.types.ShortType; import org.apache.spark.sql.types.StringType; import org.apache.spark.sql.types.StructType; import org.apache.spark.sql.types.TimestampType; public class GpuColumnBatch { private final Table table; private final StructType schema; public GpuColumnBatch(Table table, StructType schema) { this.table = table; this.schema = schema; } public StructType getSchema() { return schema; } public long getNumRows() { return table.getRowCount(); } public int getNumColumns() { return table.getNumberOfColumns(); } public ColumnVector getColumnVector(int index) { return table.getColumn(index); } public long getColumn(int index) { ColumnVector v = table.getColumn(index); return v.getNativeCudfColumnAddress(); } public int[] groupByColumnWithCountHost(int groupIndex) { ColumnVector cv = getColumnVector(groupIndex); cv.ensureOnHost(); List<Integer> countData = new ArrayList<>(); int groupId = 0, groupSize = 0; for (int i = 0; i < cv.getRowCount(); i ++) { if(groupId != cv.getInt(i)) { groupId = cv.getInt(i); if (groupSize > 0) { countData.add(groupSize); } groupSize = 1; } else { groupSize ++; } } if (groupSize > 0) { countData.add(groupSize); } int[] counts = new int[countData.size()]; for (int i = 0; i < counts.length; i ++) { counts[i] = countData.get(i); } return counts; } /** * This is used to group the CUDF Dataset by column 'groupIndex', and merge all the rows into * one row in each group based on column 'oneIndex'. For example * 1 0 * 2 3 (0, 1, true) 0 * 2 3 => 3 * 5 6 6 * 5 6 * And the last row in each group is selected. * @param groupIndex The index of column to group by * @param oneIndex The index of column to get one value in each group * @param checkEqual Whether to check all the values in one group are the same * @return The native handle of the result column containing the merged data. */ public long[] groupByColumnWithAggregation(int groupIndex, int oneIndex, boolean checkEqual) { ColumnVector cv = getColumnVector(groupIndex); cv.ensureOnHost(); ColumnVector aggrCV = getColumnVector(oneIndex); aggrCV.ensureOnHost(); List<Float> onesData = new ArrayList<>(); int groupId = 0; Float oneValue = null; for (int i = 0; i < cv.getRowCount(); i ++) { if(groupId != cv.getInt(i)) { groupId = cv.getInt(i); if (oneValue != null) { onesData.add(oneValue); } oneValue = aggrCV.getFloat(i); } else { if (checkEqual && oneValue != null && oneValue != aggrCV.getFloat(i)) { return null; } } } if (oneValue != null) { onesData.add(oneValue); } // FIXME how to release this ColumnVector? ColumnVector retCV = ColumnVector.fromBoxedFloats(onesData.toArray(new Float[]{})); retCV.ensureOnDevice(); return new long[] {retCV.getNativeCudfColumnAddress()}; } public static DType getRapidsType(DataType type) { DType result = toRapidsOrNull(type); if (result == null) { throw new IllegalArgumentException(type + " is not supported for GPU processing yet."); } return result; } private static DType toRapidsOrNull(DataType type) { if (type instanceof LongType) { return DType.INT64; } else if (type instanceof DoubleType) { return DType.FLOAT64; } else if (type instanceof ByteType) { return DType.INT8; } else if (type instanceof BooleanType) { return DType.BOOL8; } else if (type instanceof ShortType) { return DType.INT16; } else if (type instanceof IntegerType) { return DType.INT32; } else if (type instanceof FloatType) { return DType.FLOAT32; } else if (type instanceof DateType) { return DType.DATE32; } else if (type instanceof TimestampType) { return DType.TIMESTAMP; } else if (type instanceof StringType) { return DType.STRING; // TODO what do we want to do about STRING_CATEGORY??? } return null; } }
0
java-sources/ai/rapids/xgboost4j-spark_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/spark
java-sources/ai/rapids/xgboost4j-spark_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/spark/rapids/PartitionReader.java
/* * 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 ml.dmlc.xgboost4j.java.spark.rapids; import java.io.Closeable; import java.io.IOException; /** * A partition reader returned by { PartitionReaderFactory#createReader(InputPartition)} or * { PartitionReaderFactory#createColumnarReader(InputPartition)}. It's responsible for * outputting data for a RDD partition. * * Note that, Currently the type `T` can only be GpuColumnBatch * for normal data sources, or { org.apache.spark.sql.vectorized.ColumnarBatch} for columnar * data sources(whose { PartitionReaderFactory#supportColumnarReads(InputPartition)} * returns true). */ public interface PartitionReader<T> extends Closeable { /** * Proceed to next record, returns false if there is no more records. * * @throws IOException if failure happens during disk/network IO like reading files. */ boolean next() throws IOException; /** * Return the current record. This method should return same value until `next` is called. */ T get(); }
0
java-sources/ai/rapids/xgboost4j-spark_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/spark
java-sources/ai/rapids/xgboost4j-spark_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/spark/rapids/PartitionReaderFactory.java
/* * 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 ml.dmlc.xgboost4j.java.spark.rapids; import java.io.Serializable; import org.apache.spark.sql.execution.datasources.FilePartition; /** * A factory used to create {@link PartitionReader} instances. * * If Spark fails to execute any methods in the implementations of this interface or in the returned * {@link PartitionReader} (by throwing an exception), corresponding Spark task would fail and * get retried until hitting the maximum retry times. */ public interface PartitionReaderFactory extends Serializable { /** * Returns a columnar partition reader to read data from the given {@link FilePartition}. * * Implementations probably need to cast the input partition to the concrete * {@link FilePartition} class defined for the data source. */ default PartitionReader<GpuColumnBatch> createColumnarReader(FilePartition partition) { throw new UnsupportedOperationException("Cannot create columnar reader."); } /** * Returns true if the given {@link FilePartition} should be read by Spark in a columnar way. * This means, implementations must also implement { #createColumnarReader(FilePartition)} * for the input partitions that this method returns true. * * As of Spark 2.4, Spark can only read all input partition in a columnar way, or none of them. * Data source can't mix columnar and row-based partitions. This may be relaxed in future * versions. */ default boolean supportColumnarReads(FilePartition partition) { return false; } }
0
java-sources/ai/rapids/xgboost4j-spark_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j/java/spark
java-sources/ai/rapids/xgboost4j-spark_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j/java/spark/rapids/GpuColumnBatch.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java.spark.rapids; import java.util.List; import ai.rapids.cudf.ColumnVector; import ai.rapids.cudf.DType; import ai.rapids.cudf.Table; import org.apache.spark.sql.types.*; import org.apache.spark.util.random.BernoulliCellSampler; import ml.dmlc.xgboost4j.scala.spark.rapids.GpuSampler; public class GpuColumnBatch { private Table table; private final StructType schema; private GpuSampler sampler; public GpuColumnBatch(Table table, StructType schema) { this.table = table; this.schema = schema; } public void setSampler(GpuSampler sampler) { this.sampler = sampler; } public GpuSampler getSampler() { return sampler; } public void samplingTable() { if (sampler != null) { BernoulliCellSampler bcs = new BernoulliCellSampler( sampler.lb(), sampler.ub(), sampler.complement()); bcs.setSeed(sampler.seed()); Long num_rows = getNumRows(); byte[] maskVals = new byte[num_rows.intValue()]; for (int i = 0; i < num_rows.intValue(); i++) { maskVals[i] = (byte) bcs.sample(); } ColumnVector mask = ColumnVector.boolFromBytes(maskVals); Table filteredTable = table.filter(mask); mask.close(); table.close(); table = filteredTable; } } public void samplingClose() { // In case of sampling, we have replaced table with filtered table, // so we must manually free filtered table if (sampler != null) { table.close(); } } public StructType getSchema() { return schema; } public long getNumRows() { return table.getRowCount(); } public int getNumColumns() { return table.getNumberOfColumns(); } public ColumnVector getColumnVector(int index) { return table.getColumn(index); } public long getColumn(int index) { ColumnVector v = table.getColumn(index); return v.getNativeCudfColumnAddress(); } public ColumnVector getColumnVectorInitHost(int index) { ColumnVector cv = table.getColumn(index); cv.ensureOnHost(); return cv; } private double getNumericValueInColumn(int dataIndex, ColumnVector cv, StructField field) { DataType type = field.dataType(); double value; if (type instanceof FloatType) { value = cv.getFloat(dataIndex); } else if (type instanceof IntegerType) { value = cv.getInt(dataIndex); } else if (type instanceof ByteType) { value = cv.getByte(dataIndex); } else if (type instanceof ShortType) { value = cv.getShort(dataIndex); } else if (type instanceof DoubleType) { value = cv.getDouble(dataIndex); } else if (type instanceof LongType) { value = cv.getLong(dataIndex); } else { throw new IllegalArgumentException("Not a numeric type in column: " + field.name()); } return value; } private double getNumericValueInColumn(int dataIndex, int colIndex, double defVal) { ColumnVector cv = getColumnVector(colIndex); cv.ensureOnHost(); return cv.getRowCount() > 0 ? getNumericValueInColumn(dataIndex, cv, getSchema().apply(colIndex)) : defVal; } public int getIntInColumn(int dataIndex, int colIndex, int defVal) { return (int)getNumericValueInColumn(dataIndex, colIndex, defVal); } /** * Group data by column "groupIndex", and do "count" aggregation on column "groupIndex", * while do aggregation similar to "average" on column "weightIdx", but require values in * a group are equal to each other, then merge the results with "groupInfo" and "weightInfo" * separately. * * This is used to calculate group and weight info, and support chunk loading. * * @param groupIdx The index of column to group by. * @param weightIdx The index of column where to get a value in each group. * @param prevTailGid The group id of last group in prevGroupInfo. * @param groupInfo Group information calculated from earlier batches. * @param weightInfo Weight information calculated from earlier batches. * @return The group id of last group in current column batch. */ public int groupAndAggregateOnColumnsHost(int groupIdx, int weightIdx, int prevTailGid, List<Integer> groupInfo, List<Float> weightInfo) { // Weight: Initialize info if having weight column final boolean hasWeight = weightIdx >= 0; ColumnVector aggrCV = null; Float curWeight = null; if (hasWeight) { aggrCV = getColumnVectorInitHost(weightIdx); Float firstWeight = aggrCV.getRowCount() > 0 ? (float)getNumericValueInColumn(0, aggrCV, getSchema().apply(weightIdx)) : null; curWeight = weightInfo.isEmpty() ? firstWeight : weightInfo.get(weightInfo.size() - 1); } // Initialize group info ColumnVector groupCV = getColumnVectorInitHost(groupIdx); StructField groupSF = getSchema().apply(groupIdx); int groupId = prevTailGid; int groupSize = groupInfo.isEmpty() ? 0 : groupInfo.get(groupInfo.size() - 1); for (int i = 0; i < groupCV.getRowCount(); i ++) { Float weight = hasWeight ? (float)getNumericValueInColumn(i, aggrCV, getSchema().apply(weightIdx)) : 0; int gid = (int)getNumericValueInColumn(i, groupCV, groupSF); if(gid == groupId) { // The same group groupSize ++; // Weight: Check values in the same group if having weight column if (hasWeight && !weight.equals(curWeight)) { throw new IllegalArgumentException("The instances in the same group have to be" + " assigned with the same weight. Unexpected weight: " + weight); } } else { // A new group, update group info addOrUpdateInfos(prevTailGid, groupId, groupSize, curWeight, hasWeight, groupInfo, weightInfo); if (hasWeight) { curWeight = weight; } groupId = gid; groupSize = 1; } } // handle the last group addOrUpdateInfos(prevTailGid, groupId, groupSize, curWeight, hasWeight, groupInfo, weightInfo); return groupId; } private static void addOrUpdateInfos(int prevTailGid, int curGid, int curGroupSize, Float curWeight, boolean hasWeight, List<Integer> groupInfo, List<Float> weightInfo) { if (curGroupSize <= 0) { return; } if (groupInfo.isEmpty() || curGid != prevTailGid) { // The first group of the first batch or a completely new group groupInfo.add(curGroupSize); // Weight: Add weight info if (hasWeight && curWeight != null) { weightInfo.add(curWeight); } } else { // This is the case when some rows at the beginning of this batch belong to // last group in previous batch, so update the group size for previous group info. groupInfo.set(groupInfo.size() - 1, curGroupSize); // No need to update the weight of last group since all the weights in a group are the same } } public static DType getRapidsType(DataType type) { DType result = toRapidsOrNull(type); if (result == null) { throw new IllegalArgumentException(type + " is not supported for GPU processing yet."); } return result; } private static DType toRapidsOrNull(DataType type) { if (type instanceof LongType) { return DType.INT64; } else if (type instanceof DoubleType) { return DType.FLOAT64; } else if (type instanceof ByteType) { return DType.INT8; } else if (type instanceof BooleanType) { return DType.BOOL8; } else if (type instanceof ShortType) { return DType.INT16; } else if (type instanceof IntegerType) { return DType.INT32; } else if (type instanceof FloatType) { return DType.FLOAT32; } else if (type instanceof DateType) { return DType.DATE32; } else if (type instanceof TimestampType) { return DType.TIMESTAMP; } else if (type instanceof StringType) { return DType.STRING; // TODO what do we want to do about STRING_CATEGORY??? } return null; } }
0
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/Booster.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.*; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Booster for xgboost, this is a model API that support interactive build of a XGBoost Model */ public class Booster implements Serializable, KryoSerializable { private static final Log logger = LogFactory.getLog(Booster.class); // handle to the booster. private long handle = 0; private int version = 0; /** * Create a new Booster with empty stage. * * @param params Model parameters * @param cacheMats Cached DMatrix entries, * the prediction of these DMatrices will become faster than not-cached data. * @throws XGBoostError native error */ Booster(Map<String, Object> params, DMatrix[] cacheMats) throws XGBoostError { init(cacheMats); setParam("seed", "0"); setParams(params); } /** * Load a new Booster model from modelPath * @param modelPath The path to the model. * @return The created Booster. * @throws XGBoostError */ static Booster loadModel(String modelPath) throws XGBoostError { if (modelPath == null) { throw new NullPointerException("modelPath : null"); } Booster ret = new Booster(new HashMap<String, Object>(), new DMatrix[0]); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModel(ret.handle, modelPath)); return ret; } /** * Load a new Booster model from a file opened as input stream. * The assumption is the input stream only contains one XGBoost Model. * This can be used to load existing booster models saved by other xgboost bindings. * * @param in The input stream of the file. * @return The create boosted * @throws XGBoostError * @throws IOException */ static Booster loadModel(InputStream in) throws XGBoostError, IOException { int size; byte[] buf = new byte[1<<20]; ByteArrayOutputStream os = new ByteArrayOutputStream(); while ((size = in.read(buf)) != -1) { os.write(buf, 0, size); } in.close(); Booster ret = new Booster(new HashMap<String, Object>(), new DMatrix[0]); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModelFromBuffer(ret.handle,os.toByteArray())); return ret; } /** * Set parameter to the Booster. * * @param key param name * @param value param value * @throws XGBoostError native error */ public final void setParam(String key, Object value) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSetParam(handle, key, value.toString())); } /** * Set parameters to the Booster. * * @param params parameters key-value map * @throws XGBoostError native error */ public void setParams(Map<String, Object> params) throws XGBoostError { if (params != null) { for (Map.Entry<String, Object> entry : params.entrySet()) { setParam(entry.getKey(), entry.getValue().toString()); } } } /** * Get attributes stored in the Booster as a Map. * * @return A map contain attribute pairs. * @throws XGBoostError native error */ public final Map<String, String> getAttrs() throws XGBoostError { String[][] attrNames = new String[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterGetAttrNames(handle, attrNames)); Map<String, String> attrMap = new HashMap<>(); for (String name: attrNames[0]) { attrMap.put(name, this.getAttr(name)); } return attrMap; } /** * Get attribute from the Booster. * * @param key attribute key * @return attribute value * @throws XGBoostError native error */ public final String getAttr(String key) throws XGBoostError { String[] attrValue = new String[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterGetAttr(handle, key, attrValue)); return attrValue[0]; } /** * Set attribute to the Booster. * * @param key attribute key * @param value attribute value * @throws XGBoostError native error */ public final void setAttr(String key, String value) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSetAttr(handle, key, value)); } /** * Set attributes to the Booster. * * @param attrs attributes key-value map * @throws XGBoostError native error */ public void setAttrs(Map<String, String> attrs) throws XGBoostError { if (attrs != null) { for (Map.Entry<String, String> entry : attrs.entrySet()) { setAttr(entry.getKey(), entry.getValue()); } } } /** * Update the booster for one iteration. * * @param dtrain training data * @param iter current iteration number * @throws XGBoostError native error */ public void update(DMatrix dtrain, int iter) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterUpdateOneIter(handle, iter, dtrain.getHandle())); } /** * Update with customize obj func * * @param dtrain training data * @param obj customized objective class * @throws XGBoostError native error */ public void update(DMatrix dtrain, IObjective obj) throws XGBoostError { float[][] predicts = this.predict(dtrain, true, 0, false, false); List<float[]> gradients = obj.getGradient(predicts, dtrain); boost(dtrain, gradients.get(0), gradients.get(1)); } /** * update with give grad and hess * * @param dtrain training data * @param grad first order of gradient * @param hess seconde order of gradient * @throws XGBoostError native error */ public void boost(DMatrix dtrain, float[] grad, float[] hess) throws XGBoostError { if (grad.length != hess.length) { throw new AssertionError(String.format("grad/hess length mismatch %s / %s", grad.length, hess.length)); } XGBoostJNI.checkCall(XGBoostJNI.XGBoosterBoostOneIter(handle, dtrain.getHandle(), grad, hess)); } /** * evaluate with given dmatrixs. * * @param evalMatrixs dmatrixs for evaluation * @param evalNames name for eval dmatrixs, used for check results * @param iter current eval iteration * @return eval information * @throws XGBoostError native error */ public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, int iter) throws XGBoostError { long[] handles = dmatrixsToHandles(evalMatrixs); String[] evalInfo = new String[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterEvalOneIter(handle, iter, handles, evalNames, evalInfo)); return evalInfo[0]; } /** * evaluate with given dmatrixs. * * @param evalMatrixs dmatrixs for evaluation * @param evalNames name for eval dmatrixs, used for check results * @param iter current eval iteration * @param metricsOut output array containing the evaluation metrics for each evalMatrix * @return eval information * @throws XGBoostError native error */ public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, int iter, float[] metricsOut) throws XGBoostError { String stringFormat = evalSet(evalMatrixs, evalNames, iter); String[] metricPairs = stringFormat.split("\t"); for (int i = 1; i < metricPairs.length; i++) { metricsOut[i - 1] = Float.valueOf(metricPairs[i].split(":")[1]); } return stringFormat; } /** * evaluate with given customized Evaluation class * * @param evalMatrixs evaluation matrix * @param evalNames evaluation names * @param eval custom evaluator * @return eval information * @throws XGBoostError native error */ public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, IEvaluation eval) throws XGBoostError { // Hopefully, a tiny redundant allocation wouldn't hurt. return evalSet(evalMatrixs, evalNames, eval, new float[evalNames.length]); } public String evalSet(DMatrix[] evalMatrixs, String[] evalNames, IEvaluation eval, float[] metricsOut) throws XGBoostError { String evalInfo = ""; for (int i = 0; i < evalNames.length; i++) { String evalName = evalNames[i]; DMatrix evalMat = evalMatrixs[i]; float evalResult = eval.eval(predict(evalMat), evalMat); String evalMetric = eval.getMetric(); evalInfo += String.format("\t%s-%s:%f", evalName, evalMetric, evalResult); metricsOut[i] = evalResult; } return evalInfo; } /** * Advanced predict function with all the options. * * @param data data * @param outputMargin output margin * @param treeLimit limit number of trees, 0 means all trees. * @param predLeaf prediction minimum to keep leafs * @param predContribs prediction feature contributions * @return predict results */ private synchronized float[][] predict(DMatrix data, boolean outputMargin, int treeLimit, boolean predLeaf, boolean predContribs) throws XGBoostError { int optionMask = 0; if (outputMargin) { optionMask = 1; } if (predLeaf) { optionMask = 2; } if (predContribs) { optionMask = 4; } float[][] rawPredicts = new float[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterPredict(handle, data.getHandle(), optionMask, treeLimit, rawPredicts)); int row = (int) data.rowNum(); int col = rawPredicts[0].length / row; float[][] predicts = new float[row][col]; int r, c; for (int i = 0; i < rawPredicts[0].length; i++) { r = i / col; c = i % col; predicts[r][c] = rawPredicts[0][i]; } return predicts; } /** * Predict leaf indices given the data * * @param data The input data. * @param treeLimit Number of trees to include, 0 means all trees. * @return The leaf indices of the instance. * @throws XGBoostError */ public float[][] predictLeaf(DMatrix data, int treeLimit) throws XGBoostError { return this.predict(data, false, treeLimit, true, false); } /** * Output feature contributions toward predictions of given data * * @param data The input data. * @param treeLimit Number of trees to include, 0 means all trees. * @return The feature contributions and bias. * @throws XGBoostError */ public float[][] predictContrib(DMatrix data, int treeLimit) throws XGBoostError { return this.predict(data, false, treeLimit, true, true); } /** * Predict with data * * @param data dmatrix storing the input * @return predict result * @throws XGBoostError native error */ public float[][] predict(DMatrix data) throws XGBoostError { return this.predict(data, false, 0, false, false); } /** * Predict with data * * @param data data * @param outputMargin output margin * @return predict results */ public float[][] predict(DMatrix data, boolean outputMargin) throws XGBoostError { return this.predict(data, outputMargin, 0, false, false); } /** * Advanced predict function with all the options. * * @param data data * @param outputMargin output margin * @param treeLimit limit number of trees, 0 means all trees. * @return predict results */ public float[][] predict(DMatrix data, boolean outputMargin, int treeLimit) throws XGBoostError { return this.predict(data, outputMargin, treeLimit, false, false); } /** * Save model to modelPath * * @param modelPath model path */ public void saveModel(String modelPath) throws XGBoostError{ XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSaveModel(handle, modelPath)); } /** * Save the model to file opened as output stream. * The model format is compatible with other xgboost bindings. * The output stream can only save one xgboost model. * This function will close the OutputStream after the save. * * @param out The output stream */ public void saveModel(OutputStream out) throws XGBoostError, IOException { out.write(this.toByteArray()); out.close(); } /** * Get the dump of the model as a string array * * @param withStats Controls whether the split statistics are output. * @return dumped model information * @throws XGBoostError native error */ public String[] getModelDump(String featureMap, boolean withStats) throws XGBoostError { return getModelDump(featureMap, withStats, "text"); } public String[] getModelDump(String featureMap, boolean withStats, String format) throws XGBoostError { int statsFlag = 0; if (featureMap == null) { featureMap = ""; } if (withStats) { statsFlag = 1; } if (format == null) { format = "text"; } String[][] modelInfos = new String[1][]; XGBoostJNI.checkCall( XGBoostJNI.XGBoosterDumpModelEx(handle, featureMap, statsFlag, format, modelInfos)); return modelInfos[0]; } /** * Get the dump of the model as a string array with specified feature names. * * @param featureNames Names of the features. * @return dumped model information * @throws XGBoostError */ public String[] getModelDump(String[] featureNames, boolean withStats) throws XGBoostError { return getModelDump(featureNames, withStats, "text"); } public String[] getModelDump(String[] featureNames, boolean withStats, String format) throws XGBoostError { int statsFlag = 0; if (withStats) { statsFlag = 1; } if (format == null) { format = "text"; } String[][] modelInfos = new String[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterDumpModelExWithFeatures( handle, featureNames, statsFlag, format, modelInfos)); return modelInfos[0]; } /** * Supported feature importance types * * WEIGHT = Number of nodes that a feature was used to determine a split * GAIN = Average information gain per split for a feature * COVER = Average cover per split for a feature * TOTAL_GAIN = Total information gain over all splits of a feature * TOTAL_COVER = Total cover over all splits of a feature */ public static class FeatureImportanceType { public static final String WEIGHT = "weight"; public static final String GAIN = "gain"; public static final String COVER = "cover"; public static final String TOTAL_GAIN = "total_gain"; public static final String TOTAL_COVER = "total_cover"; public static final Set<String> ACCEPTED_TYPES = new HashSet<>( Arrays.asList(WEIGHT, GAIN, COVER, TOTAL_GAIN, TOTAL_COVER)); } /** * Get importance of each feature with specified feature names. * * @return featureScoreMap key: feature name, value: feature importance score, can be nill. * @throws XGBoostError native error */ public Map<String, Integer> getFeatureScore(String[] featureNames) throws XGBoostError { String[] modelInfos = getModelDump(featureNames, false); return getFeatureWeightsFromModel(modelInfos); } /** * Get importance of each feature * * @return featureScoreMap key: feature index, value: feature importance score, can be nill * @throws XGBoostError native error */ public Map<String, Integer> getFeatureScore(String featureMap) throws XGBoostError { String[] modelInfos = getModelDump(featureMap, false); return getFeatureWeightsFromModel(modelInfos); } /** * Get the importance of each feature based purely on weights (number of splits) * * @return featureScoreMap key: feature index, * value: feature importance score based on weight * @throws XGBoostError native error */ private Map<String, Integer> getFeatureWeightsFromModel(String[] modelInfos) throws XGBoostError { Map<String, Integer> featureScore = new HashMap<>(); for (String tree : modelInfos) { for (String node : tree.split("\n")) { String[] array = node.split("\\["); if (array.length == 1) { continue; } String fid = array[1].split("\\]")[0]; fid = fid.split("<")[0]; if (featureScore.containsKey(fid)) { featureScore.put(fid, 1 + featureScore.get(fid)); } else { featureScore.put(fid, 1); } } } return featureScore; } /** * Get the feature importances for gain or cover (average or total) * * @return featureImportanceMap key: feature index, * values: feature importance score based on gain or cover * @throws XGBoostError native error */ public Map<String, Double> getScore( String[] featureNames, String importanceType) throws XGBoostError { String[] modelInfos = getModelDump(featureNames, true); return getFeatureImportanceFromModel(modelInfos, importanceType); } /** * Get the feature importances for gain or cover (average or total), with feature names * * @return featureImportanceMap key: feature name, * values: feature importance score based on gain or cover * @throws XGBoostError native error */ public Map<String, Double> getScore( String featureMap, String importanceType) throws XGBoostError { String[] modelInfos = getModelDump(featureMap, true); return getFeatureImportanceFromModel(modelInfos, importanceType); } /** * Get the importance of each feature based on information gain or cover * * @return featureImportanceMap key: feature index, value: feature importance score * based on information gain or cover * @throws XGBoostError native error */ private Map<String, Double> getFeatureImportanceFromModel( String[] modelInfos, String importanceType) throws XGBoostError { if (!FeatureImportanceType.ACCEPTED_TYPES.contains(importanceType)) { throw new AssertionError(String.format("Importance type %s is not supported", importanceType)); } Map<String, Double> importanceMap = new HashMap<>(); Map<String, Double> weightMap = new HashMap<>(); if (importanceType.equals(FeatureImportanceType.WEIGHT)) { Map<String, Integer> importanceWeights = getFeatureWeightsFromModel(modelInfos); for (String feature: importanceWeights.keySet()) { importanceMap.put(feature, new Double(importanceWeights.get(feature))); } return importanceMap; } /* Each split in the tree has this text form: "0:[f28<-9.53674316e-07] yes=1,no=2,missing=1,gain=4000.53101,cover=1628.25" So the line has to be split according to whether cover or gain is desired */ String splitter = "gain="; if (importanceType.equals(FeatureImportanceType.COVER) || importanceType.equals(FeatureImportanceType.TOTAL_COVER)) { splitter = "cover="; } for (String tree: modelInfos) { for (String node: tree.split("\n")) { String[] array = node.split("\\["); if (array.length == 1) { continue; } String[] fidWithImportance = array[1].split("\\]"); // Extract gain or cover from string after closing bracket Double importance = Double.parseDouble( fidWithImportance[1].split(splitter)[1].split(",")[0] ); String fid = fidWithImportance[0].split("<")[0]; if (importanceMap.containsKey(fid)) { importanceMap.put(fid, importance + importanceMap.get(fid)); weightMap.put(fid, 1d + weightMap.get(fid)); } else { importanceMap.put(fid, importance); weightMap.put(fid, 1d); } } } /* By default we calculate total gain and total cover. Divide by the number of nodes per feature to get gain / cover */ if (importanceType.equals(FeatureImportanceType.COVER) || importanceType.equals(FeatureImportanceType.GAIN)) { for (String fid: importanceMap.keySet()) { importanceMap.put(fid, importanceMap.get(fid)/weightMap.get(fid)); } } return importanceMap; } /** * Save the model as byte array representation. * Write these bytes to a file will give compatible format with other xgboost bindings. * * If java natively support HDFS file API, use toByteArray and write the ByteArray * * @param withStats Controls whether the split statistics are output. * @return dumped model information * @throws XGBoostError native error */ private String[] getDumpInfo(boolean withStats) throws XGBoostError { int statsFlag = 0; if (withStats) { statsFlag = 1; } String[][] modelInfos = new String[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterDumpModelEx(handle, "", statsFlag, "text", modelInfos)); return modelInfos[0]; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } /** * * @return the saved byte array. * @throws XGBoostError native error */ public byte[] toByteArray() throws XGBoostError { byte[][] bytes = new byte[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterGetModelRaw(this.handle, bytes)); return bytes[0]; } /** * Load the booster model from thread-local rabit checkpoint. * This is only used in distributed training. * @return the stored version number of the checkpoint. * @throws XGBoostError */ int loadRabitCheckpoint() throws XGBoostError { int[] out = new int[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadRabitCheckpoint(this.handle, out)); version = out[0]; return version; } /** * Save the booster model into thread-local rabit checkpoint and increment the version. * This is only used in distributed training. * @throws XGBoostError */ void saveRabitCheckpoint() throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGBoosterSaveRabitCheckpoint(this.handle)); version += 1; } /** * Internal initialization function. * @param cacheMats The cached DMatrix. * @throws XGBoostError */ private void init(DMatrix[] cacheMats) throws XGBoostError { long[] handles = null; if (cacheMats != null) { handles = dmatrixsToHandles(cacheMats); } long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGBoosterCreate(handles, out)); handle = out[0]; } /** * transfer DMatrix array to handle array (used for native functions) * * @param dmatrixs * @return handle array for input dmatrixs */ private static long[] dmatrixsToHandles(DMatrix[] dmatrixs) { long[] handles = new long[dmatrixs.length]; for (int i = 0; i < dmatrixs.length; i++) { handles[i] = dmatrixs[i].getHandle(); } return handles; } // making Booster serializable private void writeObject(java.io.ObjectOutputStream out) throws IOException { try { out.writeInt(version); out.writeObject(this.toByteArray()); } catch (XGBoostError ex) { ex.printStackTrace(); logger.error(ex.getMessage()); } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { try { this.init(null); this.version = in.readInt(); byte[] bytes = (byte[])in.readObject(); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModelFromBuffer(this.handle, bytes)); } catch (XGBoostError ex) { ex.printStackTrace(); logger.error(ex.getMessage()); } } @Override protected void finalize() throws Throwable { super.finalize(); dispose(); } public synchronized void dispose() { if (handle != 0L) { XGBoostJNI.XGBoosterFree(handle); handle = 0; } } @Override public void write(Kryo kryo, Output output) { try { byte[] serObj = this.toByteArray(); int serObjSize = serObj.length; output.writeInt(serObjSize); output.writeInt(version); output.write(serObj); } catch (XGBoostError ex) { logger.error(ex.getMessage(), ex); } } @Override public void read(Kryo kryo, Input input) { try { this.init(null); int serObjSize = input.readInt(); this.version = input.readInt(); byte[] bytes = new byte[serObjSize]; input.readBytes(bytes); XGBoostJNI.checkCall(XGBoostJNI.XGBoosterLoadModelFromBuffer(this.handle, bytes)); } catch (XGBoostError ex) { logger.error(ex.getMessage(), ex); } } }
0
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/DMatrix.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.util.Iterator; import ml.dmlc.xgboost4j.LabeledPoint; /** * DMatrix for xgboost. * * @author hzx */ public class DMatrix { protected long handle = 0; private int gpu_id = 0; private float missing = Float.NaN; /** * sparse matrix type (CSR or CSC) */ public static enum SparseType { CSR, CSC; } /** * Create DMatrix from iterator. * * @param iter The data iterator of mini batch to provide the data. * @param cacheInfo Cache path information, used for external memory setting, can be null. * @throws XGBoostError */ public DMatrix(Iterator<LabeledPoint> iter, String cacheInfo) throws XGBoostError { if (iter == null) { throw new NullPointerException("iter: null"); } // 32k as batch size int batchSize = 32 << 10; Iterator<DataBatch> batchIter = new DataBatch.BatchIterator(iter, batchSize); long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromDataIter(batchIter, cacheInfo, out)); handle = out[0]; } /** * Create DMatrix by loading libsvm file from dataPath * * @param dataPath The path to the data. * @throws XGBoostError */ public DMatrix(String dataPath) throws XGBoostError { if (dataPath == null) { throw new NullPointerException("dataPath: null"); } long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromFile(dataPath, 1, out)); handle = out[0]; } /** * Create DMatrix from Sparse matrix in CSR/CSC format. * @param headers The row index of the matrix. * @param indices The indices of presenting entries. * @param data The data content. * @param st Type of sparsity. * @throws XGBoostError */ @Deprecated public DMatrix(long[] headers, int[] indices, float[] data, DMatrix.SparseType st) throws XGBoostError { long[] out = new long[1]; if (st == SparseType.CSR) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSREx(headers, indices, data, 0, out)); } else if (st == SparseType.CSC) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSCEx(headers, indices, data, 0, out)); } else { throw new UnknownError("unknow sparsetype"); } handle = out[0]; } /** * Create DMatrix from Sparse matrix in CSR/CSC format. * @param headers The row index of the matrix. * @param indices The indices of presenting entries. * @param data The data content. * @param st Type of sparsity. * @param shapeParam when st is CSR, it specifies the column number, otherwise it is taken as * row number * @throws XGBoostError */ public DMatrix(long[] headers, int[] indices, float[] data, DMatrix.SparseType st, int shapeParam) throws XGBoostError { long[] out = new long[1]; if (st == SparseType.CSR) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSREx(headers, indices, data, shapeParam, out)); } else if (st == SparseType.CSC) { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCSCEx(headers, indices, data, shapeParam, out)); } else { throw new UnknownError("unknow sparsetype"); } handle = out[0]; } /** * create DMatrix from dense matrix * * @param data data values * @param nrow number of rows * @param ncol number of columns * @throws XGBoostError native error */ public DMatrix(float[] data, int nrow, int ncol) throws XGBoostError { long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromMat(data, nrow, ncol, 0.0f, out)); handle = out[0]; } /** * create DMatrix from dense matrix * @param data data values * @param nrow number of rows * @param ncol number of columns * @param missing the specified value to represent the missing value */ public DMatrix(float[] data, int nrow, int ncol, float missing) throws XGBoostError { long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromMat(data, nrow, ncol, missing, out)); handle = out[0]; } /** * used for DMatrix slice */ protected DMatrix(long handle) { this.handle = handle; } //START CUDF Support /** * Create DMatrix from cuDF. * * @param gdf_cols The native handles of GDF columns * @throws XGBoostError native error */ public DMatrix(long[] gdf_cols) throws XGBoostError { this(gdf_cols, 0, Float.NaN); } /** * Create DMatrix from cuDF. * * @param gdf_cols The native handles of GDF columns * @param gpu_id The gpu id to use * @throws XGBoostError native error */ public DMatrix(long[] gdf_cols, int gpu_id, float missing) throws XGBoostError { if (gdf_cols == null) { throw new NullPointerException("gdf_cols: null"); } long[] out = new long[1]; this.gpu_id = gpu_id; this.missing = missing; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixCreateFromCUDF(gdf_cols, out, gpu_id, missing)); handle = out[0]; } /** * Append CUDF to DMatrix * @param gdf_cols * @throws XGBoostError */ public void appendCUDF(long[] gdf_cols) throws XGBoostError { if (gdf_cols == null) { throw new NullPointerException("gdf_cols: null"); } XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixAppendCUDF(handle, gdf_cols, gpu_id, missing)); } /** * Set CUDF information for DMatrix. * * @param field The name of this info, such as "label" or "weight" * @param cols The native handles of GDF columns * @throws XGBoostError native error */ public void setCUDFInfo(String field, long[] cols) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetCUDFInfo(handle, field, cols, gpu_id)); } /** * Append CUDF information for DMatrix * @param field * @param cols * @throws XGBoostError */ public void appendCUDFInfo(String field, long[] cols) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixAppendCUDFInfo(handle, field, cols, gpu_id)); } // END CUDF Support /** * set label of dmatrix * * @param labels labels * @throws XGBoostError native error */ public void setLabel(float[] labels) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetFloatInfo(handle, "label", labels)); } /** * set weight of each instance * * @param weights weights * @throws XGBoostError native error */ public void setWeight(float[] weights) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetFloatInfo(handle, "weight", weights)); } /** * Set base margin (initial prediction). * * The margin must have the same number of elements as the number of * rows in this matrix. */ public void setBaseMargin(float[] baseMargin) throws XGBoostError { if (baseMargin.length != rowNum()) { throw new IllegalArgumentException(String.format( "base margin must have exactly %s elements, got %s", rowNum(), baseMargin.length)); } XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetFloatInfo(handle, "base_margin", baseMargin)); } /** * Set base margin (initial prediction). */ public void setBaseMargin(float[][] baseMargin) throws XGBoostError { setBaseMargin(flatten(baseMargin)); } /** * Set group sizes of DMatrix (used for ranking) * * @param group group size as array * @throws XGBoostError native error */ public void setGroup(int[] group) throws XGBoostError { XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSetGroup(handle, group)); } private float[] getFloatInfo(String field) throws XGBoostError { float[][] infos = new float[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixGetFloatInfo(handle, field, infos)); return infos[0]; } private int[] getIntInfo(String field) throws XGBoostError { int[][] infos = new int[1][]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixGetUIntInfo(handle, field, infos)); return infos[0]; } /** * get label values * * @return label * @throws XGBoostError native error */ public float[] getLabel() throws XGBoostError { return getFloatInfo("label"); } /** * get weight of the DMatrix * * @return weights * @throws XGBoostError native error */ public float[] getWeight() throws XGBoostError { return getFloatInfo("weight"); } /** * Get base margin of the DMatrix. */ public float[] getBaseMargin() throws XGBoostError { return getFloatInfo("base_margin"); } /** * Slice the DMatrix and return a new DMatrix that only contains `rowIndex`. * * @param rowIndex row index * @return sliced new DMatrix * @throws XGBoostError native error */ public DMatrix slice(int[] rowIndex) throws XGBoostError { long[] out = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixSliceDMatrix(handle, rowIndex, out)); long sHandle = out[0]; DMatrix sMatrix = new DMatrix(sHandle); return sMatrix; } /** * get the row number of DMatrix * * @return number of rows * @throws XGBoostError native error */ public long rowNum() throws XGBoostError { long[] rowNum = new long[1]; XGBoostJNI.checkCall(XGBoostJNI.XGDMatrixNumRow(handle, rowNum)); return rowNum[0]; } /** * save DMatrix to filePath */ public void saveBinary(String filePath) { XGBoostJNI.XGDMatrixSaveBinary(handle, filePath, 1); } /** * Get the handle */ public long getHandle() { return handle; } /** * flatten a mat to array */ private static float[] flatten(float[][] mat) { int size = 0; for (float[] array : mat) size += array.length; float[] result = new float[size]; int pos = 0; for (float[] ar : mat) { System.arraycopy(ar, 0, result, pos, ar.length); pos += ar.length; } return result; } @Override protected void finalize() { dispose(); } public synchronized void dispose() { if (handle != 0) { XGBoostJNI.XGDMatrixFree(handle); handle = 0; } } }
0
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/EnvironmentDetector.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class EnvironmentDetector { private static final Log log = LogFactory.getLog(EnvironmentDetector.class); public static Optional<String> getCudaVersion() { // firstly, try getting version from env variable Optional<String> version = Optional .ofNullable(System.getenv("RAPIDS_CUDA_VERSION")) .filter(literal -> literal.matches("([0-9][.0-9]*)")); version.ifPresent(literal -> log.info("Found CUDA version from env variable: " + literal)); // secondly, try getting version from the "nvcc" command if (!version.isPresent()) { try { version = extractPattern( runCommand("nvcc", "--version"), "Cuda compilation tools, release [.0-9]+, V([.0-9]+)"); version.ifPresent(literal -> log.info("Found CUDA version from nvcc command: " + literal)); } catch (IOException | InterruptedException e) { log.debug("Could not get CUDA version with \"nvcc --version\"", e); version = Optional.empty(); } } // thirdly, try reading version from CUDA home if (!version.isPresent()) { try { version = extractPattern( readFileContent("/usr/local/cuda/version.txt"), "CUDA Version ([.0-9]+)"); version.ifPresent(literal -> { log.info("Found CUDA version from /usr/local/cuda/version.txt: " + literal); }); } catch (IOException e) { log.debug("Could not read CUDA version from CUDA home", e); version = Optional.empty(); } } return version; } private static Optional<String> extractPattern(String content, String regex) { Matcher matcher = Pattern.compile(regex).matcher(content); return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); } private static String readFileContent(String path) throws IOException { return new String(Files.readAllBytes(Paths.get(path))); } private static String runCommand(String ...command) throws IOException, InterruptedException { Process process = Runtime.getRuntime().exec(command); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { return reader.lines().collect(Collectors.joining(System.lineSeparator())); } finally { assert process.waitFor() == 0; } } }
0
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/NativeLibLoader.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.*; import java.lang.reflect.Field; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * class to load native library * * @author hzx */ class NativeLibLoader { private static final Log logger = LogFactory.getLog(NativeLibLoader.class); private static boolean initialized = false; private static final String nativeResourcePath = "/lib/"; private static final String[] libNames = new String[]{"xgboost4j"}; static synchronized void initXGBoost() throws IOException { if (!initialized) { String cuda = getCudaFolder(); for (String libName : libNames) { try { String libraryFromJar = nativeResourcePath + cuda + System.mapLibraryName(libName); loadLibraryFromJar(libraryFromJar); } catch (IOException ioe) { logger.error("failed to load " + libName + " library from jar"); throw ioe; } } initialized = true; } } private static String getCudaFolder() { String version = EnvironmentDetector .getCudaVersion() .orElseGet(() -> { logger.info("could not get CUDA version, fall back on version 9.2"); return "9.2.0"; }); assert version.indexOf('.') + 2 <= version.length(): "cuda version format error!"; String mainVersion = version.indexOf('.') > 0 ? version.substring(0, version.indexOf('.') + 2) : version; String folder = "cuda" + mainVersion + "/"; logger.info(String.format("found folder %s for CUDA %s", folder, version)); return folder; } /** * Loads library from current JAR archive * <p/> * The file from JAR is copied into system temporary directory and then loaded. * The temporary file is deleted after exiting. * Method uses String as filename because the pathname is "abstract", not system-dependent. * <p/> * The restrictions of {@link File#createTempFile(java.lang.String, java.lang.String)} apply to * {@code path}. * * @param path The filename inside JAR as absolute path (beginning with '/'), * e.g. /package/File.ext * @throws IOException If temporary file creation or read/write operation fails * @throws IllegalArgumentException If source file (param path) does not exist * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than * three characters */ private static void loadLibraryFromJar(String path) throws IOException, IllegalArgumentException{ String temp = createTempFileFromResource(path); // Finally, load the library System.load(temp); } /** * Create a temp file that copies the resource from current JAR archive * <p/> * The file from JAR is copied into system temp file. * The temporary file is deleted after exiting. * Method uses String as filename because the pathname is "abstract", not system-dependent. * <p/> * The restrictions of {@link File#createTempFile(java.lang.String, java.lang.String)} apply to * {@code path}. * @param path Path to the resources in the jar * @return The created temp file. * @throws IOException * @throws IllegalArgumentException */ static String createTempFileFromResource(String path) throws IOException, IllegalArgumentException { // Obtain filename from path if (!path.startsWith("/")) { throw new IllegalArgumentException("The path has to be absolute (start with '/')."); } String[] parts = path.split("/"); String filename = (parts.length > 1) ? parts[parts.length - 1] : null; // Split filename to prexif and suffix (extension) String prefix = ""; String suffix = null; if (filename != null) { parts = filename.split("\\.", 2); prefix = parts[0]; suffix = (parts.length > 1) ? "." + parts[parts.length - 1] : null; // Thanks, davs! :-) } // Check if the filename is okay if (filename == null || prefix.length() < 3) { throw new IllegalArgumentException("The filename has to be at least 3 characters long."); } // Prepare temporary file File temp = File.createTempFile(prefix, suffix); temp.deleteOnExit(); if (!temp.exists()) { throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist."); } // Prepare buffer for data copying byte[] buffer = new byte[1024]; int readBytes; // Open and check input stream InputStream is = NativeLibLoader.class.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("File " + path + " was not found inside JAR."); } // Open output stream and copy data between source file in JAR and the temporary file OutputStream os = new FileOutputStream(temp); try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { // If read/write fails, close streams safely before throwing an exception os.close(); is.close(); } return temp.getAbsolutePath(); } }
0
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.11/1.0.0-Beta2/ml/dmlc/xgboost4j/java/XGBoostJNI.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * xgboost JNI functions * change 2015-7-6: *use a long[] (length=1) as container of handle to get the output DMatrix or Booster * * @author hzx */ class XGBoostJNI { private static final Log logger = LogFactory.getLog(DMatrix.class); static { try { NativeLibLoader.initXGBoost(); } catch (Exception ex) { logger.error("Failed to load native library", ex); throw new RuntimeException(ex); } } /** * Check the return code of the JNI call. * * @throws XGBoostError if the call failed. */ static void checkCall(int ret) throws XGBoostError { if (ret != 0) { throw new XGBoostError(XGBGetLastError()); } } public final static native String XGBGetLastError(); public final static native int XGDMatrixCreateFromFile(String fname, int silent, long[] out); final static native int XGDMatrixCreateFromDataIter(java.util.Iterator<DataBatch> iter, String cache_info, long[] out); public final static native int XGDMatrixCreateFromCSREx(long[] indptr, int[] indices, float[] data, int shapeParam, long[] out); public final static native int XGDMatrixCreateFromCSCEx(long[] colptr, int[] indices, float[] data, int shapeParam, long[] out); public final static native int XGDMatrixCreateFromMat(float[] data, int nrow, int ncol, float missing, long[] out); // CUDF support: Suppose gdf_columns are passed as array of native handles public final static native int XGDMatrixCreateFromCUDF(long[] cols, long[] out, int gpu_id, float missing); public final static native int XGDMatrixAppendCUDF(long handle, long[] cols, int gpu_id, float missing); public final static native int XGDMatrixSetCUDFInfo(long handle, String field, long[] cols, int gpu_id); public final static native int XGDMatrixAppendCUDFInfo(long handle, String field, long[] cols, int gpu_id); public final static native int XGDMatrixSliceDMatrix(long handle, int[] idxset, long[] out); public final static native int XGDMatrixFree(long handle); public final static native int XGDMatrixSaveBinary(long handle, String fname, int silent); public final static native int XGDMatrixSetFloatInfo(long handle, String field, float[] array); public final static native int XGDMatrixSetUIntInfo(long handle, String field, int[] array); public final static native int XGDMatrixSetGroup(long handle, int[] group); public final static native int XGDMatrixGetFloatInfo(long handle, String field, float[][] info); public final static native int XGDMatrixGetUIntInfo(long handle, String filed, int[][] info); public final static native int XGDMatrixNumRow(long handle, long[] row); public final static native int XGBoosterCreate(long[] handles, long[] out); public final static native int XGBoosterFree(long handle); public final static native int XGBoosterSetParam(long handle, String name, String value); public final static native int XGBoosterUpdateOneIter(long handle, int iter, long dtrain); public final static native int XGBoosterBoostOneIter(long handle, long dtrain, float[] grad, float[] hess); public final static native int XGBoosterEvalOneIter(long handle, int iter, long[] dmats, String[] evnames, String[] eval_info); public final static native int XGBoosterPredict(long handle, long dmat, int option_mask, int ntree_limit, float[][] predicts); public final static native int XGBoosterLoadModel(long handle, String fname); public final static native int XGBoosterSaveModel(long handle, String fname); public final static native int XGBoosterLoadModelFromBuffer(long handle, byte[] bytes); public final static native int XGBoosterGetModelRaw(long handle, byte[][] out_bytes); public final static native int XGBoosterDumpModelEx(long handle, String fmap, int with_stats, String format, String[][] out_strings); public final static native int XGBoosterDumpModelExWithFeatures( long handle, String[] feature_names, int with_stats, String format, String[][] out_strings); public final static native int XGBoosterGetAttrNames(long handle, String[][] out_strings); public final static native int XGBoosterGetAttr(long handle, String key, String[] out_string); public final static native int XGBoosterSetAttr(long handle, String key, String value); public final static native int XGBoosterLoadRabitCheckpoint(long handle, int[] out_version); public final static native int XGBoosterSaveRabitCheckpoint(long handle); // rabit functions public final static native int RabitInit(String[] args); public final static native int RabitFinalize(); public final static native int RabitTrackerPrint(String msg); public final static native int RabitGetRank(int[] out); public final static native int RabitGetWorldSize(int[] out); public final static native int RabitVersionNumber(int[] out); // Perform Allreduce operation on data in sendrecvbuf. // This JNI function does not support the callback function for data preparation yet. final static native int RabitAllreduce(ByteBuffer sendrecvbuf, int count, int enum_dtype, int enum_op); }
0
java-sources/ai/rapids/xgboost4j_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j/java/EnvironmentDetector.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class EnvironmentDetector { private static String cudaVersionFile = "/usr/local/cuda/version.txt"; private static final Log log = LogFactory.getLog(EnvironmentDetector.class); public static Optional<String> getCudaVersion() { // firstly, try getting version from env variable Optional<String> version = Optional .ofNullable(System.getenv("RAPIDS_CUDA_VERSION")) .filter(literal -> literal.matches("([0-9][.0-9]*)")); version.ifPresent(literal -> log.info("Found CUDA version from env variable: " + literal)); // secondly, try getting version from the "nvcc" command if (!version.isPresent()) { try { version = extractPattern( runCommand("nvcc", "--version"), "Cuda compilation tools, release [.0-9]+, V([.0-9]+)"); version.ifPresent(literal -> log.info("Found CUDA version from nvcc command: " + literal)); } catch (IOException | InterruptedException e) { log.debug("Could not get CUDA version with \"nvcc --version\"", e); version = Optional.empty(); } } // thirdly, try reading version from CUDA home if (!version.isPresent()) { try { version = extractPattern(readFileContent(cudaVersionFile), "CUDA Version ([.0-9]+)"); version.ifPresent(literal -> { log.info(String.format("Found CUDA version from %s: %s", cudaVersionFile, literal)); }); } catch (IOException e) { log.debug("Could not read CUDA version from CUDA home", e); version = Optional.empty(); } } return version; } private static Optional<String> extractPattern(String content, String regex) { Matcher matcher = Pattern.compile(regex).matcher(content); return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); } private static String readFileContent(String path) throws IOException { return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); } private static String runCommand(String ...command) throws IOException, InterruptedException { Process process = Runtime.getRuntime().exec(command); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { return reader.lines().collect(Collectors.joining(System.lineSeparator())); } finally { assert process.waitFor() == 0; } } }
0
java-sources/ai/rapids/xgboost4j_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j/java/Rabit.java
package ml.dmlc.xgboost4j.java; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; /** * Rabit global class for synchronization. */ public class Rabit { public enum OpType implements Serializable { MAX(0), MIN(1), SUM(2), BITWISE_OR(3); private int op; public int getOperand() { return this.op; } OpType(int op) { this.op = op; } } public enum DataType implements Serializable { CHAR(0, 1), UCHAR(1, 1), INT(2, 4), UNIT(3, 4), LONG(4, 8), ULONG(5, 8), FLOAT(6, 4), DOUBLE(7, 8), LONGLONG(8, 8), ULONGLONG(9, 8); private int enumOp; private int size; public int getEnumOp() { return this.enumOp; } public int getSize() { return this.size; } DataType(int enumOp, int size) { this.enumOp = enumOp; this.size = size; } } private static void checkCall(int ret) throws XGBoostError { if (ret != 0) { throw new XGBoostError(XGBoostJNI.XGBGetLastError()); } } /** * Initialize the rabit library on current working thread. * @param envs The additional environment variables to pass to rabit. * @throws XGBoostError */ public static void init(Map<String, String> envs) throws XGBoostError { String[] args = new String[envs.size()]; int idx = 0; for (java.util.Map.Entry<String, String> e : envs.entrySet()) { args[idx++] = e.getKey() + '=' + e.getValue(); } checkCall(XGBoostJNI.RabitInit(args)); } /** * Shutdown the rabit engine in current working thread, equals to finalize. * @throws XGBoostError */ public static void shutdown() throws XGBoostError { checkCall(XGBoostJNI.RabitFinalize()); } /** * Print the message on rabit tracker. * @param msg * @throws XGBoostError */ public static void trackerPrint(String msg) throws XGBoostError { checkCall(XGBoostJNI.RabitTrackerPrint(msg)); } /** * Get version number of current stored model in the thread. * which means how many calls to CheckPoint we made so far. * @return version Number. * @throws XGBoostError */ public static int versionNumber() throws XGBoostError { int[] out = new int[1]; checkCall(XGBoostJNI.RabitVersionNumber(out)); return out[0]; } /** * get rank of current thread. * @return the rank. * @throws XGBoostError */ public static int getRank() throws XGBoostError { int[] out = new int[1]; checkCall(XGBoostJNI.RabitGetRank(out)); return out[0]; } /** * get world size of current job. * @return the worldsize * @throws XGBoostError */ public static int getWorldSize() throws XGBoostError { int[] out = new int[1]; checkCall(XGBoostJNI.RabitGetWorldSize(out)); return out[0]; } /** * perform Allreduce on distributed float vectors using operator op. * This implementation of allReduce does not support customized prepare function callback in the * native code, as this function is meant for testing purposes only (to test the Rabit tracker.) * * @param elements local elements on distributed workers. * @param op operator used for Allreduce. * @return All-reduced float elements according to the given operator. */ public static float[] allReduce(float[] elements, OpType op) { DataType dataType = DataType.FLOAT; ByteBuffer buffer = ByteBuffer.allocateDirect(dataType.getSize() * elements.length) .order(ByteOrder.nativeOrder()); for (float el : elements) { buffer.putFloat(el); } buffer.flip(); XGBoostJNI.RabitAllreduce(buffer, elements.length, dataType.getEnumOp(), op.getOperand()); float[] results = new float[elements.length]; buffer.asFloatBuffer().get(results); return results; } /** * perform Broadcast on distributed int vectors. * * @param data local data on distributed workers. * @param root the root of process. * @return The data from broadcast worker. */ public static int[] broadcast(int[] data, int root) { if (data == null) return null; int size = DataType.INT.getSize() * data.length; ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()); // Init buffer for (int el : data) { buffer.putInt(el); } buffer.flip(); XGBoostJNI.RabitBroadcast(buffer, size, root); int[] results = new int[data.length]; buffer.asIntBuffer().get(results); return results; } }
0
java-sources/ai/rapids/xgboost4j_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j
java-sources/ai/rapids/xgboost4j_2.x/1.0.0-Beta5/ml/dmlc/xgboost4j/java/XGBoostJNI.java
/* Copyright (c) 2014 by Contributors Licensed 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 ml.dmlc.xgboost4j.java; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * xgboost JNI functions * change 2015-7-6: *use a long[] (length=1) as container of handle to get the output DMatrix or Booster * * @author hzx */ class XGBoostJNI { private static final Log logger = LogFactory.getLog(DMatrix.class); static { try { NativeLibLoader.initXGBoost(); } catch (Exception ex) { logger.error("Failed to load native library", ex); throw new RuntimeException(ex); } } /** * Check the return code of the JNI call. * * @throws XGBoostError if the call failed. */ static void checkCall(int ret) throws XGBoostError { if (ret != 0) { throw new XGBoostError(XGBGetLastError()); } } public final static native String XGBGetLastError(); public final static native int XGDMatrixCreateFromFile(String fname, int silent, long[] out); final static native int XGDMatrixCreateFromDataIter(java.util.Iterator<DataBatch> iter, String cache_info, long[] out); public final static native int XGDMatrixCreateFromCSREx(long[] indptr, int[] indices, float[] data, int shapeParam, long[] out); public final static native int XGDMatrixCreateFromCSCEx(long[] colptr, int[] indices, float[] data, int shapeParam, long[] out); public final static native int XGDMatrixCreateFromMat(float[] data, int nrow, int ncol, float missing, long[] out); // CUDF support: Suppose gdf_columns are passed as array of native handles public final static native int XGDMatrixCreateFromCUDF(long[] cols, long[] out, int gpu_id, float missing); public final static native int XGDMatrixAppendCUDF(long handle, long[] cols, int gpu_id, float missing); public final static native int XGDMatrixSetCUDFInfo(long handle, String field, long[] cols, int gpu_id); public final static native int XGDMatrixAppendCUDFInfo(long handle, String field, long[] cols, int gpu_id); public final static native int XGDMatrixSliceDMatrix(long handle, int[] idxset, long[] out); public final static native int XGDMatrixFree(long handle); public final static native int XGDMatrixSaveBinary(long handle, String fname, int silent); public final static native int XGDMatrixSetFloatInfo(long handle, String field, float[] array); public final static native int XGDMatrixSetUIntInfo(long handle, String field, int[] array); public final static native int XGDMatrixSetGroup(long handle, int[] group); public final static native int XGDMatrixGetFloatInfo(long handle, String field, float[][] info); public final static native int XGDMatrixGetUIntInfo(long handle, String filed, int[][] info); public final static native int XGDMatrixNumRow(long handle, long[] row); public final static native int XGBoosterCreate(long[] handles, long[] out); public final static native int XGBoosterFree(long handle); public final static native int XGBoosterSetParam(long handle, String name, String value); public final static native int XGBoosterUpdateOneIter(long handle, int iter, long dtrain); public final static native int XGBoosterBoostOneIter(long handle, long dtrain, float[] grad, float[] hess); public final static native int XGBoosterEvalOneIter(long handle, int iter, long[] dmats, String[] evnames, String[] eval_info); public final static native int XGBoosterPredict(long handle, long dmat, int option_mask, int ntree_limit, float[][] predicts); public final static native int XGBoosterLoadModel(long handle, String fname); public final static native int XGBoosterSaveModel(long handle, String fname); public final static native int XGBoosterLoadModelFromBuffer(long handle, byte[] bytes); public final static native int XGBoosterGetModelRaw(long handle, byte[][] out_bytes); public final static native int XGBoosterDumpModelEx(long handle, String fmap, int with_stats, String format, String[][] out_strings); public final static native int XGBoosterDumpModelExWithFeatures( long handle, String[] feature_names, int with_stats, String format, String[][] out_strings); public final static native int XGBoosterGetAttrNames(long handle, String[][] out_strings); public final static native int XGBoosterGetAttr(long handle, String key, String[] out_string); public final static native int XGBoosterSetAttr(long handle, String key, String value); public final static native int XGBoosterLoadRabitCheckpoint(long handle, int[] out_version); public final static native int XGBoosterSaveRabitCheckpoint(long handle); // rabit functions public final static native int RabitInit(String[] args); public final static native int RabitFinalize(); public final static native int RabitTrackerPrint(String msg); public final static native int RabitGetRank(int[] out); public final static native int RabitGetWorldSize(int[] out); public final static native int RabitVersionNumber(int[] out); // Perform Allreduce operation on data in sendrecvbuf. // This JNI function does not support the callback function for data preparation yet. final static native int RabitAllreduce(ByteBuffer sendrecvbuf, int count, int enum_dtype, int enum_op); // Perform Broadcast operation on data in sendrecvbuf. final static native int RabitBroadcast(ByteBuffer sendrecvbuf, long size, int root); }
0
java-sources/ai/realengine/realengine/1.0.0/ai
java-sources/ai/realengine/realengine/1.0.0/ai/realengine/RealEngineAIClient.java
package ai.realengine; import ai.realengine.dto.RealEngineAIResponse; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.Call; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; /** * A client for the RealEngine AI service. */ public class RealEngineAIClient { private static final TypeReference<RealEngineAIResponse<String>> STRING_RESPONSE_TYPE = new TypeReference<>() { }; private static final int HTTP_TOO_MANY_REQUESTS = 429; private static final int HTTP_ACCEPTED = 202; private static final int SERVER_ERROR = 500; private static final long DEFAULT_WAIT_MS = 1000; private static final long MAX_BASE_WAIT_MS = TimeUnit.MINUTES.toMillis(1); private static final String LOCATION_HEADER = "Location"; private static final String RETRY_AFTER_HEADER = "X-Retry-After"; private final OkHttpClient httpClient; private final HttpUrl rootUrl; private final ObjectMapper mapper; private final ScheduledExecutorService executorService; private final String token; private final int maxRetries; /** * Create a new client. * * @param httpClient the http client to use * @param rootUrl the root url of the service * @param mapper the object mapper to use * @param executorService the executor service to use * @param token the token to use * @param maxRetries the maximum number of retries to perform */ public RealEngineAIClient(OkHttpClient httpClient, String rootUrl, ObjectMapper mapper, ScheduledExecutorService executorService, String token, int maxRetries) { if (httpClient == null) { throw new IllegalArgumentException("httpClient must not be null"); } if (rootUrl == null || rootUrl.isEmpty()) { throw new IllegalArgumentException("rootUrl must not be null or empty"); } if (mapper == null) { throw new IllegalArgumentException("mapper must not be null"); } if (executorService == null) { throw new IllegalArgumentException("executorService must not be null"); } if (token == null || token.isEmpty()) { throw new IllegalArgumentException("token must not be null or empty"); } if (maxRetries < 0) { throw new IllegalArgumentException("maxRetries must be >= 0"); } this.maxRetries = maxRetries; HttpUrl parsedRootUrl = HttpUrl.parse(rootUrl); if (parsedRootUrl == null) { throw new IllegalArgumentException("The rootUrl provided is not valid"); } this.httpClient = httpClient; this.rootUrl = parsedRootUrl; this.mapper = mapper; this.executorService = executorService; this.token = token; } public static RealEngineAIClientBuilder newBuilder() { return new RealEngineAIClientBuilder(); } /** * Get the caption for an image at the given url. * * @param url the url of the image to caption * @return a future that will be completed with the caption, or an exception if the captioning failed */ public CompletableFuture<String> getCaption(String url) { var requestUrl = rootUrl.newBuilder() .addPathSegment("caption") .addQueryParameter("url", url) .build(); var request = buildRequest(requestUrl); var callback = new Callback<>(STRING_RESPONSE_TYPE); return call(request, callback); } private <T> void retryLater(Callback<T> callback, Response response, int retryCount) { var baseWaitTime = (long) (DEFAULT_WAIT_MS * Math.pow(2, retryCount)); var jitter = ThreadLocalRandom.current().nextDouble(0.5, 1.5); var retryAfter = (long) (Math.min(MAX_BASE_WAIT_MS, baseWaitTime) * jitter); var future = executorService.schedule( () -> call(response.request(), callback), retryAfter, TimeUnit.MILLISECONDS); callback.getResult().exceptionally(th -> { future.cancel(true); return null; }); } private <T> void getTaskResult(Callback<T> callback, Response response) { var retryAfter = getRetryAfterMs(response); var location = getLocation(response); if (location == null) { callback.getResult() .completeExceptionally(new RealEngineAIException("Location header is missing", response.code(), response.request() .url() .encodedPath())); return; } var future = executorService.schedule( () -> call(buildRequest(location), callback), retryAfter, TimeUnit.MILLISECONDS); // If the future will be cancelled, cancel the future call callback.getResult().exceptionally(th -> { future.cancel(true); return null; }); } private HttpUrl getLocation(Response response) { var location = response.header(LOCATION_HEADER); if (location == null) { return null; } if (location.startsWith("http")) { return HttpUrl.parse(location); } return rootUrl.resolve(location); } private long getRetryAfterMs(Response response) { var retryHeader = response.header(RETRY_AFTER_HEADER); if (retryHeader == null) { return DEFAULT_WAIT_MS; } try { var seconds = Double.parseDouble(retryHeader); return (long) (seconds * 1000); } catch (NumberFormatException e) { return DEFAULT_WAIT_MS; } } private Request buildRequest(HttpUrl url) { return new Request.Builder() .url(url) .addHeader("Authorization", "Bearer " + token) .build(); } private <T> CompletableFuture<T> call(Request request, Callback<T> callback) { var call = httpClient.newCall(request); // If the future will be cancelled, cancel the call callback.getResult().exceptionally(th -> { call.cancel(); return null; }); call.enqueue(callback); return callback.getResult(); } private class Callback<T> implements okhttp3.Callback { final CompletableFuture<T> result; final TypeReference<RealEngineAIResponse<T>> responseType; volatile int retryCount = 0; private Callback(TypeReference<RealEngineAIResponse<T>> responseType) { this.result = new CompletableFuture<>(); this.responseType = responseType; } public CompletableFuture<T> getResult() { return result; } @Override public void onResponse(Call call, Response response) { try (response) { var statusCode = response.code(); var path = response.request() .url() .encodedPath(); if (statusCode == HTTP_TOO_MANY_REQUESTS || statusCode >= SERVER_ERROR) { if (retryCount >= maxRetries) { throw new RealEngineAIException("Too many retries", statusCode, path); } // It's ok to increment the retry count without additional synchronization // because there are no concurrent requests // noinspection NonAtomicOperationOnVolatileField retryCount++; retryLater(this, response, retryCount); return; } retryCount = 0; if (statusCode == HTTP_ACCEPTED) { getTaskResult(this, response); return; } var apiResponse = read(response); if (!apiResponse.isSuccess()) { var error = apiResponse.getError(); if (error == null) { throw new RealEngineAIException("The response is not successful but the error is null", statusCode, path); } throw new RealEngineAIException(error, statusCode, path); } result.complete(apiResponse.getData()); } catch (Exception e) { result.completeExceptionally(e); } } @Override public void onFailure(Call call, IOException e) { result.completeExceptionally(e); } private RealEngineAIResponse<T> read(Response response) throws IOException { var body = response.body(); if (body == null) { var path = response.request() .url() .encodedPath(); throw new RealEngineAIException("The response body is null", response.code(), path); } return mapper.readValue( body.byteStream(), responseType); } } }
0
java-sources/ai/realengine/realengine/1.0.0/ai
java-sources/ai/realengine/realengine/1.0.0/ai/realengine/RealEngineAIClientBuilder.java
package ai.realengine; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; import java.time.Duration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class RealEngineAIClientBuilder { private String token; private Duration connectTimeout = Duration.ofMillis(500); private Duration readTimeout = Duration.ofSeconds(2); private Duration writeTimeout = Duration.ofSeconds(2); private int maxIdleConnections = 5; private int maxConcurrentRequests = 5; private Duration keepAliveDuration = Duration.ofMinutes(5); private String rootUrl = "https://api.realengine.ai"; private ObjectMapper objectMapper; private ScheduledExecutorService executorService; private int maxRetries = 5; /** * Set the authentication token to use. * * @param token the token to use */ public RealEngineAIClientBuilder setToken(String token) { if (token == null || token.isBlank()) { throw new IllegalArgumentException("Token must not be null or blank"); } this.token = token; return this; } /** * Set the connect timeout. * The connect timeout is the timeout for establishing a TCP connection. * The default value is 500ms. */ public RealEngineAIClientBuilder setConnectTimeout(Duration connectTimeout) { if (connectTimeout.toMillis() < 0) { throw new IllegalArgumentException("Connect timeout must not be negative"); } this.connectTimeout = connectTimeout; return this; } /** * Set the read timeout. * The read timeout is the timeout for reading data from the server. * The default value is 2s. */ public RealEngineAIClientBuilder setReadTimeout(Duration readTimeout) { if (readTimeout.toMillis() < 0) { throw new IllegalArgumentException("Read timeout must not be negative"); } this.readTimeout = readTimeout; return this; } /** * Set the write timeout. * The write timeout is the timeout for writing data to the server. * The default value is 2s. */ public RealEngineAIClientBuilder setWriteTimeout(Duration writeTimeout) { if (writeTimeout.toMillis() < 0) { throw new IllegalArgumentException("Write timeout must not be negative"); } this.writeTimeout = writeTimeout; return this; } /** * Set the maximum number of idle connections. * The default value is 5. */ public RealEngineAIClientBuilder setMaxIdleConnections(int maxIdleConnections) { if (maxIdleConnections < 0) { throw new IllegalArgumentException("Max idle connections must not be negative"); } this.maxIdleConnections = maxIdleConnections; return this; } /** * Set the maximum number of concurrent requests. * The default value is 5. */ public RealEngineAIClientBuilder setMaxConcurrentRequests(int maxConcurrentRequests) { this.maxConcurrentRequests = maxConcurrentRequests; return this; } /** * Set the keep alive duration. * The keep alive duration is the duration after which idle connections are closed. * The default value is 5 minutes. */ public RealEngineAIClientBuilder setKeepAliveDuration(Duration keepAliveDuration) { if (keepAliveDuration.toMillis() < 0) { throw new IllegalArgumentException("Keep alive duration must not be negative"); } this.keepAliveDuration = keepAliveDuration; return this; } /** * Set the root URL. * The default value is <a href="https://api.realengine.ai">https://api.realengine.ai</a> */ public RealEngineAIClientBuilder setRootUrl(String rootUrl) { if (rootUrl == null || rootUrl.isBlank()) { throw new IllegalArgumentException("Root URL must not be null or blank"); } this.rootUrl = rootUrl; return this; } /** * Set the object mapper. */ public RealEngineAIClientBuilder setObjectMapper(ObjectMapper objectMapper) { if (objectMapper == null) { throw new IllegalArgumentException("Object mapper must not be null"); } this.objectMapper = objectMapper; return this; } /** * Set the executor service. * The executor service is used for scheduling the polling of the task status. */ public RealEngineAIClientBuilder setExecutorService(ScheduledExecutorService executorService) { if (executorService == null) { throw new IllegalArgumentException("Executor service must not be null"); } this.executorService = executorService; return this; } /** * Set the maximum number of retries. * The default value is 5. */ public RealEngineAIClientBuilder setMaxRetries(int maxRetries) { if (maxRetries < 0) { throw new IllegalArgumentException("Max retries must not be negative"); } this.maxRetries = maxRetries; return this; } public RealEngineAIClient build() { if (token == null || token.isBlank()) { throw new IllegalStateException("Token must be set"); } var dispatcher = new okhttp3.Dispatcher(); dispatcher.setMaxRequests(maxConcurrentRequests); dispatcher.setMaxRequestsPerHost(maxConcurrentRequests); var httpClient = new OkHttpClient.Builder() .dispatcher(dispatcher) .connectTimeout(connectTimeout) .readTimeout(readTimeout) .writeTimeout(writeTimeout) .connectionPool(new ConnectionPool( maxIdleConnections, keepAliveDuration.toMillis(), TimeUnit.MILLISECONDS)) .build(); if (objectMapper == null) { objectMapper = new ObjectMapper(); } if (executorService == null) { executorService = Executors.newSingleThreadScheduledExecutor(); } return new RealEngineAIClient(httpClient, rootUrl, objectMapper, executorService, token, maxRetries); } }
0
java-sources/ai/realengine/realengine/1.0.0/ai
java-sources/ai/realengine/realengine/1.0.0/ai/realengine/RealEngineAIException.java
package ai.realengine; import ai.realengine.dto.ErrorDTO; public class RealEngineAIException extends RuntimeException { /** * Unique error identifier, useful for support purposes */ private final String errorId; /** * Error message */ private final String errorMessage; /** * HTTP status code of the errored response */ private final int httpStatus; /** * Path of the request that caused the error */ private final String path; public RealEngineAIException(String message, int httpStatus, String path) { super(message + " http status: " + httpStatus + ", path: " + path); this.errorId = ""; this.errorMessage = message; this.httpStatus = httpStatus; this.path = path; } public RealEngineAIException(ErrorDTO error, int httpStatus, String path) { super("Error id: " + error.getId() + ", message: " + error.getMsg() + ", http status: " + httpStatus + ", path: " + path); this.errorId = error.getId(); this.errorMessage = error.getMsg(); this.httpStatus = httpStatus; this.path = path; } public String getErrorId() { return errorId; } public String getErrorMessage() { return errorMessage; } public int getHttpStatus() { return httpStatus; } public String getPath() { return path; } }
0
java-sources/ai/realengine/realengine/1.0.0/ai/realengine
java-sources/ai/realengine/realengine/1.0.0/ai/realengine/dto/ErrorDTO.java
package ai.realengine.dto; public class ErrorDTO { private String id; private String msg; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return "Error{" + "id='" + id + '\'' + ", msg='" + msg + '\'' + '}'; } }
0
java-sources/ai/realengine/realengine/1.0.0/ai/realengine
java-sources/ai/realengine/realengine/1.0.0/ai/realengine/dto/RealEngineAIResponse.java
package ai.realengine.dto; public class RealEngineAIResponse<T> { private boolean success; private T data; private ErrorDTO error; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public T getData() { return data; } public void setData(T data) { this.data = data; } public ErrorDTO getError() { return error; } public void setError(ErrorDTO error) { this.error = error; } @Override public String toString() { return "RealEngineAIResponse{" + "success=" + success + ", data=" + data + ", error=" + error + '}'; } }
0
java-sources/ai/retack/retack-java-sdk/1.0.0/ai
java-sources/ai/retack/retack-java-sdk/1.0.0/ai/retack/ErrorLoggingHandler.java
package ai.retack; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class ErrorLoggingHandler extends Handler { private final String envKey; public ErrorLoggingHandler(String envKey) { this.envKey = envKey; } @Override public void publish(LogRecord record) { if (record.getLevel().intValue() >= Level.SEVERE.intValue() && record.getThrown() != null) { String errorTitle = record.getMessage(); Throwable throwable = record.getThrown(); UserContext userContext = new UserContext("defaultUser", "defaultSession"); String stackTrace = getStackTraceAsString(throwable); ErrorPayload payload = new ErrorPayload(errorTitle, stackTrace, userContext); sendError(payload); } } private String getStackTraceAsString(Throwable throwable) { StringBuilder result = new StringBuilder(); for (StackTraceElement element : throwable.getStackTrace()) { result.append(element.toString()).append("\n"); } return result.toString(); } private void sendError(ErrorPayload payload) { try { URL url = new URL("https://api.retack.ai/observe/error-log/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("ENV-KEY", envKey); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write(payload.toJson().getBytes()); os.flush(); os.close(); int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Failed to send error: HTTP error code : " + responseCode); } } catch (Exception e) { e.printStackTrace(); } } @Override public void flush() { // No need to implement } @Override public void close() throws SecurityException { // No need to implement } }
0
java-sources/ai/retack/retack-java-sdk/1.0.0/ai
java-sources/ai/retack/retack-java-sdk/1.0.0/ai/retack/ErrorPayload.java
package ai.retack; public class ErrorPayload { private final String title; private final String stackTrace; private final UserContext userContext; public ErrorPayload(String title, String stackTrace, UserContext userContext) { this.title = title; this.stackTrace = stackTrace; this.userContext = userContext; } public String toJson() { return "{" + "\"title\":\"" + escapeJson(title) + "\"," + "\"stack_trace\":\"" + escapeJson(stackTrace) + "\"," + "\"user_context\":{" + "\"userId\":\"" + escapeJson(userContext.getUserId()) + "\"," + "\"sessionId\":\"" + escapeJson(userContext.getSessionId()) + "\"" + "}" + "}"; } private String escapeJson(String value) { if (value == null) { return ""; } return value.replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r"); } }
0
java-sources/ai/retack/retack-java-sdk/1.0.0/ai
java-sources/ai/retack/retack-java-sdk/1.0.0/ai/retack/UserContext.java
package ai.retack; public class UserContext { private final String userId; private final String sessionId; public UserContext(String userId, String sessionId) { this.userId = userId; this.sessionId = sessionId; } public String getUserId() { return userId; } public String getSessionId() { return sessionId; } }
0
java-sources/ai/rev/revai-java-sdk/2.5.0/ai/rev
java-sources/ai/rev/revai-java-sdk/2.5.0/ai/rev/exceptions/AuthorizationException.java
package ai.rev.exceptions; import org.json.JSONObject; /** * The AuthorizationException happens when an invalid token access is used to query any * endpoint. */ public class AuthorizationException extends RevAiApiException { public AuthorizationException(JSONObject errorResponse) { super("Authorization Exception", errorResponse, 401); } }
0
java-sources/ai/rev/revai-java-sdk/2.5.0/ai/rev
java-sources/ai/rev/revai-java-sdk/2.5.0/ai/rev/exceptions/ForbiddenRequestException.java
package ai.rev.exceptions; import org.json.JSONObject; /** * The ForbiddenRequestException happens when the request contains parameters that do not pass validation * or the request is not allowed for the user */ public class ForbiddenRequestException extends RevAiApiException { public ForbiddenRequestException(JSONObject errorResponse) { super("Forbidden Request Exception", errorResponse, 403); } }