Skip to main content

Text Feature Extraction

Original integration-test class: FeatureExtraction in 4.1.1.ML.FeatureExtraction.Text.cs. This is a direct SDK operation, not a PipelineClient workflow.

4 recorded job or prediction directories matched by module and scenario path. 2 have completed/success status and a saved result. These are API execution records, not confirmed xUnit pass counts. Partition jobs are counted separately.

Prerequisites​

Use the original SDK test project, its xUnit dependencies, helper classes and any upstream cache entries referenced in the source. See configuration.

Required environment variable names referenced in the source: PARALLELMODEL_MODEL_ID, PARALLELMODEL_COMPUTE_SIZE, PARALLELMODEL_ENCRYPTION_KEY_1, PARALLELMODEL_REGION, PARALLELMODEL_CLIENT_ID, PARALLELMODEL_CLIENT_SECRET.

SDK calls used​

ClientMethods in the source
FeatureExtractionClientDownloadBytesAsync, ExtractAsync, LogAsync, ResultAsync, SendAsync, StatusAsync

Execution workflow​

  1. Initialise the client and output paths.
  2. Resolve the imputed training blob from cache metadata.
  3. Save the typed request, submit it once and save the send response.
  4. Save each status response until the job reaches a terminal state.
  5. Retrieve logs and stop retrying after the first successful response.
  6. Retrieve and save the original result.
  7. Extract and download the declared artifacts in order.
  8. Publish the grouped cache entry after all artifact downloads succeed.

Recorded operation examples​

OperationRecorded jobsResult recorded
CountVectorizer11
HashingVectorizer11
TfidfTransformer10
TfidfVectorizer10

Run the original integration test​

This filter selects the class and its parameterized scenarios; it does not select only a single recorded job.

dotnet test --filter "FullyQualifiedName~ParallelModel.Sdk.UnitTests.FeatureExtraction.Run"

Full C# source​

The supplied test logic is preserved. The method signature is:

Run(string datasetName, string selectionName, string impute, string name)
using ParallelModel.Sdk.Authentication;
using ParallelModel.Sdk.Exceptions;
using ParallelModel.Sdk.ML.FeatureExtraction.Models.Requests;
using ParallelModel.Sdk.UnitTests.Attributes;
using ParallelModel.Sdk.UnitTests.Cache;
using ParallelModel.Sdk.UnitTests.Helpers;
using System.Text.Json;

