-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Add AutoML Interactive Extension #6243
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
aaad18b
ce5f67d
77cc34d
e2278c4
b3884cc
4b65d8b
ee268ee
5f97544
11228f3
4348d97
5cfbec4
02ffadd
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
// 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.Generic; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace Microsoft.ML.AutoML | ||
{ | ||
internal class ActionThrottler | ||
{ | ||
private readonly Action _action; | ||
private readonly TimeSpan _minDelay; | ||
|
||
private DateTime _nextUpdateTime = DateTime.MinValue; | ||
private int _updatePending = 0; | ||
|
||
/// <summary> | ||
/// This constructor initializes an ActionThrottler that ensures <paramref name="action"/> runs no more than once per <paramref name="minDelay"/>. | ||
/// </summary> | ||
/// <param name="action">The action to thorttle.</param> | ||
/// <param name="minDelay">Timespan to indicate the minimum delay between each time action is executed.</param> | ||
public ActionThrottler(Action action, TimeSpan minDelay) | ||
{ | ||
_minDelay = minDelay; | ||
_action = action; | ||
} | ||
|
||
|
||
public async Task ExecuteAsync() | ||
{ | ||
if (Interlocked.CompareExchange(ref _updatePending, 1, 0) == 0) // _updatePending is int initialized with 0 | ||
{ | ||
DateTime currentTime = DateTime.UtcNow; | ||
|
||
if (_nextUpdateTime > currentTime) | ||
{ | ||
await Task.Delay(_nextUpdateTime - currentTime); | ||
} | ||
_action(); | ||
_nextUpdateTime = DateTime.UtcNow + _minDelay; | ||
_updatePending = 0; | ||
} | ||
} | ||
} | ||
} |
103 changes: 103 additions & 0 deletions
103
src/Microsoft.ML.AutoML.Interactive/AutoMLMonitorKernelExtension.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
// 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 Microsoft.AspNetCore.Html; | ||
using Microsoft.Data.Analysis; | ||
using Microsoft.DotNet.Interactive; | ||
using Microsoft.DotNet.Interactive.Commands; | ||
using Microsoft.DotNet.Interactive.Formatting; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Text.Json; | ||
using System.Threading.Tasks; | ||
using Plotly.NET.CSharp; | ||
using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags; | ||
|
||
|
||
namespace Microsoft.ML.AutoML | ||
{ | ||
public class AutoMLMonitorKernelExtension : IKernelExtension | ||
{ | ||
public async Task OnLoadAsync(Kernel kernel) | ||
{ | ||
Formatter.Register<NotebookMonitor>((monitor, writer) => | ||
{ | ||
WriteSummary(monitor, writer); | ||
WriteChart(monitor, writer); | ||
WriteTable(monitor, writer); | ||
}, "text/html"); | ||
|
||
if (Kernel.Root?.FindKernel("csharp") is { } csKernel) | ||
{ | ||
await LoadExtensionApiAsync(csKernel); | ||
} | ||
} | ||
|
||
private static async Task LoadExtensionApiAsync(Kernel cSharpKernel) | ||
{ | ||
await cSharpKernel.SendAsync(new SubmitCode($@"#r ""{typeof(AutoMLMonitorKernelExtension).Assembly.Location}"" | ||
using {typeof(NotebookMonitor).Namespace};")); | ||
} | ||
|
||
private static void WriteSummary(NotebookMonitor monitor, TextWriter writer) | ||
{ | ||
|
||
var summary = new List<IHtmlContent>(); | ||
|
||
if (monitor.BestTrial != null) | ||
{ | ||
var bestTrialParam = JsonSerializer.Serialize(monitor.BestTrial.TrialSettings.Parameter, new JsonSerializerOptions() { WriteIndented = true, }); | ||
summary.Add(h3("Best Trial")); | ||
summary.Add(p($"Id: {monitor.BestTrial.TrialSettings.TrialId}")); | ||
summary.Add(p($"Trainer: {monitor.BestTrial.TrialSettings.Pipeline}".Replace("Unknown=>", ""))); | ||
summary.Add(p($"Parameters: {bestTrialParam}")); | ||
} | ||
if (monitor.ActiveTrial != null) | ||
{ | ||
|
||
var activeTrialParam = JsonSerializer.Serialize(monitor.ActiveTrial.Parameter, new JsonSerializerOptions() { WriteIndented = true, }); | ||
|
||
summary.Add(h3("Active Trial")); | ||
summary.Add(p($"Id: {monitor.ActiveTrial.TrialId}")); | ||
summary.Add(p($"Trainer: {monitor.ActiveTrial.Pipeline}".Replace("Unknown=>", ""))); | ||
JakeRadMSFT marked this conversation as resolved.
Show resolved
Hide resolved
|
||
summary.Add(p($"Parameters: {activeTrialParam}")); | ||
} | ||
|
||
writer.Write(div(summary)); | ||
} | ||
|
||
private static void WriteChart(NotebookMonitor monitor, TextWriter writer) | ||
{ | ||
var x = monitor.CompletedTrials.Select(x => x.TrialSettings.TrialId); | ||
var y = monitor.CompletedTrials.Select(x => x.Metric); | ||
|
||
var chart = Chart.Point<int, double, string>(x, y, "Plot Metrics over Trials.") | ||
.WithTraceInfo(ShowLegend: false) | ||
.WithXAxisStyle<double, double, string>(TitleText: "Trial", ShowGrid: false) | ||
.WithYAxisStyle<double, double, string>(TitleText: "Metric", ShowGrid: false); | ||
|
||
var chartHeader = new List<IHtmlContent>(); | ||
chartHeader.Add(h3("Plot Metrics over Trials")); | ||
writer.Write(div(chartHeader)); | ||
|
||
|
||
Formatter.GetPreferredFormatterFor(typeof(Plotly.NET.GenericChart.GenericChart), "text/html").Format(chart, writer); | ||
|
||
// Works around issue with earlier versions of Plotly.NET - https://github.com/plotly/Plotly.NET/pull/305 | ||
if (writer.ToString().EndsWith("</div \r\n")) | ||
{ | ||
writer.Write(">"); | ||
} | ||
} | ||
|
||
private static void WriteTable(NotebookMonitor notebookMonitor, TextWriter writer) | ||
{ | ||
var tableHeader = new List<IHtmlContent>(); | ||
tableHeader.Add(h3("All Trials Table")); | ||
writer.Write(div(tableHeader)); | ||
Formatter.GetPreferredFormatterFor(typeof(DataFrame), "text/html").Format(notebookMonitor.TrialData, writer); | ||
} | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
src/Microsoft.ML.AutoML.Interactive/Microsoft.ML.AutoML.Interactive.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net6.0</TargetFramework> | ||
michaelgsharp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<IsPackable>false</IsPackable> | ||
michaelgsharp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.DotNet.Interactive" Version="$(MicrosoftDotNetInteractiveVersion)" /> | ||
<PackageReference Include="Microsoft.DotNet.Interactive.Formatting" Version="$(MicrosoftDotNetInteractiveFormattingVersion)" /> | ||
<PackageReference Include="Plotly.NET.CSharp" Version="$(PlotlyNETCSharpVersion)" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Microsoft.ML.SearchSpace\Microsoft.ML.SearchSpace.csproj" /> | ||
michaelgsharp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<ProjectReference Include="..\Microsoft.Data.Analysis\Microsoft.Data.Analysis.csproj" /> | ||
<ProjectReference Include="..\Microsoft.ML.AutoML\Microsoft.ML.AutoML.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
// 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 Microsoft.DotNet.Interactive; | ||
using System.Collections.Generic; | ||
using Microsoft.Data.Analysis; | ||
using System; | ||
using System.Threading.Tasks; | ||
using System.Text.Json; | ||
using System.Threading; | ||
|
||
namespace Microsoft.ML.AutoML | ||
{ | ||
public class NotebookMonitor : IMonitor | ||
{ | ||
private readonly ActionThrottler _updateThrottler; | ||
private DisplayedValue _valueToUpdate; | ||
|
||
public TrialResult BestTrial { get; set; } | ||
public TrialResult MostRecentTrial { get; set; } | ||
public TrialSettings ActiveTrial { get; set; } | ||
public List<TrialResult> CompletedTrials { get; set; } | ||
public DataFrame TrialData { get; set; } | ||
|
||
public NotebookMonitor() | ||
{ | ||
CompletedTrials = new List<TrialResult>(); | ||
TrialData = new DataFrame(new PrimitiveDataFrameColumn<int>("Trial"), new PrimitiveDataFrameColumn<float>("Metric"), new StringDataFrameColumn("Trainer"), new StringDataFrameColumn("Parameters")); | ||
_updateThrottler = new ActionThrottler(Update, TimeSpan.FromSeconds(5)); | ||
} | ||
|
||
public void ReportBestTrial(TrialResult result) | ||
{ | ||
BestTrial = result; | ||
|
||
ThrottledUpdate(); | ||
} | ||
|
||
public void ReportCompletedTrial(TrialResult result) | ||
{ | ||
MostRecentTrial = result; | ||
CompletedTrials.Add(result); | ||
|
||
var activeRunParam = JsonSerializer.Serialize(result.TrialSettings.Parameter, new JsonSerializerOptions() { WriteIndented = false, }); | ||
|
||
TrialData.Append(new List<KeyValuePair<string, object>>() | ||
{ | ||
new KeyValuePair<string, object>("Trial",result.TrialSettings.TrialId), | ||
new KeyValuePair<string, object>("Metric", result.Metric), | ||
new KeyValuePair<string, object>("Trainer",result.TrialSettings.Pipeline.ToString().Replace("Unknown=>","")), | ||
new KeyValuePair<string, object>("Parameters",activeRunParam), | ||
}, true); | ||
|
||
ThrottledUpdate(); | ||
} | ||
|
||
public void ReportFailTrial(TrialResult result) | ||
{ | ||
// TODO figure out what to do with failed trials. | ||
ThrottledUpdate(); | ||
} | ||
|
||
public void ReportRunningTrial(TrialSettings setting) | ||
{ | ||
ActiveTrial = setting; | ||
ThrottledUpdate(); | ||
} | ||
|
||
private void ThrottledUpdate() | ||
{ | ||
Task.Run(async () => await _updateThrottler.ExecuteAsync()); | ||
} | ||
|
||
public void Update() | ||
{ | ||
_valueToUpdate.Update(this); | ||
} | ||
JakeRadMSFT marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
public void SetUpdate(DisplayedValue valueToUpdate) | ||
{ | ||
_valueToUpdate = valueToUpdate; | ||
ThrottledUpdate(); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.