// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.Options;
using Microsoft.ML;
namespace Microsoft.Extensions.ML
{
///
/// Provides a pool of objects
/// that can be used to make predictions.
///
public class PredictionEnginePool : IDisposable
where TData : class
where TPrediction : class, new()
{
private readonly MLOptions _mlContextOptions;
private readonly IOptionsFactory> _predictionEngineOptions;
private readonly IServiceProvider _serviceProvider;
private readonly PoolLoader _defaultEnginePool;
private readonly ConcurrentDictionary> _namedPools;
private int _disposed;
public PredictionEnginePool(IServiceProvider serviceProvider,
IOptions mlContextOptions,
IOptionsFactory> predictionEngineOptions)
{
_mlContextOptions = mlContextOptions.Value;
_predictionEngineOptions = predictionEngineOptions;
_serviceProvider = serviceProvider;
var defaultOptions = _predictionEngineOptions.Create(string.Empty);
if (defaultOptions.ModelLoader != null)
{
_defaultEnginePool = new PoolLoader(_serviceProvider, defaultOptions);
}
_namedPools = new ConcurrentDictionary>();
}
///
/// Get the Model used to create the pooled PredictionEngine.
///
///
/// The name of the model. Used when there are multiple models with the same input/output.
///
public ITransformer GetModel(string modelName)
{
if (!_namedPools.ContainsKey(modelName))
{
AddPool(modelName);
}
return _namedPools[modelName].Loader.GetModel();
}
///
/// Get the Model used to create the pooled PredictionEngine.
///
public ITransformer GetModel()
{
return _defaultEnginePool.Loader.GetModel();
}
///
/// Gets a PredictionEngine that can be used to make predictions using
/// and .
///
public PredictionEngine GetPredictionEngine()
{
return GetPredictionEngine(string.Empty);
}
///
/// Gets a PredictionEngine for a named model.
///
///
/// The name of the model which allows for uniquely identifying the model when
/// multiple models have the same and
/// types.
///
public PredictionEngine GetPredictionEngine(string modelName)
{
if (Volatile.Read(ref _disposed) != 0)
{
throw new ObjectDisposedException(nameof(PredictionEnginePool));
}
if (_namedPools.TryGetValue(modelName, out var existingPool))
{
return existingPool.Get();
}
//This is the case where someone has used string.Empty to get the default model.
//We can throw all the time, but it seems reasonable that we would just do what
//they are expecting if they know that an empty string means default.
if (string.IsNullOrEmpty(modelName))
{
if (_defaultEnginePool == null)
{
throw new ArgumentException("You need to configure a default, not named, model before you use this method.");
}
return _defaultEnginePool.Get();
}
var pool = AddPool(modelName);
return pool.Get();
}
private PoolLoader AddPool(string modelName)
{
//Here we are in the world of named models where the model hasn't been built yet.
var options = _predictionEngineOptions.Create(modelName);
var pool = new PoolLoader(_serviceProvider, options);
pool = _namedPools.GetOrAdd(modelName, pool);
return pool;
}
///
/// Returns a rented PredictionEngine to the pool.
///
/// The rented PredictionEngine.
public void ReturnPredictionEngine(PredictionEngine engine)
{
ReturnPredictionEngine(string.Empty, engine);
}
///
/// Returns a rented PredictionEngine to the pool.
///
///
/// The name of the model which allows for uniquely identifying the model when
/// multiple models have the same and
/// types.
///
/// The rented PredictionEngine.
public void ReturnPredictionEngine(string modelName, PredictionEngine engine)
{
if (engine == null)
{
throw new ArgumentNullException(nameof(engine));
}
if (Volatile.Read(ref _disposed) != 0)
{
engine.Dispose();
return;
}
if (string.IsNullOrEmpty(modelName))
{
if (_defaultEnginePool != null)
{
_defaultEnginePool.Return(engine);
}
else
{
engine.Dispose();
}
}
else if (_namedPools.TryGetValue(modelName, out var pool))
{
pool.Return(engine);
}
else
{
engine.Dispose();
}
}
///
/// Disposes the pooled prediction engines and releases the file/uri watchers backing each
/// model loader.
///
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
_defaultEnginePool?.Dispose();
foreach (var pool in _namedPools.Values)
{
pool.Dispose();
}
_namedPools.Clear();
}
}
}