namespace ParallelModel.Sdk.UnitTests
{
[Collection("FeatureExtraction")]
public sealed class FeatureExtraction
{
private static readonly SharedSendThrottle sendThrottle = new(TimeSpan.FromSeconds(12));
private static readonly TimeSpan ApiTimeout = TimeSpan.FromSeconds(300);
private static readonly string[] Algorithms =
["CountVectorizer", "HashingVectorizer", "TfidfTransformer", "TfidfVectorizer"];

public static TheoryData<string, string, string, string> FeatureExtractionRequests =>
ImputeAttribute.GetRequests(typeof(FeatureExtraction), nameof(Run), FeatureExtractionAlgorithmsFor);

private static string[] FeatureExtractionAlgorithmsFor(string datasetName) => Algorithms;

[Theory]
[MemberData(nameof(FeatureExtractionRequests))]
[Trait("Category", "Integration")]
[Impute("Fetch20Newsgroups", "TrainTestSplit", "SimpleImputer")]
public async Task Run(string datasetName, string selectionName, string impute, string name)
{
// 1. Initialise the client and output paths.
SharedEnvironmentHelper.LoadEnvIfAvailable();
CancellationToken cancellationToken = TestContext.Current.CancellationToken;
Guid modelId = SharedEnvironmentHelper.RequiredGuid("PARALLELMODEL_MODEL_ID");
string computeSize = SharedEnvironmentHelper.Required("PARALLELMODEL_COMPUTE_SIZE");
string encryptionKey = SharedEnvironmentHelper.Required("PARALLELMODEL_ENCRYPTION_KEY_1");
TimeSpan pollingInterval = TimeSpan.FromSeconds(30);
ParallelModelClient parallelModelClient = new(new DefaultParallelModelAuthenticationOptions
{
Region = SharedEnvironmentHelper.Required("PARALLELMODEL_REGION"),
ClientId = SharedEnvironmentHelper.Required("PARALLELMODEL_CLIENT_ID"),
ClientSecret = SharedEnvironmentHelper.Required("PARALLELMODEL_CLIENT_SECRET"),
Timeout = TimeSpan.FromSeconds(90)
});

string outputRoot = SharedEnvironmentHelper.OutputDirectory;
string runId = Guid.NewGuid().ToString("N");
string outputDirectory = Path.Combine(outputRoot, "featureextraction.text", datasetName, name, runId);
string cacheDirectory = SharedEnvironmentHelper.CacheDirectory;
Directory.CreateDirectory(Path.Combine(outputDirectory, "artifacts"));
int responseFileNumber = 0;

// 2. Resolve the imputed training blob from cache metadata.
MLDecompositionHelper.ImputedArtifact source = await MLDecompositionHelper.LoadImputedArtifactAsync(
datasetName, selectionName, impute, "train", cacheDirectory, ImputeCacheEntry.TextFileName,
cancellationToken);
const string textColumn = "text";
const string fileFormat = "csv";

// 3. Save the typed request, submit it once and save the send response.
await sendThrottle.WaitForSendSlotAsync(cancellationToken);
string requestFileName = $"{++responseFileNumber:000}-request.json";
JsonElement sendResponse = await RequestAsync("send", () => SendFeatureExtractionAsync(
datasetName, name, source.BlobId, fileFormat, textColumn,
parallelModelClient, modelId, computeSize, encryptionKey,
outputDirectory, requestFileName, cancellationToken));
Guid jobId = GetResponseProperty(sendResponse, "jobId", "job_id").GetGuid();

// 4. Save each status response until the job reaches a terminal state.
DateTimeOffset statusDeadline = DateTimeOffset.UtcNow.AddMinutes(10);
for (int attempt = 1; ; attempt++)
{
object statusResponse = await RequestAsync($"status-{attempt:000}", async () =>
await parallelModelClient.FeatureExtractionClient.StatusAsync(
modelId, jobId, computeSize, ApiTimeout, cancellationToken));
JsonElement statusJson = JsonSerializer.SerializeToElement(statusResponse, statusResponse.GetType());
JsonElement statusValue = GetResponseProperty(statusJson, "status");
string? jobStatus = statusValue.ValueKind == JsonValueKind.String ? statusValue.GetString() : null;
switch (jobStatus?.ToLowerInvariant())
{
case "success" or "succeeded" or "completed":
break;
case null or "error" or "failed" or "cancelled" or "canceled" or "deadletter"
or "dead-lettered" or "deadlettered" or "dead_letter" or "dead-letter":
try
{
await RequestAsync("logs", GetLogsAsync);
}
catch (Exception) when (!cancellationToken.IsCancellationRequested)
{
// RequestAsync has already attempted to save the log error.
}

throw new InvalidOperationException(
$"Job {jobId} returned a status error or ended with status '{jobStatus}'. See saved responses.");
default:
if (DateTimeOffset.UtcNow >= statusDeadline)
throw new TimeoutException($"Status polling expired for job {jobId}.");
await Task.Delay(pollingInterval, cancellationToken);
continue;
}

break;
}

// 5. Retrieve logs and stop retrying after the first successful response.
try
{
await RequestAsync("logs", GetLogsAsync, maximumAttempts: 10);
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested && IsTransient(exception))
{
// The result can still be retrieved if logs are temporarily unavailable.
}

// 6. Retrieve and save the original result.
object resultResponse = await RequestAsync("result", async () =>
await parallelModelClient.FeatureExtractionClient.ResultAsync(
modelId, jobId, computeSize, encryptionKey, timeout: ApiTimeout,
cancellationToken: cancellationToken), maximumAttempts: int.MaxValue,
retryDeadline: DateTimeOffset.UtcNow.AddMinutes(5));

// 7. Extract and download the declared artifacts in order.
JsonElement resultJson = JsonSerializer.SerializeToElement(resultResponse, resultResponse.GetType());
JsonElement artifactFiles = GetResponseProperty(resultJson, "artifactFiles", "artifact_files");
string[] artifactPaths = artifactFiles.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null
? ["result.json"]
: artifactFiles.Deserialize<string[]>()!;
List<FeatureExtractionArtifactCacheEntry> artifacts = new();
for (int index = 0; index < artifactPaths.Length; index++)
{
string artifactPath = artifactPaths[index];
object extractResponse = await RequestAsync($"extract-{index + 1:000}", async () =>
await parallelModelClient.FeatureExtractionClient.ExtractAsync(
modelId, jobId, artifactPath, computeSize, encryptionKey, encryptionKey,
timeout: ApiTimeout, cancellationToken: cancellationToken), maximumAttempts: 5);
JsonElement extractJson = JsonSerializer.SerializeToElement(extractResponse, extractResponse.GetType());
Guid blobId = GetResponseProperty(extractJson, "uploadedBlobId", "uploaded_blob_id").GetGuid();
byte[] artifactBytes = await RequestAsync($"download-{index + 1:000}", async () =>
await parallelModelClient.FeatureExtractionClient.DownloadBytesAsync(
modelId, jobId, blobId, computeSize, encryptionKey, ApiTimeout, cancellationToken),
maximumAttempts: 5, saveJson: false);
await SharedArtifactHelper.SaveAsync(
outputDirectory, index + 1, artifactPath, artifactBytes, cancellationToken);
artifacts.Add(new FeatureExtractionArtifactCacheEntry(artifactPath, blobId));
}

// 8. Publish the grouped cache entry after all artifact downloads succeed.
FeatureExtractionCacheEntry cacheEntry = new(
datasetName, textColumn, name, modelId, source.BlobId, jobId, runId, artifacts);
await SharedCacheHelper.UpdateAsync<List<FeatureExtractionCacheEntry>>(
cacheDirectory, FeatureExtractionCacheEntry.FileName, existingEntries =>
{
List<FeatureExtractionCacheEntry> entries = existingEntries ?? new();
entries.RemoveAll(entry => entry.ModelId == modelId && entry.Dataset == datasetName
&& entry.TextColumn == textColumn && entry.Algorithm == name);
entries.Add(cacheEntry);
return entries;
}, cancellationToken);

async Task<object> GetLogsAsync() => await parallelModelClient.FeatureExtractionClient.LogAsync(
modelId, jobId, computeSize, TimeSpan.FromSeconds(30), cancellationToken);

// Request execution stays local to Run. Storage helpers know nothing about jobs.
async Task<T> RequestAsync<T>(string stage, Func<Task<T>> request,
int maximumAttempts = 1, bool saveJson = true, DateTimeOffset? retryDeadline = null)
{
for (int attempt = 1; ; attempt++)
{
T response;
try
{
response = await request();
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
{
await SharedResponseHelper.SaveExceptionAsync(outputDirectory,
$"{++responseFileNumber:000}-{stage}-attempt-{attempt:000}-error.txt",
exception, cancellationToken);
if (attempt >= maximumAttempts || !IsTransient(exception) ||
(retryDeadline.HasValue && DateTimeOffset.UtcNow >= retryDeadline.Value))
throw;
await Task.Delay(pollingInterval, cancellationToken);
continue;
}

if (saveJson)
await SharedResponseHelper.SaveAsync(outputDirectory,
$"{++responseFileNumber:000}-{stage}.json", response, cancellationToken);
return response;
}
}

static bool IsTransient(Exception exception) => exception is ParallelModelApiException apiException
? (int)apiException.StatusCode is 404 or 408 or 409 or 429 or >= 500
: exception is System.Net.Http.HttpRequestException or TimeoutException or TaskCanceledException;
}

private static async Task<JsonElement> SendFeatureExtractionAsync(
string datasetName, string name, Guid inputBlobId, string fileFormat, string textColumn,
ParallelModelClient parallelModelClient, Guid modelId, string computeSize, string encryptionKey,
string outputDirectory, string requestFileName, CancellationToken cancellationToken)
{
ParallelModelFeatureExtractionOutputModel output = new()
{
Name = $"{datasetName}-{name}.zip",
Description = "Feature extraction integration test using cached imputed training text",
RecordType = "Generic",
AccessTier = "Hot",
Tags = ["text", "feature-extraction", datasetName, name]
};

async Task<JsonElement> SendTypedAsync<TRequest>(TRequest request)
where TRequest : class, IParallelModelFeatureExtractionSendRequest
{
await SharedResponseHelper.SaveAsync(outputDirectory, requestFileName, request, cancellationToken);
return await parallelModelClient.FeatureExtractionClient.SendAsync(
modelId, request, computeSize, encryptionKey, encryptionKey, ApiTimeout, cancellationToken);
}

return name switch
{
"CountVectorizer" => await SendTypedAsync(new CountVectorizerJobSendRequestModel
{
Input = new CountVectorizerJobSendRequestModel.CountVectorizerInputModel
{
InputBlobId = inputBlobId,
ClassifierType = "CountVectorizer",
ClassifierParams = new CountVectorizerJobSendRequestModel.CountVectorizerClassifierParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
Lowercase = true
},
TextColumn = textColumn,
FileFormat = fileFormat,
Evaluation = new CountVectorizerJobSendRequestModel.CountVectorizerEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = true
},
Output = output,
RequestTimeoutSeconds = 300
}),
"HashingVectorizer" => await SendTypedAsync(new HashingVectorizerJobSendRequestModel
{
Input = new HashingVectorizerJobSendRequestModel.HashingVectorizerInputModel
{
InputBlobId = inputBlobId,
ClassifierType = "HashingVectorizer",
ClassifierParams = new HashingVectorizerJobSendRequestModel.HashingVectorizerClassifierParamsModel
{
NFeatures = 64,
AlternateSign = false,
Norm = "l2"
},
TextColumn = textColumn,
FileFormat = fileFormat,
Evaluation = new HashingVectorizerJobSendRequestModel.HashingVectorizerEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = true
},
Output = output,
RequestTimeoutSeconds = 300
}),
"TfidfTransformer" => await SendTypedAsync(new TfidfTransformerJobSendRequestModel
{
Input = new TfidfTransformerJobSendRequestModel.TfidfTransformerInputModel
{
InputBlobId = inputBlobId,
ClassifierType = "TfidfTransformer",
ClassifierParams = new TfidfTransformerJobSendRequestModel.TfidfTransformerClassifierParamsModel
{
Norm = "l2",
UseIdf = true,
CountParams = new TfidfTransformerJobSendRequestModel.TfidfTransformerClassifierParamsCountParamsModel
{
NgramRange = [1, 2]
}
},
TextColumn = textColumn,
FileFormat = fileFormat,
Evaluation = new TfidfTransformerJobSendRequestModel.TfidfTransformerEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = true
},
Output = output,
RequestTimeoutSeconds = 300
}),
"TfidfVectorizer" => await SendTypedAsync(new TfidfVectorizerJobSendRequestModel
{
Input = new TfidfVectorizerJobSendRequestModel.TfidfVectorizerInputModel
{
InputBlobId = inputBlobId,
ClassifierType = "TfidfVectorizer",
ClassifierParams = new TfidfVectorizerJobSendRequestModel.TfidfVectorizerClassifierParamsModel
{
NgramRange = [1, 2],
SublinearTf = true,
Norm = "l2"
},
TextColumn = textColumn,
FileFormat = fileFormat,
Evaluation = new TfidfVectorizerJobSendRequestModel.TfidfVectorizerEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = true
},
Output = output,
RequestTimeoutSeconds = 300
}),
_ => throw new NotSupportedException(name)
};
}

private static JsonElement GetResponseProperty(JsonElement response, string camelCaseName, string? snakeCaseName = null)
{
if (response.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty property in response.EnumerateObject())
{
if (string.Equals(property.Name, camelCaseName, StringComparison.OrdinalIgnoreCase)
|| property.Name == snakeCaseName)
return property.Value;
}
}

return default;
}
}
}