id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,607
|
Tensor.cpp
|
Const-me_Whisper/Whisper/ML/Tensor.cpp
|
#include "stdafx.h"
#include "Tensor.h"
#include "../D3D/MappedResource.h"
#include "../D3D/createBuffer.h"
#include "../source/ggml.h"
using namespace DirectCompute;
Tensor::Tensor( const Tensor& that )
{
ne = that.ne;
nb = that.nb;
srv = that.srv;
uav = that.uav;
#ifdef _DEBUG
dbgType = that.dbgType;
#endif
}
Tensor::Tensor( Tensor&& that ) noexcept
{
ne = that.ne;
nb = that.nb;
srv.Attach( that.srv.Detach() );
uav.Attach( that.uav.Detach() );
#ifdef _DEBUG
dbgType = that.dbgType;
#endif
}
Tensor& Tensor::operator=( const Tensor& that )
{
ne = that.ne;
nb = that.nb;
srv = that.srv;
uav = that.uav;
#ifdef _DEBUG
dbgType = that.dbgType;
#endif
return *this;
}
Tensor& Tensor::operator=( Tensor&& that ) noexcept
{
ne = that.ne;
nb = that.nb;
srv.Attach( that.srv.Detach() );
uav.Attach( that.uav.Detach() );
#ifdef _DEBUG
dbgType = that.dbgType;
#endif
return *this;
}
Tensor::Tensor( const TensorShape& shape, CComPtr<ID3D11ShaderResourceView>& srv, CComPtr<ID3D11UnorderedAccessView>& uav ) noexcept :
TensorShape( shape )
{
TensorGpuViews::srv.Attach( srv.Detach() );
TensorGpuViews::uav.Attach( uav.Detach() );
}
Tensor::Tensor( const TensorShape& shape, const TensorGpuViews& views ) :
TensorShape( shape )
{
srv = views;
uav = views;
}
HRESULT Tensor::create( const ggml_tensor& ggml, eBufferUse usage, bool uploadData )
{
TensorGpuViews::clear();
switch( usage )
{
case eBufferUse::Immutable:
case eBufferUse::ReadWriteDownload:
break;
default:
return E_INVALIDARG;
}
CComPtr<ID3D11Buffer> buffer;
CHECK( TensorShape::create( ggml ) );
const ggml_type dataType = ggml.type;
const uint32_t cbElement = (uint32_t)ggml_type_size( dataType );
const size_t totalBytes = ggml_nbytes( &ggml );
if( totalBytes > INT_MAX )
return DISP_E_OVERFLOW;
const uint32_t countElements = (uint32_t)( totalBytes / cbElement );
{
const void* const rsi = uploadData ? ggml.data : nullptr;
CHECK( createBuffer( usage, totalBytes, &buffer, rsi, nullptr ) );
}
DXGI_FORMAT format;
eDataType type;
switch( dataType )
{
case GGML_TYPE_F16:
format = DXGI_FORMAT_R16_FLOAT;
type = eDataType::FP16;
break;
case GGML_TYPE_F32:
format = DXGI_FORMAT_R32_FLOAT;
type = eDataType::FP32;
break;
default:
return E_NOTIMPL;
}
const bool makeUav = ( usage == eBufferUse::ReadWrite );
CHECK( TensorGpuViews::create( buffer, format, totalBytes / cbElement, makeUav ) );
#ifdef _DEBUG
dbgType.type = type;
dbgType.usage = usage;
dbgType.hasInitialData = uploadData;
#endif
return S_OK;
}
HRESULT Tensor::createImmutable( eDataType type, const std::array<int, 4>& size, const void* rsi )
{
size_t elts = (uint32_t)size[ 0 ];
elts *= (uint32_t)size[ 1 ];
elts *= (uint32_t)size[ 2 ];
elts *= (uint32_t)size[ 3 ];
DXGI_FORMAT format;
size_t cbElement;
switch( type )
{
case eDataType::FP16:
format = DXGI_FORMAT_R16_FLOAT;
cbElement = 2;
break;
case eDataType::FP32:
format = DXGI_FORMAT_R32_FLOAT;
cbElement = 4;
break;
default:
return E_NOTIMPL;
}
CComPtr<ID3D11Buffer> buffer;
CHECK( createBuffer( eBufferUse::Immutable, cbElement * elts, &buffer, rsi, nullptr ) );
CHECK( TensorGpuViews::create( buffer, format, elts, false ) );
__m128i v = _mm_loadu_si128( ( const __m128i* )size.data() );
_mm_storeu_si128( ( __m128i* )ne.data(), v );
setDenseStrides();
return S_OK;
}
HRESULT Tensor::create( eDataType type, std::initializer_list<uint32_t> sizeElements, eBufferUse usage, CComPtr<ID3D11Buffer>& buffer, const void* rsi, ID3D11Buffer** ppStagingBuffer, bool shared )
{
TensorGpuViews::clear();
size_t nDims = sizeElements.size();
if( 0 == nDims || nDims > 4 )
return E_INVALIDARG;
nDims = std::min( nDims, (size_t)4 );
size_t totalElements = 1;
for( size_t i = 0; i < nDims; i++ )
{
uint32_t n = sizeElements.begin()[ i ];
if( n == 0 )
return E_INVALIDARG;
ne[ i ] = n;
totalElements *= n;
}
DXGI_FORMAT format;
size_t cbElement;
switch( type )
{
case eDataType::FP32:
format = DXGI_FORMAT_R32_FLOAT;
cbElement = 4;
break;
case eDataType::FP16:
format = DXGI_FORMAT_R16_FLOAT;
cbElement = 2;
break;
case eDataType::U32:
format = DXGI_FORMAT_R32_UINT;
cbElement = 4;
break;
default:
return E_NOTIMPL;
}
const size_t totalBytes = cbElement * totalElements;
if( totalBytes > INT_MAX )
return DISP_E_OVERFLOW;
for( size_t i = nDims; i < 4; i++ )
ne[ i ] = 1;
TensorShape::setDenseStrides();
CHECK( createBuffer( usage, totalBytes, &buffer, rsi, ppStagingBuffer, shared ) );
CHECK( TensorGpuViews::create( buffer, format, totalBytes / cbElement, true ) );
#ifdef _DEBUG
dbgType.type = type;
dbgType.usage = usage;
dbgType.hasInitialData = ( nullptr != rsi );
#endif
return S_OK;
}
HRESULT Tensor::create( eDataType type, std::initializer_list<uint32_t> sizeElements, bool shared )
{
CComPtr<ID3D11Buffer> buffer;
return create( type, sizeElements, eBufferUse::ReadWrite, buffer, nullptr, nullptr, shared );
}
HRESULT Tensor::create( eDataType type, const std::array<uint32_t, 4>& sizeElements, bool shared )
{
std::initializer_list<uint32_t> il( sizeElements.data(), sizeElements.data() + 4 );
return create( type, il, shared );
}
eDataType Tensor::getType() const
{
ID3D11ShaderResourceView* const srv = *this;
if( nullptr == srv )
throw OLE_E_BLANK;
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
srv->GetDesc( &viewDesc );
const DXGI_FORMAT format = viewDesc.Format;
switch( format )
{
case DXGI_FORMAT_R32_FLOAT:
return eDataType::FP32;
case DXGI_FORMAT_R16_FLOAT:
return eDataType::FP16;
case DXGI_FORMAT_R32_UINT:
return eDataType::U32;
}
throw E_NOTIMPL;
}
CComPtr<ID3D11Buffer> Tensor::getBuffer() const
{
ID3D11ShaderResourceView* const srv = *this;
if( nullptr == srv )
throw OLE_E_BLANK;
CComPtr<ID3D11Resource> res;
srv->GetResource( &res );
CComPtr<ID3D11Buffer> buff;
check( res.QueryInterface( &buff ) );
return buff;
}
uint32_t Tensor::dxgiSizeof( DXGI_FORMAT format )
{
switch( format )
{
case DXGI_FORMAT_R16_FLOAT:
return 2;
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_UINT:
return 4;
}
throw E_INVALIDARG;
}
void Tensor::downloadImpl( const D3D11_SHADER_RESOURCE_VIEW_DESC& viewDesc, uint32_t countElements, size_t cbElement, void* rdi ) const
{
assert( viewDesc.ViewDimension == D3D_SRV_DIMENSION_BUFFER );
const uint32_t idxFirst = viewDesc.Buffer.FirstElement;
CComPtr<ID3D11Buffer> buff = getBuffer();
D3D11_BUFFER_DESC desc;
buff->GetDesc( &desc );
desc.BindFlags = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
CComPtr<ID3D11Buffer> staging;
check( device()->CreateBuffer( &desc, nullptr, &staging ) );
context()->CopyResource( staging, buff );
MappedResource mapped;
check( mapped.map( staging, true ) );
const uint8_t* rsi = (const uint8_t*)mapped.data();
rsi += cbElement * idxFirst;
memcpy( rdi, rsi, cbElement * countElements );
}
void Tensor::download( std::vector<float>& vec ) const
{
ID3D11ShaderResourceView* const srv = *this;
if( nullptr == srv )
throw OLE_E_BLANK;
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
srv->GetDesc( &viewDesc );
if( viewDesc.Format != DXGI_FORMAT_R32_FLOAT )
throw E_INVALIDARG;
uint32_t countElements = viewDesc.Buffer.NumElements;
vec.resize( countElements );
downloadImpl( viewDesc, countElements, 4, vec.data() );
}
void Tensor::download( std::vector<uint16_t>& vec ) const
{
ID3D11ShaderResourceView* const srv = *this;
if( nullptr == srv )
throw OLE_E_BLANK;
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
srv->GetDesc( &viewDesc );
if( viewDesc.Format != DXGI_FORMAT_R16_FLOAT )
throw E_INVALIDARG;
uint32_t countElements = viewDesc.Buffer.NumElements;
vec.resize( countElements );
downloadImpl( viewDesc, countElements, 2, vec.data() );
}
Tensor Tensor::reshape3d( uint32_t ne0, uint32_t ne1, uint32_t ne2 ) const
{
if( !isContinuous() )
throw E_NOTIMPL;
if( countElements() != ne0 * ne1 * ne2 )
throw E_INVALIDARG;
Tensor res = *this;
res.ne = { ne0, ne1, ne2, 1 };
res.setDenseStrides();
return res;
}
| 8,093
|
C++
|
.cpp
| 294
| 25.445578
| 197
| 0.723884
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,608
|
TensorShape.cpp
|
Const-me_Whisper/Whisper/ML/TensorShape.cpp
|
#include "stdafx.h"
#include "TensorShape.h"
#include "../source/ggml.h"
using namespace DirectCompute;
TensorShape::TensorShape()
{
setZero();
}
TensorShape::TensorShape( const TensorShape& that )
{
_mm_storeu_si128( ( __m128i* )ne.data(), that.sizeVec() );
_mm_storeu_si128( ( __m128i* )nb.data(), that.stridesVec() );
}
void TensorShape::operator=( const TensorShape& that )
{
_mm_storeu_si128( ( __m128i* )ne.data(), that.sizeVec() );
_mm_storeu_si128( ( __m128i* )nb.data(), that.stridesVec() );
}
HRESULT TensorShape::create( const ggml_tensor& ggml )
{
for( size_t i = 0; i < 4; i++ )
ne[ i ] = (uint32_t)ggml.ne[ i ];
const ggml_type dataType = ggml.type;
// Verify a few things
uint32_t cbElement = (uint32_t)ggml_type_size( dataType );
for( size_t i = 0; i < 4; i++ )
{
size_t stride = ggml.nb[ i ];
if( 0 != stride % cbElement )
return E_INVALIDARG;
size_t nn = stride / cbElement;
if( nn > UINT_MAX )
return DISP_E_OVERFLOW;
nb[ i ] = (uint32_t)nn;
}
return S_OK;
}
TensorShape::TensorShape( const ggml_tensor& ggml )
{
HRESULT hr = create( ggml );
if( FAILED( hr ) )
throw hr;
}
void TensorShape::setDenseStrides()
{
nb[ 0 ] = 1;
nb[ 1 ] = ne[ 0 ];
const uint32_t p01 = ne[ 0 ] * ne[ 1 ];
nb[ 2 ] = p01;
nb[ 3 ] = p01 * ne[ 2 ];
}
bool DirectCompute::canMulMat( const TensorShape& t0, const TensorShape& t1 )
{
/*
return
( t0.ne[ 0 ] == t1.ne[ 0 ] ) &&
( t0.ne[ 2 ] == t1.ne[ 2 ] ) &&
( t0.ne[ 3 ] == t1.ne[ 3 ] ); */
__m128i a = t0.sizeVec();
__m128i b = t1.sizeVec();
__m128i xx = _mm_xor_si128( a, b );
xx = _mm_shuffle_epi32( xx, _MM_SHUFFLE( 3, 2, 0, 0 ) );
return (bool)_mm_testz_si128( xx, xx );
}
| 1,678
|
C++
|
.cpp
| 64
| 24.28125
| 77
| 0.619166
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,609
|
DbgNanTest.cpp
|
Const-me_Whisper/Whisper/ML/DbgNanTest.cpp
|
#include "stdafx.h"
#include "DbgNanTest.h"
#include "../D3D/MappedResource.h"
using namespace DirectCompute;
HRESULT DbgNanTest::create()
{
ID3D11Device* const dev = DirectCompute::device();
CD3D11_BUFFER_DESC desc{ 4, D3D11_BIND_UNORDERED_ACCESS };
CHECK( dev->CreateBuffer( &desc, nullptr, &bufferDefault ) );
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
CHECK( dev->CreateBuffer( &desc, nullptr, &bufferStaging ) );
CD3D11_UNORDERED_ACCESS_VIEW_DESC viewDesc{ D3D11_UAV_DIMENSION_BUFFER, DXGI_FORMAT_R32_UINT, 0, 1 };
CHECK( dev->CreateUnorderedAccessView( bufferDefault, &viewDesc, &uav ) );
return S_OK;
}
void DbgNanTest::destroy()
{
uav = nullptr;
bufferStaging = nullptr;
bufferDefault = nullptr;
}
bool DbgNanTest::test() const
{
context()->CopyResource( bufferStaging, bufferDefault );
MappedResource mapped;
check( mapped.map( bufferStaging, true ) );
const BOOL val = *(const BOOL*)mapped.data();
return val != 0;
}
| 1,007
|
C++
|
.cpp
| 31
| 30.709677
| 102
| 0.753608
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,610
|
mlUtils.cpp
|
Const-me_Whisper/Whisper/ML/mlUtils.cpp
|
#include "stdafx.h"
#include "LookupTables.h"
#include "../D3D/MappedResource.h"
#include "mlUtils.h"
#include "../D3D/shaders.h"
#include "../D3D/Binder.h"
#include "DbgNanTest.h"
namespace DirectCompute
{
void zeroMemory( ID3D11UnorderedAccessView* uav, uint32_t length, bool fillWithNaN )
{
__m128i cbData = _mm_cvtsi32_si128( (int)length );
cbData = _mm_insert_epi32( cbData, fillWithNaN ? 1 : 0, 1 );
ID3D11Buffer* cb = updateSmallCb( cbData );
ID3D11DeviceContext* ctx = context();
ctx->CSSetUnorderedAccessViews( 0, 1, &uav, nullptr );
csSetCB( cb );
constexpr uint32_t THREADS = 512;
constexpr uint32_t ITERATIONS = 128;
constexpr uint32_t elementsPerGroup = THREADS * ITERATIONS;
const uint32_t countGroups = ( length + elementsPerGroup - 1 ) / elementsPerGroup;
bindShader( eComputeShader::zeroMemory );
ctx->Dispatch( countGroups, 1, 1 );
}
void fillTensorWithNaN( ID3D11UnorderedAccessView* uav )
{
// Note we fill the complete unordered access view, ignoring the current size of the tensor. This is deliberate.
D3D11_UNORDERED_ACCESS_VIEW_DESC desc;
uav->GetDesc( &desc );
assert( desc.Format == DXGI_FORMAT_R32_FLOAT || desc.Format == DXGI_FORMAT_R16_FLOAT );
zeroMemory( uav, desc.Buffer.NumElements, true );
}
bool scanTensorForNaN( ID3D11ShaderResourceView* tensor, uint32_t length )
{
#if DBG_TEST_NAN
// Unlike fillTensorWithNaN function, this one only tests initial portion of the buffer
const DbgNanTest& buffers = getNanTestBuffers();
// Update constant buffer with elements = length, reset = true
__m128i cbData = _mm_cvtsi32_si128( (int)length );
cbData = _mm_insert_epi32( cbData, 1, 1 );
ID3D11Buffer* cb = updateSmallCb( cbData );
// Bind the compute shader and resources
bindShader( eComputeShader::dbgFindNaN );
csSetCB( cb );
Binder bind;
bind.bind( tensor, buffers );
// Dispatch exactly 1 thread group of that shader
context()->Dispatch( 1, 1, 1 );
// Update constant buffer with elements = length, reset = false
cbData = _mm_cvtsi32_si128( (int)length );
updateSmallCb( cbData );
// Dispatch the necessary count of that shader
constexpr uint32_t THREADS = 512;
constexpr uint32_t ITERATIONS = 128;
constexpr uint32_t elementsPerGroup = THREADS * ITERATIONS;
const uint32_t countGroups = ( length + elementsPerGroup - 1 ) / elementsPerGroup;
context()->Dispatch( countGroups, 1, 1 );
// Download result from GPU. This stalls the GPU pipeline, and ruins the performance.
// This code better be disabled with DBG_TEST_NAN=0 macro
return buffers.test();
#else
return false;
#endif
}
HRESULT cloneResourceView( ID3D11ShaderResourceView* rsi, ID3D11ShaderResourceView** rdi )
{
if( nullptr == rdi || nullptr == rsi )
return E_POINTER;
if( nullptr == rsi )
{
*rdi = nullptr;
return S_FALSE;
}
// Open shared resource on another device
CComPtr<ID3D11Resource> sourceRes;
rsi->GetResource( &sourceRes );
#ifdef DEBUG
CComPtr<ID3D11Buffer> sourceBuffer;
CHECK( sourceRes->QueryInterface( &sourceBuffer ) );
D3D11_BUFFER_DESC buffDesc;
sourceBuffer->GetDesc( &buffDesc );
const uint32_t miscFlags = buffDesc.MiscFlags;
if( 0 == ( miscFlags & D3D11_RESOURCE_MISC_SHARED ) )
{
logError( u8"Source buffer doesn't have D3D11_RESOURCE_MISC_SHARED flag" );
return E_INVALIDARG;
}
#endif
CComPtr<IDXGIResource> sourceDxgiRes;
CHECK( sourceRes->QueryInterface( &sourceDxgiRes ) );
HANDLE h = nullptr;
CHECK( sourceDxgiRes->GetSharedHandle( &h ) );
CComPtr<ID3D11Buffer> newBuffer;
CHECK( device()->OpenSharedResource( h, IID_PPV_ARGS( &newBuffer ) ) );
// Create shader resource view on the new device, using the same specs
D3D11_SHADER_RESOURCE_VIEW_DESC desc;
rsi->GetDesc( &desc );
CHECK( device()->CreateShaderResourceView( newBuffer, &desc, rdi ) );
return S_OK;
}
}
| 3,868
|
C++
|
.cpp
| 101
| 35.49505
| 114
| 0.7344
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,611
|
LookupTables.cpp
|
Const-me_Whisper/Whisper/ML/LookupTables.cpp
|
#include "stdafx.h"
#include "LookupTables.h"
#include "LookupTablesData.h"
#include <memory>
#include "mlUtils.h"
using namespace DirectCompute;
namespace
{
HRESULT uploadLookupTable( const std::array<uint16_t, 0x10000>& rsi, CComPtr<ID3D11ShaderResourceView>& rdi )
{
rdi = nullptr;
CComPtr<ID3D11Buffer> buffer;
CD3D11_BUFFER_DESC desc{ 0x10000 * 2, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_IMMUTABLE };
if( gpuInfo().cloneableModel() )
{
desc.Usage = D3D11_USAGE_DEFAULT;
desc.MiscFlags |= D3D11_RESOURCE_MISC_SHARED;
}
D3D11_SUBRESOURCE_DATA srd{ rsi.data(), 0, 0 };
CHECK( device()->CreateBuffer( &desc, &srd, &buffer ) );
CD3D11_SHADER_RESOURCE_VIEW_DESC viewDesc{ D3D11_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R16_UINT, 0, 0x10000 };
CHECK( device()->CreateShaderResourceView( buffer, &viewDesc, &rdi ) );
return S_OK;
}
}
HRESULT LookupTables::create()
{
std::unique_ptr<LookupTablesData> data;
try
{
data = std::make_unique<LookupTablesData>();
}
catch( const std::bad_alloc& )
{
return E_OUTOFMEMORY;
}
CHECK( uploadLookupTable( data->gelu, m_gelu ) );
CHECK( uploadLookupTable( data->exponent, m_exponent ) );
return S_OK;
}
HRESULT LookupTables::createClone( const LookupTables& source )
{
CHECK( cloneResourceView( source.m_gelu, &m_gelu ) );
CHECK( cloneResourceView( source.m_exponent, &m_exponent ) );
return S_OK;
}
void LookupTables::clear()
{
m_gelu = nullptr;
m_exponent = nullptr;
}
__m128i LookupTables::getMemoryUsage() const
{
__m128i v = resourceMemoryUsage( m_gelu );
v = _mm_add_epi64( v, resourceMemoryUsage( m_exponent ) );
return v;
}
| 1,621
|
C++
|
.cpp
| 57
| 26.350877
| 110
| 0.733119
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,612
|
tensorOpsTests.cpp
|
Const-me_Whisper/Whisper/ML/tensorOpsTests.cpp
|
#include "stdafx.h"
#include "tensorOpsTests.h"
#include "MlContext.h"
#include "TensorEx.h"
#include "../D3D/shaders.h"
#include "../D3D/Binder.h"
#include "testUtils.h"
#include "../Whisper/WhisperContext.h"
void DirectCompute::testMulMat( const ggml_tensor* src0, const ggml_tensor* src1, const ggml_tensor* dst, const void* tempBuffer )
{
return;
CaptureRaii capture;
const size_t nb00 = src0->nb[ 0 ];
const size_t nb01 = src0->nb[ 1 ];
if( src0->type != GGML_TYPE_F16 )
return; // TODO
if( nb01 < nb00 )
return; // TODO
WhisperContext& ctx = WhisperContext::current();
Tensor arg0, arg1;
check( arg0.create( *src0, eBufferUse::Immutable, true ) );
check( arg1.create( *src1, eBufferUse::Immutable, true ) );
TensorEx res;
check( res.create( *dst, eBufferUse::ReadWriteDownload, false ) );
ctx.mulMat( arg0, arg1, res );
std::vector<float> tv;
check( res.download( tv ) );
const size_t len = tv.size();
computeDiff( tv.data(), (const float*)dst->data, len ).print( "testMulMat-product" );
#if 0
dbgWriteBinaryFile( L"product-orig.bin", dst->data, len * 4 );
dbgWriteBinaryFile( L"product-gpu.bin", tv.data(), len * 4 );
__debugbreak();
#endif
}
#if 0
void DirectCompute::testMulMatReshape( const ggml_tensor* src1, const void* tempBuffer )
{
Tensor src;
check( src.create( *src1, eBufferUse::Immutable, true ) );
const size_t ne10 = (uint32_t)src1->ne[ 0 ];
const size_t ne11 = (uint32_t)src1->ne[ 1 ];
const size_t ne12 = (uint32_t)src1->ne[ 2 ];
const size_t ne13 = (uint32_t)src1->ne[ 3 ];
if( 1 != ne13 )
throw E_UNEXPECTED;
const size_t tempLength = ne10 * ne11 * ne12 * ne13;
Context& ctx = Context::current();
const ReadWriteViews& temp = ctx.temp.fp16( tempLength );
{
Binder bind;
ctx.cb.bind();
bindShader( eComputeShader::mulMatDotReshape );
ctx.cb.update( src );
bind.bind( src, temp );
context()->Dispatch( (UINT)ne11, (UINT)ne12, 1 );
}
std::vector<uint16_t> reshaped;
check( downloadBuffer( temp, reshaped ) );
computeDiff( reshaped.data(), (const uint16_t*)tempBuffer, reshaped.size() ).print( "testMulMatReshape" );
#if 0
dbgWriteBinaryFile( L"fp32.bin", src1->data, ggml_nbytes( src1 ) );
dbgWriteBinaryFile( L"fp16-cpu.bin", tempBuffer, reshaped.size() * 2 );
dbgWriteBinaryFile( L"fp16-gpu.bin", reshaped.data(), reshaped.size() * 2 );
__debugbreak();
#endif
}
#endif
void DirectCompute::computeMulMat( const ggml_tensor* src0, const ggml_tensor* src1, ggml_tensor* dst )
{
CaptureRaii capture;
const size_t nb00 = src0->nb[ 0 ];
const size_t nb01 = src0->nb[ 1 ];
if( src0->type != GGML_TYPE_F16 )
throw E_INVALIDARG;
if( nb01 < nb00 )
throw E_INVALIDARG;
WhisperContext& ctx = WhisperContext::current();
Tensor arg0, arg1;
check( arg0.create( *src0, eBufferUse::Immutable, true ) );
check( arg1.create( *src1, eBufferUse::Immutable, true ) );
TensorEx res;
check( res.create( *dst, eBufferUse::ReadWriteDownload, false ) );
ctx.mulMat( arg0, arg1, res );
check( res.download( dst->data ) );
}
void DirectCompute::testFlashAttention( const ggml_tensor* q, const ggml_tensor* k, const ggml_tensor* v, bool masked, const ggml_tensor* dst )
{
CaptureRaii capture;
Tensor Q, K, V;
TensorEx res;
check( Q.create( *q, eBufferUse::Immutable, true ) );
check( K.create( *k, eBufferUse::Immutable, true ) );
check( V.create( *v, eBufferUse::Immutable, true ) );
check( res.create( *dst, eBufferUse::ReadWriteDownload, false ) );
WhisperContext& ctx = WhisperContext::current();
ctx.flashAttention( Q, K, V, res, masked );
std::vector<float> tv;
check( res.download( tv ) );
const size_t len = tv.size();
computeDiff( tv.data(), (const float*)dst->data, len ).print( "testFlashAttention" );
}
void DirectCompute::computeFlashAttention( const ggml_tensor* q, const ggml_tensor* k, const ggml_tensor* v, bool masked, ggml_tensor* dst )
{
CaptureRaii capture;
Tensor Q, K, V;
TensorEx res;
check( Q.create( *q, eBufferUse::Immutable, true ) );
check( K.create( *k, eBufferUse::Immutable, true ) );
check( V.create( *v, eBufferUse::Immutable, true ) );
check( res.create( *dst, eBufferUse::ReadWriteDownload, false ) );
WhisperContext& ctx = WhisperContext::current();
ctx.flashAttention( Q, K, V, res, masked );
check( res.download( dst->data ) );
}
void DirectCompute::testConvolution( const ggml_tensor* src0, const ggml_tensor* src1, const ggml_tensor* dst )
{
CaptureRaii capture;
Tensor arg0, arg1;
check( arg0.create( *src0, eBufferUse::Immutable, true ) );
check( arg1.create( *src1, eBufferUse::Immutable, true ) );
TensorEx res;
check( res.create( *dst, eBufferUse::ReadWriteDownload, false ) );
WhisperContext& ctx = WhisperContext::current();
ctx.convolution( arg0, arg1, res );
std::vector<float> tv;
check( res.download( tv ) );
const size_t len = tv.size();
computeDiff( tv.data(), (const float*)dst->data, len ).print( "testConvolution" );
}
void DirectCompute::computeConvolution( const ggml_tensor* src0, const ggml_tensor* src1, ggml_tensor* dst )
{
CaptureRaii capture;
Tensor arg0, arg1;
check( arg0.create( *src0, eBufferUse::Immutable, true ) );
check( arg1.create( *src1, eBufferUse::Immutable, true ) );
TensorEx res;
check( res.create( *dst, eBufferUse::ReadWriteDownload, false ) );
WhisperContext& ctx = WhisperContext::current();
ctx.convolution( arg0, arg1, res );
res.download( dst->data );
}
| 5,394
|
C++
|
.cpp
| 142
| 35.873239
| 143
| 0.709708
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,613
|
TensorGpuViews.cpp
|
Const-me_Whisper/Whisper/ML/TensorGpuViews.cpp
|
#include "stdafx.h"
#include "TensorGpuViews.h"
using namespace DirectCompute;
HRESULT TensorGpuViews::create( ID3D11Buffer* gpuBuffer, DXGI_FORMAT format, size_t countElements, bool makeUav )
{
srv = nullptr;
uav = nullptr;
if( countElements > UINT_MAX )
return DISP_E_OVERFLOW;
CD3D11_SHADER_RESOURCE_VIEW_DESC viewDesc{ D3D11_SRV_DIMENSION_BUFFER, format, 0, (UINT)countElements };
CHECK( device()->CreateShaderResourceView( gpuBuffer, &viewDesc, &srv ) );
if( makeUav )
{
CD3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc{ D3D11_UAV_DIMENSION_BUFFER, format , 0, (UINT)countElements };
CHECK( device()->CreateUnorderedAccessView( gpuBuffer, &uavDesc, &uav ) );
}
return S_OK;
}
| 693
|
C++
|
.cpp
| 18
| 36.444444
| 113
| 0.76155
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,614
|
TempBuffers.cpp
|
Const-me_Whisper/Whisper/ML/TempBuffers.cpp
|
#include "stdafx.h"
#include "TempBuffers.h"
#include "../D3D/createBuffer.h"
#include "../D3D/MappedResource.h"
#include "mlUtils.h"
using namespace DirectCompute;
#define CHECK( hr ) { const HRESULT __hr = ( hr ); if( FAILED( __hr ) ) return __hr; }
HRESULT TempBuffers::Buffer::resize( DXGI_FORMAT format, size_t elements, size_t cbElement, bool zeroMemory )
{
if( elements <= capacity )
{
if( zeroMemory )
DirectCompute::zeroMemory( *this, (uint32_t)elements );
return S_OK;
}
clear();
CComPtr<ID3D11Buffer> buffer;
const size_t totalBytes = elements * cbElement;
CHECK( createBuffer( eBufferUse::ReadWrite, totalBytes, &buffer, nullptr, nullptr ) );
CHECK( TensorGpuViews::create( buffer, format, elements, true ) );
capacity = elements;
return S_OK;
}
const TensorGpuViews& TempBuffers::fp16( size_t countElements, bool zeroMemory )
{
HRESULT hr = m_fp16.resize( DXGI_FORMAT_R16_FLOAT, countElements, 2, zeroMemory );
if( FAILED( hr ) )
throw hr;
return m_fp16;
}
const TensorGpuViews& TempBuffers::fp16_2( size_t countElements, bool zeroMemory )
{
HRESULT hr = m_fp16_2.resize( DXGI_FORMAT_R16_FLOAT, countElements, 2, zeroMemory );
if( FAILED( hr ) )
throw hr;
return m_fp16_2;
}
const TensorGpuViews& TempBuffers::fp32( size_t countElements, bool zeroMemory )
{
HRESULT hr = m_fp32.resize( DXGI_FORMAT_R32_FLOAT, countElements, 4, zeroMemory );
if( FAILED( hr ) )
throw hr;
return m_fp32;
}
__m128i TempBuffers::getMemoryUse() const
{
size_t cb = m_fp16.getCapacity() * 2;
cb += m_fp16_2.getCapacity() * 2;
cb += m_fp32.getCapacity() * 4;
return setHigh_size( cb );
}
| 1,619
|
C++
|
.cpp
| 51
| 29.921569
| 109
| 0.724072
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,615
|
convertThings.cpp
|
Const-me_Whisper/Whisper/source.compat/convertThings.cpp
|
#include "stdafx.h"
#if BUILD_BOTH_VERSIONS
#include "../API/iContext.cl.h"
#include "convertThings.h"
using namespace Whisper;
sFullParams makeNewParams( const whisper_full_params& wfp )
{
assert( nullptr == wfp.encoder_begin_callback );
assert( nullptr == wfp.new_segment_callback );
sFullParams res;
memset( &res, 0, sizeof( res ) );
res.strategy = (eSamplingStrategy)wfp.strategy;
res.cpuThreads = wfp.n_threads;
res.n_max_text_ctx = wfp.n_max_text_ctx;
res.offset_ms = wfp.offset_ms;
res.duration_ms = wfp.duration_ms;
// flags
uint32_t flags = 0;
if( wfp.translate ) flags |= (uint32_t)eFullParamsFlags::Translate;
if( wfp.no_context ) flags |= (uint32_t)eFullParamsFlags::NoContext;
if( wfp.single_segment ) flags |= (uint32_t)eFullParamsFlags::SingleSegment;
if( wfp.print_special ) flags |= (uint32_t)eFullParamsFlags::PrintSpecial;
if( wfp.print_progress ) flags |= (uint32_t)eFullParamsFlags::PrintProgress;
if( wfp.print_realtime ) flags |= (uint32_t)eFullParamsFlags::PrintRealtime;
if( wfp.print_timestamps ) flags |= (uint32_t)eFullParamsFlags::PrintTimestamps;
if( wfp.token_timestamps ) flags |= (uint32_t)eFullParamsFlags::TokenTimestamps;
if( wfp.speed_up ) flags |= (uint32_t)eFullParamsFlags::SpeedupAudio;
res.flags = (eFullParamsFlags)flags;
res.language = findLanguageKeyA( wfp.language );
res.thold_pt = wfp.thold_pt;
res.thold_ptsum = wfp.thold_ptsum;
res.max_len = wfp.max_len;
res.greedy.n_past = wfp.greedy.n_past;
res.beam_search.n_past = wfp.beam_search.n_past;
res.beam_search.beam_width = wfp.beam_search.beam_width;
res.beam_search.n_best = wfp.beam_search.n_best;
res.audio_ctx = wfp.audio_ctx;
res.prompt_tokens = wfp.prompt_tokens;
res.prompt_n_tokens = wfp.prompt_n_tokens;
return res;
}
namespace
{
class NewParamsTemp
{
char language[ 5 ];
iContext* newContext;
pfnNewSegment newSegment;
pfnEncoderBegin encoderBegin;
static bool encBegin( struct whisper_context* ctx, void* user_data );
static void newSeg( struct whisper_context* ctx, int n_new, void* user_data );
public:
void initialize( whisper_full_params& res, const Whisper::sFullParams& rsi, Whisper::iContext* context )
{
*(uint32_t*)( &language[ 0 ] ) = rsi.language;
language[ 4 ] = '\0';
res.language = language;
newContext = context;
if( nullptr != rsi.encoder_begin_callback )
{
encoderBegin = rsi.encoder_begin_callback;
res.encoder_begin_callback = &encBegin;
res.encoder_begin_callback_user_data = rsi.encoder_begin_callback_user_data;
}
else
{
encoderBegin = nullptr;
res.encoder_begin_callback = nullptr;
res.encoder_begin_callback_user_data = nullptr;
}
if( nullptr != rsi.new_segment_callback )
{
newSegment = rsi.new_segment_callback;
res.new_segment_callback = &newSeg;
res.new_segment_callback_user_data = rsi.new_segment_callback_user_data;
}
else
{
newSegment = nullptr;
res.new_segment_callback = nullptr;
res.new_segment_callback_user_data = nullptr;
}
}
};
static thread_local NewParamsTemp npTemp;
bool NewParamsTemp::encBegin( struct whisper_context* ctx, void* user_data )
{
const NewParamsTemp& tmp = npTemp;
HRESULT hr = tmp.encoderBegin( tmp.newContext, user_data );
if( SUCCEEDED( hr ) )
return S_OK == hr;
throw hr;
}
void NewParamsTemp::newSeg( struct whisper_context* ctx, int n_new, void* user_data )
{
assert( n_new >= 0 );
const NewParamsTemp& tmp = npTemp;
HRESULT hr = tmp.newSegment( tmp.newContext, (uint32_t)n_new, user_data );
if( SUCCEEDED( hr ) )
return;
throw hr;
}
}
whisper_full_params makeOldParams( const Whisper::sFullParams& rsi, Whisper::iContext* context )
{
whisper_full_params res;
memset( &res, 0, sizeof( res ) );
res.strategy = (whisper_sampling_strategy)rsi.strategy;
res.n_threads = rsi.cpuThreads;
res.n_max_text_ctx = rsi.n_max_text_ctx;
res.offset_ms = rsi.offset_ms;
res.duration_ms = rsi.duration_ms;
// flags
const uint32_t flags = (uint32_t)rsi.flags;
auto hasFlag = [ = ]( eFullParamsFlags bit ) { return 0 != ( flags & (uint32_t)bit ); };
res.translate = hasFlag( eFullParamsFlags::Translate );
res.no_context = hasFlag( eFullParamsFlags::NoContext );
res.single_segment = hasFlag( eFullParamsFlags::SingleSegment );
res.print_special = hasFlag( eFullParamsFlags::PrintSpecial );
res.print_progress = hasFlag( eFullParamsFlags::PrintProgress );
res.print_realtime = hasFlag( eFullParamsFlags::PrintRealtime );
res.print_timestamps = hasFlag( eFullParamsFlags::PrintTimestamps );
res.token_timestamps = hasFlag( eFullParamsFlags::TokenTimestamps );
res.speed_up = hasFlag( eFullParamsFlags::SpeedupAudio );
res.thold_pt = rsi.thold_pt;
res.thold_ptsum = rsi.thold_ptsum;
res.max_len = rsi.max_len;
res.greedy.n_past = rsi.greedy.n_past;
res.beam_search.n_past = rsi.beam_search.n_past;
res.beam_search.beam_width = rsi.beam_search.beam_width;
res.beam_search.n_best = rsi.beam_search.n_best;
res.audio_ctx = rsi.audio_ctx;
res.prompt_tokens = rsi.prompt_tokens;
res.prompt_n_tokens = rsi.prompt_n_tokens;
NewParamsTemp& tmp = npTemp;
tmp.initialize( res, rsi, context );
return res;
}
#include "../Whisper/TranscribeResult.h"
#include <mfapi.h>
namespace
{
inline sTimeSpan time( int64_t wt )
{
int64_t ticks = MFllMulDiv( wt, 10'000'000, 100, 0 );
return sTimeSpan{ (uint64_t)ticks };
}
void makeNewResults( whisper_context* ctx, Whisper::eResultFlags flags, TranscribeResult& res )
{
const bool makeTokens = 0 != ( flags & eResultFlags::Tokens );
res.segments.clear();
res.tokens.clear();
const int countSegments = whisper_full_n_segments( ctx );
res.segments.resize( countSegments );
const int tokenEot = whisper_token_eot( ctx );
for( int i = 0; i < countSegments; i++ )
{
sSegment& seg = res.segments[ i ];
seg.text = whisper_full_get_segment_text( ctx, i );
seg.time.begin = time( whisper_full_get_segment_t0( ctx, i ) );
seg.time.end = time( whisper_full_get_segment_t1( ctx, i ) );
seg.firstToken = (uint32_t)res.tokens.size();
seg.countTokens = 0;
if( !makeTokens )
continue;
const int countTokens = whisper_full_n_tokens( ctx, i );
seg.countTokens = countTokens;
res.tokens.resize( res.tokens.size() + countTokens );
for( int t = 0; t < countTokens; t++ )
{
sToken& tok = res.tokens[ seg.firstToken + t ];
tok.text = whisper_full_get_token_text( ctx, i, t );
const whisper_token_data src = whisper_full_get_token_data( ctx, i, t );
tok.time.begin = time( src.t0 );
tok.time.end = time( src.t1 );
tok.probability = src.p;
tok.probabilityTimestamp = src.pt;
tok.ptsum = src.ptsum;
tok.vlen = src.vlen;
tok.id = src.id;
uint32_t flags = 0;
if( src.id >= tokenEot )
flags |= eTokenFlags::Special;
tok.flags = (eTokenFlags)flags;
}
}
}
}
HRESULT makeNewResults( whisper_context* ctx, Whisper::eResultFlags flags, Whisper::iTranscribeResult** pp )
{
static TranscribeResultStatic trs;
if( flags & eResultFlags::NewObject )
{
return E_NOTIMPL;
}
else
{
makeNewResults( ctx, flags, trs );
*pp = &trs;
( *pp )->AddRef();
return S_OK;
}
}
#endif
| 7,199
|
C++
|
.cpp
| 204
| 32.387255
| 108
| 0.714901
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,616
|
AppState.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/AppState.cpp
|
#include "stdafx.h"
#include "AppState.h"
#include "Utils/miscUtils.h"
#include <commctrl.h>
#pragma comment(lib, "Comctl32.lib")
#include "CircleIndicator.h"
namespace
{
static const HKEY regKeyRoot = HKEY_CURRENT_USER;
const LPCTSTR regKey = LR"(SOFTWARE\const.me\WhisperDesktop)";
const LPCTSTR regValPath = L"modelPath";
const LPCTSTR regValImpl = L"modelImpl";
const LPCTSTR regValLang = L"language";
const LPCTSTR regValLastScreen = L"screen";
const LPCTSTR regValGpuFlags = L"gpuFlags";
static HRESULT readString( CRegKey& k, LPCTSTR name, CString& rdi )
{
ULONG nChars = 0;
LSTATUS lss = k.QueryStringValue( name, nullptr, &nChars );
if( lss != ERROR_SUCCESS )
return HRESULT_FROM_WIN32( lss );
if( nChars == 0 )
{
rdi = L"";
return S_FALSE;
}
lss = k.QueryStringValue( name, rdi.GetBufferSetLength( nChars ), &nChars );
rdi.ReleaseBuffer();
if( lss != ERROR_SUCCESS )
return HRESULT_FROM_WIN32( lss );
return S_OK;
}
using Whisper::eModelImplementation;
}
HRESULT AppState::startup()
{
HRESULT hr = CoInitializeEx( nullptr, COINIT_MULTITHREADED );
if( FAILED( hr ) )
{
reportFatalError( "CoInitializeEx failed", hr );
return hr;
}
coInit = true;
LSTATUS lss = registryKey.Create( regKeyRoot, regKey );
if( lss != ERROR_SUCCESS )
{
hr = HRESULT_FROM_WIN32( lss );
reportFatalError( "Unable to open the registry key", hr );
return hr;
}
INITCOMMONCONTROLSEX init;
init.dwSize = sizeof( init );
init.dwICC = ICC_LINK_CLASS | ICC_PROGRESS_CLASS | ICC_STANDARD_CLASSES | ICC_TAB_CLASSES;
const BOOL icc = InitCommonControlsEx( &init );
if( !icc )
{
reportFatalError( "InitCommonControlsEx failed", HRESULT_FROM_WIN32( GetLastError() ) );
return E_FAIL;
}
hr = initMediaFoundation( &mediaFoundation );
if( FAILED( hr ) )
{
reportFatalError( "Unable to initialize Media Foundation runtime", hr );
return hr;
}
hr = console.initialize();
if( FAILED( hr ) )
{
reportFatalError( "Unable to initialize logging", hr );
return hr;
}
hr = CircleIndicator::registerClass();
if( FAILED( hr ) )
{
reportFatalError( "Unable to register custom controls", hr );
return hr;
}
appIcon.LoadIcon( IDI_WHISPERDESKTOP );
return S_OK;
}
AppState::~AppState()
{
if( coInit )
{
CoUninitialize();
coInit = false;
}
}
HRESULT AppState::findModelSource()
{
CHECK( readString( registryKey, regValPath, source.path ) );
{
CAtlFile file;
CHECK( file.Create( source.path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING ) );
ULONGLONG len;
CHECK( file.GetSize( len ) );
source.sizeInBytes = len;
}
CString impl;
CHECK( readString( registryKey, regValImpl, impl ) );
CHECK( implParse( impl, source.impl ) );
source.found = true;
return S_OK;
}
HRESULT AppState::saveModelSource()
{
LSTATUS lss = registryKey.SetStringValue( regValPath, source.path );
if( lss != ERROR_SUCCESS )
return HRESULT_FROM_WIN32( lss );
LPCTSTR impl = implString( source.impl );
if( nullptr == impl )
return E_INVALIDARG;
lss = registryKey.SetStringValue( regValImpl, impl );
if( lss != ERROR_SUCCESS )
return HRESULT_FROM_WIN32( lss );
return S_OK;
}
uint32_t AppState::languageRead()
{
DWORD dw;
LSTATUS lss = registryKey.QueryDWORDValue( regValLang, dw );
if( lss == ERROR_SUCCESS )
return dw;
return UINT_MAX;
}
void AppState::languageWrite( uint32_t key )
{
registryKey.SetDWORDValue( regValLang, key );
}
CString AppState::stringLoad( LPCTSTR name )
{
CString res;
readString( registryKey, name, res );
return res;
}
void AppState::stringStore( LPCTSTR name, LPCTSTR value )
{
if( nullptr != value )
registryKey.SetStringValue( name, value );
else
registryKey.DeleteValue( name );
}
uint32_t AppState::dwordLoad( LPCTSTR name, uint32_t fallback )
{
DWORD dw;
LSTATUS lss = registryKey.QueryDWORDValue( name, dw );
if( lss == ERROR_SUCCESS )
return dw;
return fallback;
}
void AppState::dwordStore( LPCTSTR name, uint32_t value )
{
registryKey.SetDWORDValue( name, value );
}
void AppState::lastScreenSave( HRESULT code )
{
dwordStore( regValLastScreen, (uint32_t)code );
}
HRESULT AppState::lastScreenLoad()
{
return (HRESULT)dwordLoad( regValLastScreen, SCREEN_TRANSCRIBE );
}
void AppState::setupIcon( CWindow* wnd )
{
HICON ic = appIcon;
if( nullptr != ic )
{
wnd->SendMessage( WM_SETICON, ICON_SMALL, (LPARAM)ic );
wnd->SendMessage( WM_SETICON, ICON_BIG, (LPARAM)ic );
}
}
uint32_t AppState::gpuFlagsLoad()
{
return dwordLoad( regValGpuFlags, 0 );
}
void AppState::gpuFlagsStore( uint32_t flags )
{
if( 0 == flags )
registryKey.DeleteValue( regValGpuFlags );
else
dwordStore( regValGpuFlags, flags );
}
bool AppState::boolLoad( LPCTSTR name )
{
return dwordLoad( name, 0 ) != 0;
}
void AppState::boolStore( LPCTSTR name, bool val )
{
if( val )
dwordStore( name, 1 );
else
registryKey.DeleteValue( name );
}
| 4,873
|
C++
|
.cpp
| 193
| 23.150259
| 91
| 0.730009
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,617
|
CaptureDlg.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/CaptureDlg.cpp
|
#include "stdafx.h"
#include "CaptureDlg.h"
HRESULT CaptureDlg::show()
{
auto res = DoModal( nullptr );
if( res == -1 )
return HRESULT_FROM_WIN32( GetLastError() );
switch( res )
{
case IDC_BACK:
return SCREEN_MODEL;
case IDC_TRANSCRIBE:
return SCREEN_TRANSCRIBE;
}
return S_OK;
}
static const LPCTSTR regValDevice = L"captureDevice";
static const LPCTSTR regValOutPath = L"captureTextFile";
static const LPCTSTR regValOutFormat = L"captureTextFlags";
enum struct CaptureDlg::eTextFlags : uint32_t
{
Save = 1,
Append = 2,
Timestamps = 4,
};
LRESULT CaptureDlg::OnInitDialog( UINT nMessage, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
// First DDX call, hooks up variables to controls.
DoDataExchange( false );
languageSelector.initialize( m_hWnd, IDC_LANGUAGE, appState );
cbTranslate.initialize( m_hWnd, IDC_TRANSLATE, appState );
cbConsole.initialize( m_hWnd, IDC_CONSOLE, appState );
pendingState.initialize(
// Controls to disable while pending, re-enable afterwards
{
languageSelector, GetDlgItem( IDC_TRANSLATE ),
cbCaptureDevice,
checkSave, checkAppend, checkTimestamps, transcribeOutputPath, transcribeOutputBrowse,
GetDlgItem( IDC_DEV_REFRESH ),
GetDlgItem( IDC_BACK ),
GetDlgItem( IDC_TRANSCRIBE ),
GetDlgItem( IDCANCEL ),
},
// Controls to show while pending, hide afterwards
{
voiceActivity, GetDlgItem( IDC_VOICE_ACTIVITY_LBL ),
transcribeActivity, GetDlgItem( IDC_TRANS_LBL ),
stalled, GetDlgItem( IDC_STALL_LBL ),
progressBar,
} );
stalled.setActiveColor( flipRgb( 0xffcc33 ) );
HRESULT hr = work.create( this );
if( FAILED( hr ) )
{
reportError( m_hWnd, L"CreateThreadpoolWork failed", nullptr, hr );
EndDialog( IDCANCEL );
}
listDevices();
selectDevice( appState.stringLoad( regValDevice ) );
constexpr uint32_t defaultFlags = (uint32_t)eTextFlags::Append;
uint32_t flags = appState.dwordLoad( regValOutFormat, defaultFlags );
if( flags & (uint32_t)eTextFlags::Save )
checkSave.SetCheck( BST_CHECKED );
if( flags & (uint32_t)eTextFlags::Append )
checkAppend.SetCheck( BST_CHECKED );
if( flags & (uint32_t)eTextFlags::Timestamps )
checkTimestamps.SetCheck( BST_CHECKED );
transcribeOutputPath.SetWindowText( appState.stringLoad( regValOutPath ) );
onSaveTextCheckbox();
appState.lastScreenSave( SCREEN_CAPTURE );
appState.setupIcon( this );
ATLVERIFY( CenterWindow() );
return 0;
}
HRESULT __stdcall CaptureDlg::listDevicesCallback( int len, const Whisper::sCaptureDevice* buffer, void* pv ) noexcept
{
std::vector<sCaptureDevice>& devices = *( std::vector<sCaptureDevice> * )pv;
devices.resize( len );
for( int i = 0; i < len; i++ )
{
devices[ i ].displayName = buffer[ i ].displayName;
devices[ i ].endpoint = buffer[ i ].endpoint;
}
return S_OK;
}
bool CaptureDlg::listDevices()
{
appState.mediaFoundation->listCaptureDevices( &listDevicesCallback, &devices );
cbCaptureDevice.ResetContent();
for( const auto& dev : devices )
cbCaptureDevice.AddString( dev.displayName );
return !devices.empty();
}
void CaptureDlg::onDeviceRefresh()
{
// Save the current selection
const int curSel = cbCaptureDevice.GetCurSel();
CString str;
if( curSel >= 0 && curSel < (int)devices.size() )
str = std::move( devices[ curSel ].endpoint );
// Refresh
listDevices();
// Restore the selection
selectDevice( str );
const size_t len = devices.size();
if( len == 0 )
{
MessageBox( L"No capture devices found on this computer.\nIf you have a USB microphone, connect it to this PC,\nand press “refresh” button.",
L"Capture Devices", MB_OK | MB_ICONWARNING );
}
else
{
const char* suffix = ( len != 1 ) ? "s" : "";
str.Format( L"Detected %zu audio capture device%S.", len, suffix );
MessageBox( str, L"Capture Devices", MB_OK | MB_ICONINFORMATION );
}
}
bool CaptureDlg::selectDevice( LPCTSTR endpoint )
{
if( nullptr != endpoint && 0 != *endpoint )
{
for( size_t i = 0; i < devices.size(); i++ )
{
if( devices[ i ].endpoint == endpoint )
{
cbCaptureDevice.SetCurSel( (int)i );
return true;
}
}
}
if( !devices.empty() )
cbCaptureDevice.SetCurSel( 0 );
return false;
}
void CaptureDlg::onSaveTextCheckbox()
{
const BOOL enabled = ( checkSave.GetCheck() == BST_CHECKED );
std::array<HWND, 4> controls = { checkAppend, checkTimestamps, transcribeOutputPath, transcribeOutputBrowse };
for( HWND w : controls )
::EnableWindow( w, enabled );
}
void CaptureDlg::onBrowseResult()
{
LPCTSTR title = L"Output Text File";
LPCTSTR outputFilters = L"Text files (*.txt)\0*.txt\0\0";
CString path;
transcribeOutputPath.GetWindowText( path );
if( !getSaveFileName( m_hWnd, title, outputFilters, path ) )
return;
LPCTSTR ext = PathFindExtension( path );
if( 0 == *ext )
{
wchar_t* const buffer = path.GetBufferSetLength( path.GetLength() + 5 );
PathRenameExtension( buffer, L".txt" );
path.ReleaseBuffer();
}
transcribeOutputPath.SetWindowText( path );
}
CaptureDlg::eTextFlags CaptureDlg::getOutputFlags()
{
uint32_t flags = 0;
if( checkSave.GetCheck() == BST_CHECKED )
flags |= (uint32_t)eTextFlags::Save;
if( checkAppend.GetCheck() == BST_CHECKED )
flags |= (uint32_t)eTextFlags::Append;
if( checkTimestamps.GetCheck() == BST_CHECKED )
flags |= (uint32_t)eTextFlags::Timestamps;
return (eTextFlags)flags;
}
void CaptureDlg::setPending( bool nowPending )
{
pendingState.setPending( nowPending );
if( nowPending )
{
progressBar.SetMarquee( TRUE, 0 );
btnRunCapture.SetWindowText( L"Stop" );
}
else
{
progressBar.SetMarquee( FALSE, 0 );
btnRunCapture.SetWindowText( L"Capture" );
btnRunCapture.EnableWindow( TRUE );
captureRunning = false;
}
}
void CaptureDlg::onRunCapture()
{
if( captureRunning )
{
threadState.stopRequested = true;
btnRunCapture.EnableWindow( FALSE );
return;
}
int dev = cbCaptureDevice.GetCurSel();
if( dev < 0 || dev >= (int)devices.size() )
{
showError( L"Please select a capture device", S_FALSE );
return;
}
threadState.endpoint = devices[ dev ].endpoint;
threadState.language = languageSelector.selectedLanguage();
threadState.translate = cbTranslate.checked();
if( isInvalidTranslate( m_hWnd, threadState.language, threadState.translate ) )
return;
threadState.flags = getOutputFlags();
if( (uint32_t)threadState.flags & (uint32_t)eTextFlags::Save )
{
transcribeOutputPath.GetWindowText( threadState.textOutputPath );
if( threadState.textOutputPath.GetLength() <= 0 )
{
showError( L"Please specify the output text file", S_FALSE );
return;
}
appState.stringStore( regValOutPath, threadState.textOutputPath );
}
else
cbConsole.ensureChecked();
languageSelector.saveSelection( appState );
cbTranslate.saveSelection( appState );
appState.stringStore( regValDevice, threadState.endpoint );
appState.dwordStore( regValOutFormat, (uint32_t)threadState.flags );
captureRunning = true;
threadState.errorMessage = L"";
threadState.stopRequested = false;
threadState.captureParams.minDuration = 7;
threadState.captureParams.maxDuration = 11;
setPending( true );
work.post();
}
void __declspec( noinline ) CaptureDlg::getThreadError()
{
getLastError( threadState.errorMessage );
}
#define CHECK_EX( hr ) { const HRESULT __hr = ( hr ); if( FAILED( __hr ) ) { getThreadError(); return __hr; } }
static HRESULT appendDate( CString& str, const SYSTEMTIME& time )
{
constexpr DWORD dateFlags = DATE_LONGDATE;
int cc = GetDateFormatEx( LOCALE_NAME_USER_DEFAULT, dateFlags, &time, nullptr, nullptr, 0, nullptr );
if( 0 == cc )
return getLastHr();
const int oldLength = str.GetLength();
wchar_t* const buffer = str.GetBufferSetLength( oldLength + cc );
cc = GetDateFormatEx( LOCALE_NAME_USER_DEFAULT, dateFlags, &time, nullptr, buffer + oldLength, cc, nullptr );
if( 0 != cc )
{
str.ReleaseBuffer();
return S_OK;
}
HRESULT hr = getLastHr();
str.ReleaseBuffer();
return hr;
}
static HRESULT appendTime( CString& str, const SYSTEMTIME& time )
{
constexpr DWORD timeFlags = 0;
int cc = GetTimeFormatEx( LOCALE_NAME_USER_DEFAULT, timeFlags, &time, nullptr, nullptr, 0 );
if( 0 == cc )
return getLastHr();
const int oldLength = str.GetLength();
wchar_t* const buffer = str.GetBufferSetLength( oldLength + cc );
cc = GetTimeFormatEx( LOCALE_NAME_USER_DEFAULT, timeFlags, &time, nullptr, buffer + oldLength, cc );
if( 0 != cc )
{
str.ReleaseBuffer();
return S_OK;
}
HRESULT hr = getLastHr();
str.ReleaseBuffer();
return hr;
}
static HRESULT printDateTime( CAtlFile& file )
{
SYSTEMTIME time;
GetLocalTime( &time );
CString str;
str = L"==== Captured on ";
CHECK( appendDate( str, time ) );
str += L", ";
CHECK( appendTime( str, time ) );
str += L" ====\r\n";
CStringA u8;
makeUtf8( u8, str );
return file.Write( cstr( u8 ), (DWORD)u8.GetLength() );
}
inline HRESULT CaptureDlg::runCapture()
{
clearLastError();
using namespace Whisper;
CComPtr<iAudioCapture> capture;
CHECK_EX( appState.mediaFoundation->openCaptureDevice( threadState.endpoint, threadState.captureParams, &capture ) );
HRESULT hr;
CAtlFile file;
const uint32_t flags = (uint32_t)threadState.flags;
if( flags & (uint32_t)eTextFlags::Save )
{
const bool append = 0 != ( flags & (uint32_t)eTextFlags::Append );
const DWORD creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
hr = file.Create( threadState.textOutputPath, GENERIC_WRITE, FILE_SHARE_READ, creation );
if( FAILED( hr ) )
{
threadState.errorMessage = L"Unable to create the output text file";
return hr;
}
if( append )
{
ULONGLONG size;
CHECK( file.GetSize( size ) );
if( size == 0 )
CHECK( writeUtf8Bom( file ) )
else
CHECK( file.Seek( 0, SEEK_END ) );
}
else
{
CHECK( writeUtf8Bom( file ) );
}
if( flags & (uint32_t)eTextFlags::Timestamps )
CHECK( printDateTime( file ) );
threadState.file = &file;
}
else
threadState.file = nullptr;
CComPtr<iContext> context;
CHECK_EX( appState.model->createContext( &context ) );
sFullParams fullParams;
CHECK_EX( context->fullDefaultParams( eSamplingStrategy::Greedy, &fullParams ) );
fullParams.language = threadState.language;
fullParams.setFlag( eFullParamsFlags::Translate, threadState.translate );
fullParams.resetFlag( eFullParamsFlags::PrintRealtime );
fullParams.new_segment_callback = &newSegmentCallback;
fullParams.new_segment_callback_user_data = this;
sCaptureCallbacks callbacks;
callbacks.shouldCancel = &cbCancel;
callbacks.captureStatus = &cbStatus;
callbacks.pv = this;
CHECK_EX( context->runCapture( fullParams, callbacks, capture ) );
threadState.file = nullptr;
context->timingsPrint();
return S_OK;
}
void __stdcall CaptureDlg::poolCallback() noexcept
{
const HRESULT hr = runCapture();
PostMessage( WM_CALLBACK_COMPLETION, hr );
}
void CaptureDlg::showError( LPCTSTR text, HRESULT hr )
{
reportError( m_hWnd, text, L"Capture failed", hr );
}
LRESULT CaptureDlg::onThreadQuit( UINT nMessage, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
setPending( false );
const HRESULT hr = (HRESULT)wParam;
if( FAILED( hr ) )
{
LPCTSTR failMessage = L"Capture failed";
if( threadState.errorMessage.GetLength() > 0 )
{
CString tmp = failMessage;
tmp += L"\n";
tmp += threadState.errorMessage;
showError( tmp, hr );
}
else
showError( failMessage, hr );
return 0;
}
else
{
if( (uint32_t)threadState.flags & (uint32_t)eTextFlags::Save )
ShellExecute( NULL, L"open", threadState.textOutputPath, NULL, NULL, SW_SHOW );
}
return 0;
}
LRESULT CaptureDlg::onThreadStatus( UINT nMessage, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
using namespace Whisper;
const uint8_t newStatus = (uint8_t)wParam;
// Update the GUI
voiceActivity.setActive( 0 != ( newStatus & (uint8_t)eCaptureStatus::Voice ) );
transcribeActivity.setActive( 0 != ( newStatus & (uint8_t)eCaptureStatus::Transcribing ) );
stalled.setActive( 0 != ( newStatus & (uint8_t)eCaptureStatus::Stalled ) );
return 0;
}
HRESULT __stdcall CaptureDlg::cbCancel( void* pv ) noexcept
{
const bool stopRequested = ( (CaptureDlg*)pv )->threadState.stopRequested;
return stopRequested ? S_FALSE : S_OK;
}
HRESULT __stdcall CaptureDlg::cbStatus( void* pv, Whisper::eCaptureStatus status ) noexcept
{
CaptureDlg& dialog = *(CaptureDlg*)pv;
if( dialog.PostMessage( WM_CALLBACK_STATUS, (uint8_t)status ) )
return S_OK;
return getLastHr();
}
HRESULT __cdecl CaptureDlg::newSegmentCallback( Whisper::iContext* ctx, uint32_t n_new, void* user_data ) noexcept
{
using namespace Whisper;
CComPtr<iTranscribeResult> result;
const eResultFlags flags = eResultFlags::Timestamps | eResultFlags::Tokens;
CHECK( ctx->getResults( flags, &result ) );
CHECK( logNewSegments( result, n_new ) );
CaptureDlg& dialog = *(CaptureDlg*)user_data;
return dialog.appendTextFile( result, n_new );
}
HRESULT CaptureDlg::appendTextFile( Whisper::iTranscribeResult* results, uint32_t newSegments )
{
if( nullptr == threadState.file || 0 == newSegments )
return S_OK;
using namespace Whisper;
sTranscribeLength length;
CHECK( results->getSize( length ) );
const size_t len = length.countSegments;
size_t i = len - newSegments;
const sSegment* const segments = results->getSegments();
CStringA str;
for( ; i < len; i++ )
{
const sSegment& seg = segments[ i ];
if( 0 != ( (uint32_t)threadState.flags & (uint32_t)eTextFlags::Timestamps ) )
{
str = "[";
printTime( str, seg.time.begin );
str += " --> ";
printTime( str, seg.time.end );
str += "] ";
}
else
str = "";
str += seg.text;
str += "\r\n";
CHECK( threadState.file->Write( cstr( str ), (DWORD)str.GetLength() ) );
}
CHECK( threadState.file->Flush() );
return S_OK;
}
| 13,694
|
C++
|
.cpp
| 437
| 28.965675
| 143
| 0.728658
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,618
|
CircleIndicator.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/CircleIndicator.cpp
|
#include "stdafx.h"
#include "CircleIndicator.h"
#include <atltypes.h>
#include "AppState.h"
namespace
{
static const LPCTSTR windowClassName = L"CircleIndicator";
// Font with these symbols, shipped with Windows since forever:
// https://learn.microsoft.com/en-us/typography/font-list/segoe-ui-symbol
static const LPCTSTR fontName = L"Segoe UI Symbol";
// Outlined circle
static const LPCTSTR circleOutline = L"⚪";
// Filled circle
static const LPCTSTR circleFilled = L"⚫";
// Font size for that symbol font, in points
constexpr int fontSizePoints = 14;
// Default active color for the indicator
constexpr uint32_t defaultActiveColor = 0x7FFF7F;
}
CircleIndicator::CircleIndicator() :
activeColor( defaultActiveColor )
{ }
ATL::CWndClassInfo& CircleIndicator::GetWndClassInfo()
{
// Use custom class style with CS_PARENTDC, and COLOR_3DFACE for the background
static ATL::CWndClassInfo wc =
{
{ sizeof( WNDCLASSEX ),
CS_HREDRAW | CS_VREDRAW | CS_PARENTDC,
StartWindowProc,
0, 0, NULL, NULL, NULL, (HBRUSH)( COLOR_3DFACE + 1 ), NULL, windowClassName, NULL },
NULL, NULL, IDC_ARROW, TRUE, 0, _T( "" )
};
return wc;
}
// Class registration
HRESULT CircleIndicator::registerClass()
{
WNDPROC pUnusedWndSuperProc = nullptr;
ATOM a = GetWndClassInfo().Register( &pUnusedWndSuperProc );
if( 0 != a )
return S_OK;
return getLastHr();
}
HRESULT CircleIndicator::createFont( int height )
{
LOGFONT logFont;
memset( &logFont, 0, sizeof( logFont ) );
logFont.lfHeight = height;
logFont.lfCharSet = ANSI_CHARSET;
logFont.lfOutPrecision = OUT_TT_PRECIS;
logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
wcsncpy_s( logFont.lfFaceName, fontName, _TRUNCATE );
font.CreateFontIndirect( &logFont );
if( font )
return S_OK;
return E_FAIL;
}
void CircleIndicator::onDestroy()
{
if( font )
font.DeleteObject();
}
void CircleIndicator::onPaint( CDCHandle dc )
{
CRect rectInt32;
GetClientRect( &rectInt32 );
CPaintDC pdc( m_hWnd );
const int logPixels = pdc.GetDeviceCaps( LOGPIXELSY );
int fontSize = -MulDiv( fontSizePoints, logPixels, 72 );
if( !font || fontHeight != fontSize )
{
if( font )
font.DeleteObject();
HRESULT hr = createFont( fontSize );
if( FAILED( hr ) )
return;
fontHeight = fontSize;
}
pdc.SetBkColor( GetSysColor( COLOR_3DFACE ) );
pdc.SelectFont( font );
pdc.SetBkMode( OPAQUE );
constexpr UINT textFormat = DT_CENTER | DT_VCENTER;
if( isActive )
{
pdc.SetTextColor( activeColor );
pdc.DrawText( circleFilled, 1, rectInt32, textFormat );
pdc.SetBkMode( TRANSPARENT );
}
pdc.SetTextColor( 0 );
pdc.DrawText( circleOutline, 1, rectInt32, textFormat );
}
void CircleIndicator::setActive( bool nowActive )
{
if( nowActive == isActive )
return;
// Repaint the control
isActive = nowActive;
InvalidateRect( nullptr );
}
| 2,828
|
C++
|
.cpp
| 100
| 26.11
| 86
| 0.745562
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,619
|
TranscribeDlg.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/TranscribeDlg.cpp
|
#include "stdafx.h"
#include "TranscribeDlg.h"
#include "Utils/logger.h"
HRESULT TranscribeDlg::show()
{
auto res = DoModal( nullptr );
if( res == -1 )
return HRESULT_FROM_WIN32( GetLastError() );
switch( res )
{
case IDC_BACK:
return SCREEN_MODEL;
case IDC_CAPTURE:
return SCREEN_CAPTURE;
}
return S_OK;
}
constexpr int progressMaxInteger = 1024 * 8;
static const LPCTSTR regValInput = L"sourceMedia";
static const LPCTSTR regValOutFormat = L"resultFormat";
static const LPCTSTR regValOutPath = L"resultPath";
static const LPCTSTR regValUseInputFolder = L"useInputFolder";
LRESULT TranscribeDlg::OnInitDialog( UINT nMessage, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
// First DDX call, hooks up variables to controls.
DoDataExchange( false );
printModelDescription();
languageSelector.initialize( m_hWnd, IDC_LANGUAGE, appState );
cbConsole.initialize( m_hWnd, IDC_CONSOLE, appState );
cbTranslate.initialize( m_hWnd, IDC_TRANSLATE, appState );
populateOutputFormats();
pendingState.initialize(
{
languageSelector, GetDlgItem( IDC_TRANSLATE ),
sourceMediaPath, GetDlgItem( IDC_BROWSE_MEDIA ),
transcribeOutFormat, useInputFolder,
transcribeOutputPath, GetDlgItem( IDC_BROWSE_RESULT ),
GetDlgItem( IDCANCEL ),
GetDlgItem( IDC_BACK ),
GetDlgItem( IDC_CAPTURE )
},
{
progressBar, GetDlgItem( IDC_PENDING_TEXT )
} );
HRESULT hr = work.create( this );
if( FAILED( hr ) )
{
reportError( m_hWnd, L"CreateThreadpoolWork failed", nullptr, hr );
EndDialog( IDCANCEL );
}
progressBar.SetRange32( 0, progressMaxInteger );
progressBar.SetStep( 1 );
sourceMediaPath.SetWindowText( appState.stringLoad( regValInput ) );
transcribeOutFormat.SetCurSel( (int)appState.dwordLoad( regValOutFormat, 0 ) );
transcribeOutputPath.SetWindowText( appState.stringLoad( regValOutPath ) );
if( appState.boolLoad( regValUseInputFolder ) )
useInputFolder.SetCheck( BST_CHECKED );
BOOL unused;
onOutFormatChange( 0, 0, nullptr, unused );
appState.lastScreenSave( SCREEN_TRANSCRIBE );
appState.setupIcon( this );
ATLVERIFY( CenterWindow() );
return 0;
}
void TranscribeDlg::printModelDescription()
{
CString text;
if( S_OK == appState.model->isMultilingual() )
text = L"Multilingual";
else
text = L"Single-language";
text += L" model \"";
LPCTSTR path = appState.source.path;
path = ::PathFindFileName( path );
text += path;
text += L"\", ";
const int64_t cb = appState.source.sizeInBytes;
if( cb < 1 << 30 )
{
constexpr double mul = 1.0 / ( 1 << 20 );
double mb = (double)cb * mul;
text.AppendFormat( L"%.1f MB", mb );
}
else
{
constexpr double mul = 1.0 / ( 1 << 30 );
double gb = (double)cb * mul;
text.AppendFormat( L"%.2f GB", gb );
}
text += L" on disk, ";
text += implString( appState.source.impl );
text += L" implementation";
modelDesc.SetWindowText( text );
}
// Populate the "Output Format" combobox
void TranscribeDlg::populateOutputFormats()
{
transcribeOutFormat.AddString( L"None" );
transcribeOutFormat.AddString( L"Text file" );
transcribeOutFormat.AddString( L"Text with timestamps" );
transcribeOutFormat.AddString( L"SubRip subtitles" );
transcribeOutFormat.AddString( L"WebVTT subtitles" );
}
// The enum values should match 0-based indices of the combobox items
enum struct TranscribeDlg::eOutputFormat : uint8_t
{
None = 0,
Text = 1,
TextTimestamps = 2,
SubRip = 3,
WebVTT = 4,
};
enum struct TranscribeDlg::eVisualState : uint8_t
{
Idle = 0,
Running = 1,
Stopping = 2
};
// CBN_SELCHANGE notification for IDC_OUTPUT_FORMAT combobox
LRESULT TranscribeDlg::onOutFormatChange( UINT, INT, HWND, BOOL& bHandled )
{
BOOL enabled = transcribeOutFormat.GetCurSel() != 0;
useInputFolder.EnableWindow( enabled );
if( isChecked( useInputFolder ) && enabled )
{
enabled = FALSE;
setOutputPath();
}
transcribeOutputPath.EnableWindow( enabled );
transcribeOutputBrowse.EnableWindow( enabled );
return 0;
}
// EN_CHANGE notification for IDC_PATH_MEDIA edit box
LRESULT TranscribeDlg::onInputChange( UINT, INT, HWND, BOOL& )
{
if( !useInputFolder.IsWindowEnabled() )
return 0;
if( !isChecked( useInputFolder ) )
return 0;
setOutputPath();
return 0;
}
void TranscribeDlg::onBrowseMedia()
{
LPCTSTR title = L"Input audio file to transcribe";
LPCTSTR filters = L"Multimedia Files\0*.wav;*.wave;*.mp3;*.wma;*.mp4;*.mpeg4;*.mkv;*.m4a\0\0";
CString path;
sourceMediaPath.GetWindowText( path );
if( !getOpenFileName( m_hWnd, title, filters, path ) )
return;
sourceMediaPath.SetWindowText( path );
if( useInputFolder.IsWindowEnabled() && useInputFolder.GetCheck() == BST_CHECKED )
setOutputPath( path );
}
static const LPCTSTR outputFilters = L"Text files (*.txt)\0*.txt\0Text with timestamps (*.txt)\0*.txt\0SubRip subtitles (*.srt)\0*.srt\0WebVTT subtitles (*.vtt)\0*.vtt\0\0";
static const std::array<LPCTSTR, 4> outputExtensions =
{
L".txt", L".txt", L".srt", L".vtt"
};
void TranscribeDlg::setOutputPath( const CString& input )
{
const int format = transcribeOutFormat.GetCurSel() - 1;
if( format < 0 || format >= outputExtensions.size() )
return;
const LPCTSTR ext = outputExtensions[ format ];
CString path = input;
path.Trim();
const bool renamed = PathRenameExtension( path.GetBufferSetLength( path.GetLength() + 4 ), ext );
path.ReleaseBuffer();
if( !renamed )
return;
transcribeOutputPath.SetWindowText( path );
}
void TranscribeDlg::setOutputPath()
{
CString path;
if( !sourceMediaPath.GetWindowText( path ) )
return;
if( path.GetLength() <= 0 )
return;
setOutputPath( path );
}
void TranscribeDlg::onInputFolderCheck()
{
const bool checked = isChecked( useInputFolder );
BOOL enableOutput = checked ? FALSE : TRUE;
transcribeOutputPath.EnableWindow( enableOutput );
transcribeOutputBrowse.EnableWindow( enableOutput );
if( !checked )
return;
setOutputPath();
}
void TranscribeDlg::onBrowseOutput()
{
const DWORD origFilterIndex = (DWORD)transcribeOutFormat.GetCurSel() - 1;
LPCTSTR title = L"Output Text File";
CString path;
transcribeOutputPath.GetWindowText( path );
DWORD filterIndex = origFilterIndex;
if( !getSaveFileName( m_hWnd, title, outputFilters, path, &filterIndex ) )
return;
LPCTSTR ext = PathFindExtension( path );
if( 0 == *ext && filterIndex < outputExtensions.size() )
{
wchar_t* const buffer = path.GetBufferSetLength( path.GetLength() + 5 );
PathRenameExtension( buffer, outputExtensions[ filterIndex ] );
path.ReleaseBuffer();
}
transcribeOutputPath.SetWindowText( path );
if( filterIndex != origFilterIndex )
transcribeOutFormat.SetCurSel( filterIndex + 1 );
}
void TranscribeDlg::setPending( bool nowPending )
{
pendingState.setPending( nowPending );
}
void TranscribeDlg::transcribeError( LPCTSTR text, HRESULT hr )
{
reportError( m_hWnd, text, L"Unable to transcribe audio", hr );
}
void TranscribeDlg::onTranscribe()
{
switch( transcribeArgs.visualState )
{
case eVisualState::Running:
transcribeArgs.visualState = eVisualState::Stopping;
transcribeButton.EnableWindow( FALSE );
return;
case eVisualState::Stopping:
return;
}
// Validate input
sourceMediaPath.GetWindowText( transcribeArgs.pathMedia );
if( transcribeArgs.pathMedia.GetLength() <= 0 )
{
transcribeError( L"Please select an input audio file" );
return;
}
if( !PathFileExists( transcribeArgs.pathMedia ) )
{
transcribeError( L"Input audio file does not exist", HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND ) );
return;
}
transcribeArgs.language = languageSelector.selectedLanguage();
transcribeArgs.translate = cbTranslate.checked();
if( isInvalidTranslate( m_hWnd, transcribeArgs.language, transcribeArgs.translate ) )
return;
transcribeArgs.format = (eOutputFormat)(uint8_t)transcribeOutFormat.GetCurSel();
if( transcribeArgs.format != eOutputFormat::None )
{
transcribeOutputPath.GetWindowText( transcribeArgs.pathOutput );
if( transcribeArgs.pathOutput.GetLength() <= 0 )
{
transcribeError( L"Please select an output text file" );
return;
}
if( PathFileExists( transcribeArgs.pathOutput ) )
{
const int resp = MessageBox( L"The output file is already there.\nOverwrite the file?", L"Confirm Overwrite", MB_ICONQUESTION | MB_YESNO );
if( resp != IDYES )
return;
}
appState.stringStore( regValOutPath, transcribeArgs.pathOutput );
}
else
cbConsole.ensureChecked();
appState.dwordStore( regValOutFormat, (uint32_t)(int)transcribeArgs.format );
appState.boolStore( regValUseInputFolder, isChecked( useInputFolder ) );
languageSelector.saveSelection( appState );
cbTranslate.saveSelection( appState );
appState.stringStore( regValInput, transcribeArgs.pathMedia );
setPending( true );
transcribeArgs.visualState = eVisualState::Running;
transcribeButton.SetWindowText( L"Stop" );
work.post();
}
void __stdcall TranscribeDlg::poolCallback() noexcept
{
HRESULT hr = transcribe();
PostMessage( WM_CALLBACK_STATUS, (WPARAM)hr );
}
static void printTime( CString& rdi, int64_t ticks )
{
const Whisper::sTimeSpan ts{ (uint64_t)ticks };
const Whisper::sTimeSpanFields fields = ts;
if( fields.days != 0 )
{
rdi.AppendFormat( L"%i days, %i hours", fields.days, (int)fields.hours );
return;
}
if( ( fields.hours | fields.minutes ) != 0 )
{
rdi.AppendFormat( L"%02d:%02d:%02d", (int)fields.hours, (int)fields.minutes, (int)fields.seconds );
return;
}
rdi.AppendFormat( L"%.3f seconds", (double)ticks / 1E7 );
}
LRESULT TranscribeDlg::onCallbackStatus( UINT, WPARAM wParam, LPARAM, BOOL& bHandled )
{
setPending( false );
transcribeButton.SetWindowText( L"Transcribe" );
transcribeButton.EnableWindow( TRUE );
const bool prematurely = ( transcribeArgs.visualState == eVisualState::Stopping );
transcribeArgs.visualState = eVisualState::Idle;
const HRESULT hr = (HRESULT)wParam;
if( FAILED( hr ) )
{
LPCTSTR failMessage = L"Transcribe failed";
if( transcribeArgs.errorMessage.GetLength() > 0 )
{
CString tmp = failMessage;
tmp += L"\n";
tmp += transcribeArgs.errorMessage;
transcribeError( tmp, hr );
}
else
transcribeError( failMessage, hr );
return 0;
}
const int64_t elapsed = ( GetTickCount64() - transcribeArgs.startTime ) * 10'000;
const int64_t media = transcribeArgs.mediaDuration;
CString message;
if( prematurely )
message = L"Transcribed an initial portion of the audio";
else
message = L"Transcribed the audio";
message += L"\nMedia duration: ";
printTime( message, media );
message += L"\nProcessing time: ";
printTime( message, elapsed );
message += L"\nRelative processing speed: ";
double mul = (double)media / (double)elapsed;
message.AppendFormat( L"%g", mul );
MessageBox( message, L"Transcribe Completed", MB_OK | MB_ICONINFORMATION );
return 0;
}
void TranscribeDlg::getThreadError()
{
getLastError( transcribeArgs.errorMessage );
}
#define CHECK_EX( hr ) { const HRESULT __hr = ( hr ); if( FAILED( __hr ) ) { getThreadError(); return __hr; } }
HRESULT TranscribeDlg::transcribe()
{
transcribeArgs.startTime = GetTickCount64();
clearLastError();
transcribeArgs.errorMessage = L"";
using namespace Whisper;
CComPtr<iAudioReader> reader;
CHECK_EX( appState.mediaFoundation->openAudioFile( transcribeArgs.pathMedia, false, &reader ) );
const eOutputFormat format = transcribeArgs.format;
CAtlFile outputFile;
if( format != eOutputFormat::None )
CHECK( outputFile.Create( transcribeArgs.pathOutput, GENERIC_WRITE, 0, CREATE_ALWAYS ) );
transcribeArgs.resultFlags = eResultFlags::Timestamps | eResultFlags::Tokens;
CComPtr<iContext> context;
CHECK_EX( appState.model->createContext( &context ) );
sFullParams fullParams;
CHECK_EX( context->fullDefaultParams( eSamplingStrategy::Greedy, &fullParams ) );
fullParams.language = transcribeArgs.language;
fullParams.setFlag( eFullParamsFlags::Translate, transcribeArgs.translate );
fullParams.resetFlag( eFullParamsFlags::PrintRealtime );
// Setup the callbacks
fullParams.new_segment_callback = &newSegmentCallbackStatic;
fullParams.new_segment_callback_user_data = this;
fullParams.encoder_begin_callback = &encoderBeginCallback;
fullParams.encoder_begin_callback_user_data = this;
// Setup the progress indication sink
sProgressSink progressSink{ &progressCallbackStatic, this };
// Run the transcribe
CHECK_EX( context->runStreamed( fullParams, progressSink, reader ) );
// Once finished, query duration of the audio.
// The duration before the processing is sometimes different, by 20 seconds for the file in that issue:
// https://github.com/Const-me/Whisper/issues/4
CHECK_EX( reader->getDuration( transcribeArgs.mediaDuration ) );
context->timingsPrint();
if( format == eOutputFormat::None )
return S_OK;
CComPtr<iTranscribeResult> result;
CHECK_EX( context->getResults( transcribeArgs.resultFlags, &result ) );
sTranscribeLength len;
CHECK_EX( result->getSize( len ) );
const sSegment* const segments = result->getSegments();
switch( format )
{
case eOutputFormat::Text:
return writeTextFile( segments, len.countSegments, outputFile, false );
case eOutputFormat::TextTimestamps:
return writeTextFile( segments, len.countSegments, outputFile, true );
case eOutputFormat::SubRip:
return writeSubRip( segments, len.countSegments, outputFile );
case eOutputFormat::WebVTT:
return writeWebVTT( segments, len.countSegments, outputFile );
default:
return E_FAIL;
}
}
#undef CHECK_EX
inline HRESULT TranscribeDlg::progressCallback( double p ) noexcept
{
constexpr double mul = progressMaxInteger;
int pos = lround( mul * p );
progressBar.PostMessage( PBM_SETPOS, pos, 0 );
return S_OK;
}
HRESULT __cdecl TranscribeDlg::progressCallbackStatic( double p, Whisper::iContext* ctx, void* pv ) noexcept
{
TranscribeDlg* dlg = (TranscribeDlg*)pv;
return dlg->progressCallback( p );
}
namespace
{
HRESULT write( CAtlFile& file, const CStringA& line )
{
if( line.GetLength() > 0 )
CHECK( file.Write( cstr( line ), (DWORD)line.GetLength() ) );
return S_OK;
}
const char* skipBlank( const char* rsi )
{
while( true )
{
const char c = *rsi;
if( c == ' ' || c == '\t' )
{
rsi++;
continue;
}
return rsi;
}
}
}
using Whisper::sSegment;
HRESULT TranscribeDlg::writeTextFile( const sSegment* const segments, const size_t length, CAtlFile& file, bool timestamps )
{
using namespace Whisper;
CHECK( writeUtf8Bom( file ) );
CStringA line;
for( size_t i = 0; i < length; i++ )
{
const sSegment& seg = segments[ i ];
if( timestamps )
{
line = "[";
printTime( line, seg.time.begin );
line += " --> ";
printTime( line, seg.time.end );
line += "] ";
}
else
line = "";
line += skipBlank( seg.text );
line += "\r\n";
CHECK( write( file, line ) );
}
return S_OK;
}
HRESULT TranscribeDlg::writeSubRip( const sSegment* const segments, const size_t length, CAtlFile& file )
{
CHECK( writeUtf8Bom( file ) );
CStringA line;
for( size_t i = 0; i < length; i++ )
{
const sSegment& seg = segments[ i ];
line.Format( "%zu\r\n", i + 1 );
printTime( line, seg.time.begin, true );
line += " --> ";
printTime( line, seg.time.end, true );
line += "\r\n";
line += skipBlank( seg.text );
line += "\r\n\r\n";
CHECK( write( file, line ) );
}
return S_OK;
}
HRESULT TranscribeDlg::writeWebVTT( const sSegment* const segments, const size_t length, CAtlFile& file )
{
CHECK( writeUtf8Bom( file ) );
CStringA line;
line = "WEBVTT\r\n\r\n";
CHECK( write( file, line ) );
for( size_t i = 0; i < length; i++ )
{
const sSegment& seg = segments[ i ];
line = "";
printTime( line, seg.time.begin, false );
line += " --> ";
printTime( line, seg.time.end, false );
line += "\r\n";
line += skipBlank( seg.text );
line += "\r\n\r\n";
CHECK( write( file, line ) );
}
return S_OK;
}
inline HRESULT TranscribeDlg::newSegmentCallback( Whisper::iContext* ctx, uint32_t n_new )
{
using namespace Whisper;
CComPtr<iTranscribeResult> result;
CHECK( ctx->getResults( transcribeArgs.resultFlags, &result ) );
return logNewSegments( result, n_new );
}
HRESULT __cdecl TranscribeDlg::newSegmentCallbackStatic( Whisper::iContext* ctx, uint32_t n_new, void* user_data ) noexcept
{
TranscribeDlg* dlg = (TranscribeDlg*)user_data;
return dlg->newSegmentCallback( ctx, n_new );
}
HRESULT __cdecl TranscribeDlg::encoderBeginCallback( Whisper::iContext* ctx, void* user_data ) noexcept
{
TranscribeDlg* dlg = (TranscribeDlg*)user_data;
const eVisualState visualState = dlg->transcribeArgs.visualState;
switch( visualState )
{
case eVisualState::Idle:
return E_NOT_VALID_STATE;
case eVisualState::Running:
return S_OK;
case eVisualState::Stopping:
return S_FALSE;
default:
return E_UNEXPECTED;
}
}
void TranscribeDlg::onWmClose()
{
if( GetDlgItem( IDCANCEL ).IsWindowEnabled() )
{
EndDialog( IDCANCEL );
return;
}
constexpr UINT flags = MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2;
const int res = this->MessageBox( L"Transcribe is in progress.\nDo you want to quit anyway?", L"Confirm exit", flags );
if( res != IDYES )
return;
// TODO: instead of ExitProcess(), implement another callback in the DLL API, for proper cancellation of the background task
ExitProcess( 1 );
}
| 17,200
|
C++
|
.cpp
| 536
| 29.811567
| 173
| 0.740334
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,620
|
ModelAdvancedDlg.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/ModelAdvancedDlg.cpp
|
#include "stdafx.h"
#include "ModelAdvancedDlg.h"
using Whisper::eGpuModelFlags;
static void __stdcall addGpu( const wchar_t* name, void* pv )
{
CComboBox& cb = *(CComboBox*)pv;
cb.AddString( name );
}
LRESULT ModelAdvancedDlg::onInitDialog( UINT nMessage, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
cbWave = GetDlgItem( IDC_WAVE );
cbReshapedMatMul = GetDlgItem( IDC_RESHAPED_MAT_MUL );
cbAdapter = GetDlgItem( IDC_GPU );
const uint32_t flags = appState.gpuFlagsLoad();
// Setup the "Compute shaders" combobox
cbWave.AddString( L"Wave64 shaders on AMD" );
cbWave.AddString( L"Wave32, always" );
cbWave.AddString( L"Wave64, always" );
int i = 0;
if( 0 != ( flags & (uint32_t)eGpuModelFlags::Wave32 ) )
i = 1;
else if( 0 != ( flags & (uint32_t)eGpuModelFlags::Wave64 ) )
i = 2;
cbWave.SetCurSel( i );
// Setup the "Reshaped multiply" combobox
cbReshapedMatMul.AddString( L"Reshape on AMD" );
cbReshapedMatMul.AddString( L"Don’t reshape tensors" );
cbReshapedMatMul.AddString( L"Reshape some tensors" );
i = 0;
if( 0 != ( flags & (uint32_t)eGpuModelFlags::NoReshapedMatMul ) )
i = 1;
else if( 0 != ( flags & (uint32_t)eGpuModelFlags::UseReshapedMatMul ) )
i = 2;
cbReshapedMatMul.SetCurSel( i );
cbAdapter.AddString( L"Use default" );
HRESULT hr = Whisper::listGPUs( &addGpu, &cbAdapter );
if( FAILED( hr ) )
{
reportError( m_hWnd, L"Unable to enumerate GPUs", L"", hr );
return 0;
}
const CString setting = appState.stringLoad( L"gpu" );
if( setting.GetLength() <= 0 )
cbAdapter.SetCurSel( 0 );
else
cbAdapter.SetCurSel( cbAdapter.FindStringExact( 1, setting ) );
return 0;
}
bool ModelAdvancedDlg::show( HWND owner )
{
auto res = DoModal( owner );
return res == IDOK;
}
void ModelAdvancedDlg::onOk()
{
// Gather values from these comboboxes
uint32_t flags = 0;
int i = cbWave.GetCurSel();
if( 1 == i )
flags |= (uint32_t)eGpuModelFlags::Wave32;
else if( 2 == i )
flags |= (uint32_t)eGpuModelFlags::Wave64;
i = cbReshapedMatMul.GetCurSel();
if( 1 == i )
flags |= (uint32_t)eGpuModelFlags::NoReshapedMatMul;
else if( 2 == i )
flags |= (uint32_t)eGpuModelFlags::UseReshapedMatMul;
// Save to registry
appState.gpuFlagsStore( flags );
int gpuIndex = cbAdapter.GetCurSel();
if( gpuIndex <= 0 )
appState.stringStore( L"gpu", nullptr );
else
{
CString gpu;
cbAdapter.GetLBText( gpuIndex, gpu );
appState.stringStore( L"gpu", gpu );
}
EndDialog( IDOK );
}
| 2,452
|
C++
|
.cpp
| 80
| 28.425
| 101
| 0.708705
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,621
|
LoadModelDlg.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/LoadModelDlg.cpp
|
#include "stdafx.h"
#include "LoadModelDlg.h"
#include "Utils/miscUtils.h"
#include "Utils/logger.h"
#include "ModelAdvancedDlg.h"
constexpr int progressMaxInteger = 1024 * 8;
HRESULT LoadModelDlg::show()
{
auto res = DoModal( nullptr );
if( res == -1 )
return HRESULT_FROM_WIN32( GetLastError() );
if( res == IDOK )
{
HRESULT hr = appState.lastScreenLoad();
switch( hr )
{
case SCREEN_TRANSCRIBE:
case SCREEN_CAPTURE:
return hr;
default:
return SCREEN_TRANSCRIBE;
}
}
return S_OK;
}
LRESULT LoadModelDlg::OnInitDialog( UINT nMessage, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
// First DDX call, hooks up variables to controls.
DoDataExchange( false );
cbConsole.initialize( m_hWnd, IDC_CONSOLE, appState );
implPopulateCombobox( cbModelType, appState.source.impl );
modelPath.SetWindowTextW( appState.source.path );
HRESULT hr = work.create( this );
if( FAILED( hr ) )
{
CString text = L"CreateThreadpoolWork failed\n";
text += formatErrorMessage( hr );
::MessageBox( m_hWnd, text, L"Unable to load the model", MB_OK | MB_ICONWARNING );
return TRUE;
}
editorsWindows.reserve( 6 );
editorsWindows = { modelPath, cbModelType, GetDlgItem( IDC_BROWSE ), GetDlgItem( IDC_MODEL_ADV ), GetDlgItem( IDOK ), GetDlgItem( IDCANCEL ) };
pendingWindows.reserve( 2 );
pendingWindows = { GetDlgItem( IDC_PENDING_TEXT ), progressBar };
progressBar.SetRange32( 0, progressMaxInteger );
progressBar.SetStep( 1 );
appState.setupIcon( this );
ATLVERIFY( CenterWindow() );
if( !appState.source.found || !appState.automaticallyLoadModel )
return 0;
// AppState.findModelSource() method has located model parameters in registry;
// Post a notification identical to the "OK" button click event.
PostMessage( WM_COMMAND, IDOK, (LPARAM)( GetDlgItem( IDOK ).m_hWnd ) );
return 0;
}
LRESULT LoadModelDlg::OnBrowse( UINT, INT, HWND, BOOL& bHandled )
{
bHandled = TRUE;
CString path;
modelPath.GetWindowText( path );
if( !getOpenFileName( m_hWnd, L"Select a GGML Model File", L"Binary files (*.bin)\0*.bin\0\0", path ) )
return 0;
modelPath.SetWindowText( path );
appState.source.path = path;
return 0;
}
LRESULT LoadModelDlg::validationError( LPCTSTR message )
{
reportError( m_hWnd, message, L"Unable to load the model" );
return 0;
}
LRESULT LoadModelDlg::validationError( LPCTSTR message, HRESULT hr )
{
reportError( m_hWnd, message, L"Unable to load the model", hr );
return 0;
}
void LoadModelDlg::setPending( bool nowPending )
{
const BOOL enable = nowPending ? FALSE : TRUE;
for( HWND w : editorsWindows )
::EnableWindow( w, enable );
const int show = nowPending ? SW_NORMAL : SW_HIDE;
for( HWND w : pendingWindows )
::ShowWindow( w, show );
if( nowPending )
progressBar.SetMarquee( TRUE, 0 );
else
progressBar.SetMarquee( FALSE, 0 );
}
LRESULT LoadModelDlg::OnOk( UINT, INT, HWND, BOOL& bHandled )
{
modelPath.GetWindowText( path );
if( path.GetLength() <= 0 )
return validationError( L"Please select a model GGML file" );
{
CAtlFile file;
HRESULT hr = file.Create( path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING );
if( FAILED( hr ) )
return validationError( L"Unable to open the model file", hr );
ULONGLONG cb = 0;
file.GetSize( cb );
appState.source.sizeInBytes = cb;
}
impl = implGetValue( cbModelType );
if( impl == (Whisper::eModelImplementation)0 )
return validationError( L"Please select a model type" );
setPending( true );
work.post();
return 0;
}
static HRESULT loadModel( const wchar_t* path, Whisper::sModelSetup setup, const Whisper::sLoadModelCallbacks* callbacks, Whisper::iModel** pp )
{
constexpr bool dbgTestClone = false;
if constexpr( dbgTestClone )
setup.flags |= (uint32_t)Whisper::eGpuModelFlags::Cloneable;
CComPtr<Whisper::iModel> res;
CHECK( Whisper::loadModel( path, setup, callbacks, &res ) );
if constexpr( dbgTestClone )
{
CComPtr<Whisper::iModel> clone;
CHECK( res->clone( &clone ) );
*pp = clone.Detach();
return S_OK;
}
else
{
*pp = res.Detach();
return S_OK;
}
}
void __stdcall LoadModelDlg::poolCallback() noexcept
{
CComPtr<Whisper::iModel> model;
clearLastError();
loadError = L"";
Whisper::sLoadModelCallbacks lmcb;
lmcb.cancel = nullptr;
lmcb.progress = &LoadModelDlg::progressCallback;
lmcb.pv = this;
Whisper::sModelSetup setup;
setup.impl = impl;
setup.flags = appState.gpuFlagsLoad();
CString adapter = appState.stringLoad( L"gpu" );
setup.adapter = adapter;
HRESULT hr = ::loadModel( path, setup, &lmcb, &model );
if( SUCCEEDED( hr ) )
appState.model = model;
else
getLastError( loadError );
this->PostMessage( WM_CALLBACK_STATUS, (WPARAM)hr );
}
HRESULT __stdcall LoadModelDlg::progressCallback( double val, void* pv ) noexcept
{
LoadModelDlg& dialog = *(LoadModelDlg*)pv;
constexpr double mul = progressMaxInteger;
int pos = lround( mul * val );
dialog.progressBar.PostMessage( PBM_SETPOS, pos, 0 );
return S_OK;
}
LRESULT LoadModelDlg::OnCallbackStatus( UINT, WPARAM wParam, LPARAM, BOOL& bHandled )
{
setPending( false );
bHandled = TRUE;
const HRESULT hr = (HRESULT)wParam;
if( FAILED( hr ) )
{
LPCTSTR failMessage = L"Error loading the model";
if( loadError.GetLength() > 0 )
{
CString tmp = failMessage;
tmp += L"\n";
tmp += loadError;
return validationError( tmp, hr );
}
else
return validationError( failMessage, hr );
}
appState.source.path = path;
appState.source.impl = impl;
appState.saveModelSource();
EndDialog( IDOK );
return 0;
}
LRESULT LoadModelDlg::OnHyperlink( int idCtrl, LPNMHDR pnmh, BOOL& bHandled )
{
const UINT code = pnmh->code;
switch( code )
{
case NM_CLICK:
case NM_RETURN:
break;
default:
return 0;
}
PNMLINK pNMLink = (PNMLINK)pnmh;
LPCTSTR url = pNMLink->item.szUrl;
ShellExecute( NULL, L"open", url, NULL, NULL, SW_SHOW );
bHandled = TRUE;
return 0;
}
void LoadModelDlg::onModelAdvanced()
{
ModelAdvancedDlg dlg{ appState };
dlg.show( m_hWnd );
}
| 5,972
|
C++
|
.cpp
| 205
| 26.892683
| 144
| 0.729716
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,622
|
WhisperDesktop.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/WhisperDesktop.cpp
|
#include "stdafx.h"
#include "AppState.h"
#include "Utils/miscUtils.h"
#include "LoadModelDlg.h"
#include "TranscribeDlg.h"
#include "CaptureDlg.h"
static HRESULT dialogLoadModel( AppState& appState )
{
LoadModelDlg loadDialog{ appState };
HRESULT hr = loadDialog.show();
if( FAILED( hr ) )
{
reportFatalError( "Error loading the model", hr );
return hr;
}
appState.automaticallyLoadModel = false;
return hr;
}
static HRESULT dialogTranscribe( AppState& appState )
{
TranscribeDlg dialog{ appState };
return dialog.show();
}
static HRESULT dialogCapture( AppState& appState )
{
CaptureDlg dialog{ appState };
return dialog.show();
}
using pfnDialog = HRESULT( * )( AppState& appState );
static const std::array<pfnDialog, 4> s_dialogs =
{
nullptr, // S_OK
&dialogLoadModel, // SCREEN_MODEL
&dialogTranscribe, // SCREEN_TRANSCRIBE
&dialogCapture, // SCREEN_CAPTURE
};
int __stdcall wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
AppState appState;
HRESULT hr = appState.startup();
if( FAILED( hr ) )
return hr;
appState.findModelSource();
hr = SCREEN_MODEL;
while( true )
{
pfnDialog pfn = s_dialogs[ hr ];
if( nullptr == pfn )
return S_OK;
hr = pfn( appState );
if( FAILED( hr ) )
return hr;
if( hr == SCREEN_MODEL )
appState.model = nullptr;
}
}
| 1,352
|
C++
|
.cpp
| 56
| 22.178571
| 102
| 0.729457
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,623
|
miscUtils.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/Utils/miscUtils.cpp
|
#include "stdafx.h"
#include "miscUtils.h"
namespace
{
wchar_t* formatMessage( HRESULT hr )
{
wchar_t* err;
if( FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
hr,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
(LPTSTR)&err,
0,
NULL ) )
return err;
return nullptr;
}
}
CString formatErrorMessage( HRESULT hr )
{
CString message;
const wchar_t* err = formatMessage( hr );
if( nullptr != err )
{
message = err;
LocalFree( (HLOCAL)err );
message.TrimRight();
}
else
message.Format( L"Error code %i (0x%08X)", hr, hr );
return message;
}
void reportFatalError( const char* what, HRESULT hr )
{
CString message;
message.Format( L"%S\n%S\n", "Unable to start the application.", what );
message += formatErrorMessage( hr );
::MessageBox( nullptr, message, L"Whisper Desktop Startup", MB_OK | MB_ICONERROR );
}
namespace
{
using Whisper::eModelImplementation;
struct sImplString
{
eModelImplementation val;
LPCTSTR str;
};
static const std::array<sImplString, 3> s_implStrings =
{
sImplString{ eModelImplementation::GPU, L"GPU" },
sImplString{ eModelImplementation::Hybrid, L"Hybrid" },
sImplString{ eModelImplementation::Reference, L"Reference" },
};
}
HRESULT implParse( const CString& s, eModelImplementation& rdi )
{
for( const auto& is : s_implStrings )
{
if( 0 != s.CompareNoCase( is.str ) )
continue;
rdi = is.val;;
return S_OK;
}
return E_INVALIDARG;
}
LPCTSTR implString( eModelImplementation i )
{
for( const auto& is : s_implStrings )
if( is.val == i )
return is.str;
return nullptr;
}
void implPopulateCombobox( CComboBox& cb, Whisper::eModelImplementation impl )
{
int curSel = 0;
int idx = 0;
for( const auto& is : s_implStrings )
{
cb.AddString( is.str );
if( is.val == impl )
curSel = idx;
idx++;
}
cb.SetCurSel( curSel );
}
Whisper::eModelImplementation implGetValue( CComboBox& cb )
{
int curSel = cb.GetCurSel();
if( curSel < 0 )
return (Whisper::eModelImplementation)0;
return s_implStrings[ curSel ].val;
}
ThreadPoolWork::~ThreadPoolWork()
{
if( nullptr != work )
{
CloseThreadpoolWork( work );
work = nullptr;
}
}
void __stdcall ThreadPoolWork::callback( PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work )
{
iThreadPoolCallback* cb = (iThreadPoolCallback*)Context;
cb->poolCallback();
}
HRESULT ThreadPoolWork::create( iThreadPoolCallback* cb )
{
if( nullptr == cb )
return E_POINTER;
if( nullptr != work )
return HRESULT_FROM_WIN32( ERROR_ALREADY_INITIALIZED );
work = CreateThreadpoolWork( &callback, cb, nullptr );
if( nullptr != work )
return S_OK;
return HRESULT_FROM_WIN32( GetLastError() );
}
HRESULT ThreadPoolWork::post()
{
if( nullptr == work )
return OLE_E_BLANK;
SubmitThreadpoolWork( work );
return S_OK;
}
void makeUtf16( CString& rdi, const char* utf8 )
{
const size_t length = strlen( utf8 );
int count = MultiByteToWideChar( CP_UTF8, 0, utf8, (int)length, nullptr, 0 );
wchar_t* p = rdi.GetBufferSetLength( count );
MultiByteToWideChar( CP_UTF8, 0, utf8, (int)length, p, count );
rdi.ReleaseBuffer();
}
void makeUtf8( CStringA& rdi, const CString& utf16 )
{
int count = WideCharToMultiByte( CP_UTF8, 0, utf16, utf16.GetLength(), nullptr, 0, nullptr, nullptr );
char* s = rdi.GetBufferSetLength( count + 1 );
count = WideCharToMultiByte( CP_UTF8, 0, utf16, utf16.GetLength(), s, count, nullptr, nullptr );
rdi.ReleaseBufferSetLength( count );
}
constexpr int ofnBufferLength = 2048;
bool getOpenFileName( HWND owner, LPCTSTR title, LPCTSTR filter, CString& path )
{
wchar_t buffer[ ofnBufferLength ];
buffer[ 0 ] = 0;
OPENFILENAME ofn;
memset( &ofn, 0, sizeof( ofn ) );
ofn.lStructSize = sizeof( OPENFILENAME );
ofn.hwndOwner = owner;
ofn.lpstrFilter = filter;
ofn.lpstrTitle = title;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
ofn.lpstrFile = buffer;
ofn.nMaxFile = ofnBufferLength - 1;
CString dir;
if( path.GetLength() > 0 && path.GetLength() < ofnBufferLength )
wcsncpy_s( buffer, path, path.GetLength() );
if( !GetOpenFileName( &ofn ) )
{
path = L"";
return false;
}
else
{
path = ofn.lpstrFile;
return true;
}
}
bool getSaveFileName( HWND owner, LPCTSTR title, LPCTSTR filter, CString& path, DWORD* filterIndex )
{
wchar_t buffer[ ofnBufferLength ];
buffer[ 0 ] = 0;
OPENFILENAME ofn;
memset( &ofn, 0, sizeof( ofn ) );
ofn.lStructSize = sizeof( OPENFILENAME );
ofn.hwndOwner = owner;
ofn.lpstrFilter = filter;
ofn.lpstrTitle = title;
ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST;
ofn.lpstrFile = buffer;
ofn.nMaxFile = ofnBufferLength - 1;
if( nullptr != filterIndex )
ofn.nFilterIndex = *filterIndex + 1;
if( path.GetLength() > 0 && path.GetLength() < ofnBufferLength )
wcsncpy_s( buffer, path, path.GetLength() );
if( !GetSaveFileName( &ofn ) )
return false;
path = ofn.lpstrFile;
if( nullptr != filterIndex )
*filterIndex = ofn.nFilterIndex - 1;
return true;
}
void reportError( HWND owner, LPCTSTR text, LPCTSTR title, HRESULT hr )
{
if( nullptr == title )
title = L"Operation Failed";
CString message = text;
message.TrimRight();
if( FAILED( hr ) )
{
message += L"\n";
message += formatErrorMessage( hr );
}
::MessageBox( owner, message, title, MB_OK | MB_ICONWARNING );
}
HRESULT writeUtf8Bom( CAtlFile& file )
{
const std::array<uint8_t, 3> bom = { 0xEF, 0xBB, 0xBF };
return file.Write( bom.data(), 3 );
}
bool isInvalidTranslate( HWND owner, uint32_t lang, bool translate )
{
if( !translate )
return false;
constexpr uint32_t english = 0x6E65;
if( lang != english )
return false;
LPCTSTR message = L"The translate feature translates speech to English.\nIt’s not available when the audio language is already English.";
MessageBox( owner, message, L"Incompatible parameters", MB_OK | MB_ICONINFORMATION );
return true;
}
| 5,890
|
C++
|
.cpp
| 219
| 24.716895
| 138
| 0.72017
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,624
|
PendingState.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/Utils/PendingState.cpp
|
#include "stdafx.h"
#include "PendingState.h"
void PendingState::initialize( std::initializer_list<HWND> editors, std::initializer_list<HWND> pending )
{
editorsWindows = editors;
wasEnabled.resize( editorsWindows.size() );
pendingWindows = pending;
}
void PendingState::setPending( bool nowPending )
{
if( nowPending )
{
for( size_t i = 0; i < editorsWindows.size(); i++ )
{
BOOL e = IsWindowEnabled( editorsWindows[ i ] );
if( e )
{
wasEnabled[ i ] = true;
EnableWindow( editorsWindows[ i ], FALSE );
}
else
wasEnabled[ i ] = false;
}
}
else
{
for( size_t i = 0; i < editorsWindows.size(); i++ )
{
if( !wasEnabled[ i ] )
continue;
EnableWindow( editorsWindows[ i ], TRUE );
}
}
const int show = nowPending ? SW_NORMAL : SW_HIDE;
for( HWND w : pendingWindows )
::ShowWindow( w, show );
}
| 853
|
C++
|
.cpp
| 37
| 20.324324
| 105
| 0.663391
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,625
|
logger.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/Utils/logger.cpp
|
#include "stdafx.h"
#include "logger.h"
#include "miscUtils.h"
namespace
{
using namespace Whisper;
// Terminal color map. 10 colors grouped in ranges [0.0, 0.1, ..., 0.9]
// Lowest is red, middle is yellow, highest is green.
static const std::array<const char*, 10> k_colors =
{
"\033[38;5;196m", "\033[38;5;202m", "\033[38;5;208m", "\033[38;5;214m", "\033[38;5;220m",
"\033[38;5;226m", "\033[38;5;190m", "\033[38;5;154m", "\033[38;5;118m", "\033[38;5;82m",
};
static int colorIndex( const sToken& tok )
{
const float p = tok.probability;
const float p3 = p * p * p;
int col = (int)( p3 * float( k_colors.size() ) );
col = std::max( 0, std::min( (int)k_colors.size() - 1, col ) );
return col;
}
}
void printTime( CStringA& rdi, Whisper::sTimeSpan time, bool comma )
{
Whisper::sTimeSpanFields fields = time;
const uint32_t hours = fields.days * 24 + fields.hours;
const char separator = comma ? ',' : '.';
rdi.AppendFormat( "%02d:%02d:%02d%c%03d",
(int)hours,
(int)fields.minutes,
(int)fields.seconds,
separator,
fields.ticks / 10'000 );
}
HRESULT logNewSegments( const iTranscribeResult* results, size_t newSegments, bool printSpecial )
{
sTranscribeLength length;
CHECK( results->getSize( length ) );
const size_t len = length.countSegments;
size_t i = len - newSegments;
const sSegment* const segments = results->getSegments();
const sToken* const tokens = results->getTokens();
CStringA str;
for( ; i < len; i++ )
{
const sSegment& seg = segments[ i ];
str = "[";
printTime( str, seg.time.begin );
str += " --> ";
printTime( str, seg.time.end );
str += "] ";
for( uint32_t j = 0; j < seg.countTokens; j++ )
{
const sToken& tok = tokens[ seg.firstToken + j ];
if( !printSpecial && ( tok.flags & eTokenFlags::Special ) )
continue;
str += k_colors[ colorIndex( tok ) ];
str += tok.text;
str += "\033[0m";
}
logInfo( u8"%s", cstr( str ) );
}
return S_OK;
}
| 1,955
|
C++
|
.cpp
| 64
| 28.046875
| 97
| 0.647715
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,626
|
TranslateCheckbox.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/Utils/TranslateCheckbox.cpp
|
#include "stdafx.h"
#include "TranslateCheckbox.h"
static const LPCTSTR regValTranslate = L"translate";
void TranslateCheckbox::initialize( HWND owner, int idc, AppState& state )
{
m_hWnd = GetDlgItem( owner, idc );
assert( nullptr != m_hWnd );
if( state.boolLoad( regValTranslate ) )
::SendMessage( m_hWnd, BM_SETCHECK, BST_CHECKED, 0L );
}
bool TranslateCheckbox::checked()
{
assert( nullptr != m_hWnd );
const int state = ( int )::SendMessage( m_hWnd, BM_GETCHECK, 0, 0 );
return state == BST_CHECKED;
}
void TranslateCheckbox::saveSelection( AppState& state )
{
state.boolStore( regValTranslate, checked() );
}
| 628
|
C++
|
.cpp
| 20
| 29.75
| 74
| 0.735099
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,627
|
DebugConsole.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/Utils/DebugConsole.cpp
|
// https://github.com/Const-me/vis_avs_dx/blob/master/avs_dx/DxVisuals/Interop/ConsoleLogger.cpp
#include "stdafx.h"
#include "DebugConsole.h"
#include "miscUtils.h"
#include "../AppState.h"
#include "logger.h"
#include <string>
namespace
{
using Whisper::eLogLevel;
constexpr uint16_t defaultAttributes = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
inline uint16_t textAttributes( eLogLevel lvl )
{
switch( lvl )
{
case eLogLevel::Error:
return FOREGROUND_RED | FOREGROUND_INTENSITY;
case eLogLevel::Warning:
return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
case eLogLevel::Info:
return FOREGROUND_GREEN | FOREGROUND_INTENSITY;
case eLogLevel::Debug:
return FOREGROUND_BLUE | FOREGROUND_INTENSITY;
}
return defaultAttributes;
}
// Background stuff: accumulate messages in a small buffer, in case user will want to see them in the console.
// Ideally, we should accumulate them in a more efficient data structure, maybe a circular buffer.
// However, we don't have that many messages per second, this simple solution that uses std::deque is probably good enough for the job.
static constexpr uint16_t bufferSize = 64;
using Lock = CComCritSecLock<CComAutoCriticalSection>;
#define LOCK() Lock __lock{ critSec }
thread_local std::string threadError;
}
HRESULT DebugConsole::Entry::print( HANDLE hConsole, CString& tempString ) const
{
if( !SetConsoleTextAttribute( hConsole, textAttributes( level ) ) )
return getLastHr();
makeUtf16( tempString, message );
tempString += L"\r\n";
if( !WriteConsoleW( hConsole, tempString, (DWORD)tempString.GetLength(), nullptr, nullptr ) )
return getLastHr();
return S_OK;
}
void clearLastError()
{
threadError.clear();
}
bool getLastError( CString& rdi )
{
if( threadError.empty() )
{
rdi = L"";
return false;
}
else
{
makeUtf16( rdi, threadError.c_str() );
threadError.clear();
return true;
}
}
inline void DebugConsole::logSink( eLogLevel lvl, const char* message )
{
LOCK();
// Add to the buffer
while( buffer.size() >= bufferSize )
buffer.pop_front();
buffer.emplace_back( Entry{ lvl, message } );
// If the console window is shown, print there, too.
if( output )
buffer.rbegin()->print( output, tempString );
}
void __stdcall DebugConsole::logSinkStatic( void* context, eLogLevel lvl, const char* message )
{
if( lvl == eLogLevel::Error )
threadError = message;
DebugConsole* con = (DebugConsole*)context;
con->logSink( lvl, message );
}
HRESULT DebugConsole::initialize( Whisper::eLogLevel level )
{
if( nullptr != pGlobalInstance )
return HRESULT_FROM_WIN32( ERROR_ALREADY_INITIALIZED );
pGlobalInstance = this;
Whisper::sLoggerSetup setup;
setup.sink = &logSinkStatic;
setup.context = this;
setup.level = level;
setup.flags = Whisper::eLoggerFlags::SkipFormatMessage;
return Whisper::setupLogger( setup );
}
DebugConsole::~DebugConsole()
{
hide();
Whisper::sLoggerSetup setup;
memset( &setup, 0, sizeof( setup ) );
Whisper::setupLogger( setup );
pGlobalInstance = nullptr;
}
DebugConsole* DebugConsole::pGlobalInstance = nullptr;
void DebugConsole::windowClosed()
{
LOCK();
if( FreeConsole() )
{
// Apparently, FreeConsole already closes that handle: https://stackoverflow.com/q/12676312/126995
output.Detach();
}
output.Close();
for( CButton* b : checkboxes )
{
if( !*b )
continue;
if( !b->IsWindow() )
continue;
PostMessage( *b, BM_SETCHECK, BST_UNCHECKED, 0 );
}
}
BOOL __stdcall DebugConsole::consoleHandlerRoutine( DWORD dwCtrlType )
{
switch( dwCtrlType )
{
case CTRL_CLOSE_EVENT:
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
pGlobalInstance->windowClosed();
return TRUE;
}
return TRUE;
}
HRESULT DebugConsole::show()
{
HWND hWnd = GetConsoleWindow();
if( nullptr != hWnd )
{
ShowWindow( hWnd, SW_RESTORE );
SetForegroundWindow( hWnd );
return S_FALSE;
}
if( !AllocConsole() )
return getLastHr();
output.Close();
output.Attach( GetStdHandle( STD_OUTPUT_HANDLE ) );
if( !output )
return getLastHr();
constexpr UINT cp = CP_UTF8;
if( IsValidCodePage( cp ) )
SetConsoleOutputCP( cp );
// Enable ANSI color coding
DWORD mode = 0;
if( !GetConsoleMode( output, &mode ) )
return getLastHr();
if( 0 == ( mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING ) )
{
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if( !SetConsoleMode( output, mode ) )
return getLastHr();
}
SetConsoleTitle( L"Whisper Desktop Debug Console" );
SetConsoleCtrlHandler( &consoleHandlerRoutine, TRUE );
// Disable close command in the sys.menu of the new console, otherwise the whole process will quit: https://stackoverflow.com/a/12015131/126995
HWND hwnd = ::GetConsoleWindow();
if( hwnd != nullptr )
{
HMENU hMenu = ::GetSystemMenu( hwnd, FALSE );
if( hMenu != NULL )
DeleteMenu( hMenu, SC_CLOSE, MF_BYCOMMAND );
}
// Print old log entries
for( const auto& e : buffer )
CHECK( e.print( output, tempString ) );
const CStringA msg = "Press Control+C or Control+Break to close this window\r\n";
if( !SetConsoleTextAttribute( output, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY ) )
return getLastHr();
if( !WriteConsoleA( output, cstr( msg ), msg.GetLength(), nullptr, nullptr ) )
return getLastHr();
return S_OK;
}
HRESULT DebugConsole::hide()
{
LOCK();
if( !output )
return S_FALSE;
windowClosed();
return S_OK;
}
void DebugConsole::addCheckbox( CButton& cb )
{
checkboxes.emplace( &cb );
}
void DebugConsole::removeCheckbox( CButton& cb )
{
checkboxes.erase( &cb );
}
HRESULT ConsoleCheckbox::initialize( HWND dialog, int idc, AppState& state )
{
control = GetDlgItem( dialog, idc );
assert( control );
console = &state.console;
if( state.console.isVisible() )
control.SetCheck( BST_CHECKED );
state.console.addCheckbox( control );
return S_OK;
}
void ConsoleCheckbox::click()
{
const int state = control.GetCheck();
if( state == BST_CHECKED )
console->show();
else
console->hide();
}
void ConsoleCheckbox::ensureChecked()
{
const int state = control.GetCheck();
if( state == BST_CHECKED )
return;
control.SetCheck( BST_CHECKED );
console->show();
}
void DebugConsole::log( eLogLevel lvl, const char* pszFormat, va_list args )
{
LOCK();
// Add to the buffer
while( buffer.size() >= bufferSize )
buffer.pop_front();
tempStringA.FormatV( pszFormat, args );
buffer.emplace_back( Entry{ lvl, tempStringA } );
// If the console window is shown, print there, too.
if( output )
buffer.rbegin()->print( output, tempString );
}
void DebugConsole::logMessage( eLogLevel lvl, const char* pszFormat, va_list args )
{
if( nullptr == pGlobalInstance )
return;
pGlobalInstance->log( lvl, pszFormat, args );
}
void logMessage( Whisper::eLogLevel lvl, const char8_t* pczFormat, va_list args )
{
DebugConsole::logMessage( lvl, (const char*)pczFormat, args );
}
| 6,883
|
C++
|
.cpp
| 243
| 26.156379
| 144
| 0.736579
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,628
|
LanguageDropdown.cpp
|
Const-me_Whisper/Examples/WhisperDesktop/Utils/LanguageDropdown.cpp
|
#include "stdafx.h"
#include "LanguageDropdown.h"
#include "miscUtils.h"
namespace
{
inline wchar_t toUpper( wchar_t c )
{
size_t st = (uint16_t)c;
st = reinterpret_cast<size_t>( CharUpperW( reinterpret_cast<LPWSTR>( st ) ) );
return (wchar_t)(uint16_t)st;
}
void makeTitleCase( CString& s )
{
bool cap = true;
for( int i = 0; i < s.GetLength(); i++ )
{
wchar_t c = s[ i ];
if( cap )
{
c = toUpper( c );
s.SetAt( i, c );
}
cap = false;
if( c == ' ' )
cap = true;
}
}
}
int LanguageDropdown::getInitialSelection( AppState& state ) const
{
constexpr uint32_t english = 0x6E65;
// Load preference from the registry
uint32_t id = state.languageRead();
if( id == UINT_MAX )
id = english;
auto it = std::find( keys.begin(), keys.end(), id );
if( it == keys.end() )
{
id = english;
it = std::find( keys.begin(), keys.end(), id );
assert( it != keys.end() );
}
ptrdiff_t idx = it - keys.begin();
return (int)idx;
}
void LanguageDropdown::initialize( HWND owner, int idc, AppState& state )
{
m_hWnd = GetDlgItem( owner, idc );
assert( nullptr != m_hWnd );
Whisper::sLanguageList list;
Whisper::getSupportedLanguages( list );
const size_t length = list.length;
keys.resize( length );
CString utf16;
for( size_t i = 0; i < length; i++ )
{
keys[ i ] = list.pointer[ i ].key;
makeUtf16( utf16, list.pointer[ i ].name );
makeTitleCase( utf16 );
SendMessage( m_hWnd, CB_ADDSTRING, 0, (LPARAM)cstr( utf16 ) );
}
const int curSel = getInitialSelection( state );
SendMessage( m_hWnd, CB_SETCURSEL, curSel, 0 );
}
uint32_t LanguageDropdown::selectedLanguage()
{
const int cs = (int)SendMessage( m_hWnd, CB_GETCURSEL, 0, 0 );
if( cs < 0 || cs >= keys.size() )
return UINT_MAX;
return keys[ cs ];
}
void LanguageDropdown::saveSelection( AppState& state )
{
state.languageWrite( selectedLanguage() );
}
| 1,886
|
C++
|
.cpp
| 75
| 22.746667
| 80
| 0.657778
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,629
|
main.cpp
|
Const-me_Whisper/Examples/OldMain/main.cpp
|
#include "whisper.h"
// third-party utilities
// use your favorite implementations
#define DR_WAV_IMPLEMENTATION
#include "dr_wav.h"
#include <cmath>
#include <fstream>
#include <cstdio>
#include <string>
#include <thread>
#include <vector>
// Terminal color map. 10 colors grouped in ranges [0.0, 0.1, ..., 0.9]
// Lowest is red, middle is yellow, highest is green.
const std::vector<std::string> k_colors = {
"\033[38;5;196m", "\033[38;5;202m", "\033[38;5;208m", "\033[38;5;214m", "\033[38;5;220m",
"\033[38;5;226m", "\033[38;5;190m", "\033[38;5;154m", "\033[38;5;118m", "\033[38;5;82m",
};
// 500 -> 00:05.000
// 6000 -> 01:00.000
std::string to_timestamp(int64_t t, bool comma = false) {
int64_t msec = t * 10;
int64_t hr = msec / (1000 * 60 * 60);
msec = msec - hr * (1000 * 60 * 60);
int64_t min = msec / (1000 * 60);
msec = msec - min * (1000 * 60);
int64_t sec = msec / 1000;
msec = msec - sec * 1000;
char buf[32];
snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int) hr, (int) min, (int) sec, comma ? "," : ".", (int) msec);
return std::string(buf);
}
int timestamp_to_sample(int64_t t, int n_samples) {
return std::max(0, std::min((int) n_samples - 1, (int) ((t*WHISPER_SAMPLE_RATE)/100)));
}
// helper function to replace substrings
void replace_all(std::string & s, const std::string & search, const std::string & replace) {
for (size_t pos = 0; ; pos += replace.length()) {
pos = s.find(search, pos);
if (pos == std::string::npos) break;
s.erase(pos, search.length());
s.insert(pos, replace);
}
}
// command-line parameters
struct whisper_params {
int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
int32_t n_processors = 1;
int32_t offset_t_ms = 0;
int32_t offset_n = 0;
int32_t duration_ms = 0;
int32_t max_context = -1;
int32_t max_len = 0;
float word_thold = 0.01f;
bool speed_up = false;
bool translate = false;
bool diarize = false;
bool output_txt = false;
bool output_vtt = false;
bool output_srt = false;
bool output_wts = false;
bool print_special = false;
bool print_colors = false;
bool print_progress = false;
bool no_timestamps = false;
std::string language = "en";
std::string prompt;
std::string model = "models/ggml-base.en.bin";
std::vector<std::string> fname_inp = {};
};
void whisper_print_usage(int argc, char ** argv, const whisper_params & params);
bool whisper_params_parse(int argc, char ** argv, whisper_params & params) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg[0] != '-') {
params.fname_inp.push_back(arg);
continue;
}
if (arg == "-h" || arg == "--help") {
whisper_print_usage(argc, argv, params);
exit(0);
}
else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }
else if (arg == "-p" || arg == "--processors") { params.n_processors = std::stoi(argv[++i]); }
else if (arg == "-ot" || arg == "--offset-t") { params.offset_t_ms = std::stoi(argv[++i]); }
else if (arg == "-on" || arg == "--offset-n") { params.offset_n = std::stoi(argv[++i]); }
else if (arg == "-d" || arg == "--duration") { params.duration_ms = std::stoi(argv[++i]); }
else if (arg == "-mc" || arg == "--max-context") { params.max_context = std::stoi(argv[++i]); }
else if (arg == "-ml" || arg == "--max-len") { params.max_len = std::stoi(argv[++i]); }
else if (arg == "-wt" || arg == "--word-thold") { params.word_thold = std::stof(argv[++i]); }
else if (arg == "-su" || arg == "--speed-up") { params.speed_up = true; }
else if (arg == "-tr" || arg == "--translate") { params.translate = true; }
else if (arg == "-di" || arg == "--diarize") { params.diarize = true; }
else if (arg == "-otxt" || arg == "--output-txt") { params.output_txt = true; }
else if (arg == "-ovtt" || arg == "--output-vtt") { params.output_vtt = true; }
else if (arg == "-osrt" || arg == "--output-srt") { params.output_srt = true; }
else if (arg == "-owts" || arg == "--output-words") { params.output_wts = true; }
else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }
else if (arg == "-pc" || arg == "--print-colors") { params.print_colors = true; }
else if (arg == "-pp" || arg == "--print-progress") { params.print_progress = true; }
else if (arg == "-nt" || arg == "--no-timestamps") { params.no_timestamps = true; }
else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }
else if ( arg == "--prompt") { params.prompt = argv[++i]; }
else if (arg == "-m" || arg == "--model") { params.model = argv[++i]; }
else if (arg == "-f" || arg == "--file") { params.fname_inp.emplace_back(argv[++i]); }
else {
fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
whisper_print_usage(argc, argv, params);
exit(0);
}
}
return true;
}
void whisper_print_usage(int /*argc*/, char ** argv, const whisper_params & params) {
fprintf(stderr, "\n");
fprintf(stderr, "usage: %s [options] file0.wav file1.wav ...\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "options:\n");
fprintf(stderr, " -h, --help [default] show this help message and exit\n");
fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);
fprintf(stderr, " -p N, --processors N [%-7d] number of processors to use during computation\n", params.n_processors);
fprintf(stderr, " -ot N, --offset-t N [%-7d] time offset in milliseconds\n", params.offset_t_ms);
fprintf(stderr, " -on N, --offset-n N [%-7d] segment index offset\n", params.offset_n);
fprintf(stderr, " -d N, --duration N [%-7d] duration of audio to process in milliseconds\n", params.duration_ms);
fprintf(stderr, " -mc N, --max-context N [%-7d] maximum number of text context tokens to store\n", params.max_context);
fprintf(stderr, " -ml N, --max-len N [%-7d] maximum segment length in characters\n", params.max_len);
fprintf(stderr, " -wt N, --word-thold N [%-7.2f] word timestamp probability threshold\n", params.word_thold);
fprintf(stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", params.speed_up ? "true" : "false");
fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");
fprintf(stderr, " -di, --diarize [%-7s] stereo audio diarization\n", params.diarize ? "true" : "false");
fprintf(stderr, " -otxt, --output-txt [%-7s] output result in a text file\n", params.output_txt ? "true" : "false");
fprintf(stderr, " -ovtt, --output-vtt [%-7s] output result in a vtt file\n", params.output_vtt ? "true" : "false");
fprintf(stderr, " -osrt, --output-srt [%-7s] output result in a srt file\n", params.output_srt ? "true" : "false");
fprintf(stderr, " -owts, --output-words [%-7s] output script for generating karaoke video\n", params.output_wts ? "true" : "false");
fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");
fprintf(stderr, " -pc, --print-colors [%-7s] print colors\n", params.print_colors ? "true" : "false");
fprintf(stderr, " -pp, --print-progress [%-7s] print progress\n", params.print_progress ? "true" : "false");
fprintf(stderr, " -nt, --no-timestamps [%-7s] do not print timestamps\n", params.no_timestamps ? "false" : "true");
fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language ('auto' for auto-detect)\n", params.language.c_str());
fprintf(stderr, " --prompt PROMPT [%-7s] initial prompt\n", params.prompt.c_str());
fprintf(stderr, " -m FNAME, --model FNAME [%-7s] model path\n", params.model.c_str());
fprintf(stderr, " -f FNAME, --file FNAME [%-7s] input WAV file path\n", "");
fprintf(stderr, "\n");
}
struct whisper_print_user_data {
const whisper_params * params;
const std::vector<std::vector<float>> * pcmf32s;
};
void whisper_print_segment_callback(struct whisper_context * ctx, int n_new, void * user_data) {
const auto & params = *((whisper_print_user_data *) user_data)->params;
const auto & pcmf32s = *((whisper_print_user_data *) user_data)->pcmf32s;
const int n_segments = whisper_full_n_segments(ctx);
// print the last n_new segments
const int s0 = n_segments - n_new;
if (s0 == 0) {
printf("\n");
}
for (int i = s0; i < n_segments; i++) {
if (params.no_timestamps) {
if (params.print_colors) {
for (int j = 0; j < whisper_full_n_tokens(ctx, i); ++j) {
if (params.print_special == false) {
const whisper_token id = whisper_full_get_token_id(ctx, i, j);
if (id >= whisper_token_eot(ctx)) {
continue;
}
}
const char * text = whisper_full_get_token_text(ctx, i, j);
const float p = whisper_full_get_token_p (ctx, i, j);
const int col = std::max(0, std::min((int) k_colors.size(), (int) (std::pow(p, 3)*float(k_colors.size()))));
printf("%s%s%s", k_colors[col].c_str(), text, "\033[0m");
}
} else {
const char * text = whisper_full_get_segment_text(ctx, i);
printf("%s", text);
}
fflush(stdout);
} else {
const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
std::string speaker;
if (params.diarize && pcmf32s.size() == 2) {
const int64_t n_samples = pcmf32s[0].size();
const int64_t is0 = timestamp_to_sample(t0, n_samples);
const int64_t is1 = timestamp_to_sample(t1, n_samples);
double energy0 = 0.0f;
double energy1 = 0.0f;
for (int64_t j = is0; j < is1; j++) {
energy0 += fabs(pcmf32s[0][j]);
energy1 += fabs(pcmf32s[1][j]);
}
if (energy0 > 1.1*energy1) {
speaker = "(speaker 0)";
} else if (energy1 > 1.1*energy0) {
speaker = "(speaker 1)";
} else {
speaker = "(speaker ?)";
}
//printf("is0 = %lld, is1 = %lld, energy0 = %f, energy1 = %f, %s\n", is0, is1, energy0, energy1, speaker.c_str());
}
if (params.print_colors) {
printf("[%s --> %s] ", to_timestamp(t0).c_str(), to_timestamp(t1).c_str());
for (int j = 0; j < whisper_full_n_tokens(ctx, i); ++j) {
if (params.print_special == false) {
const whisper_token id = whisper_full_get_token_id(ctx, i, j);
if (id >= whisper_token_eot(ctx)) {
continue;
}
}
const char * text = whisper_full_get_token_text(ctx, i, j);
const float p = whisper_full_get_token_p (ctx, i, j);
const int col = std::max(0, std::min((int) k_colors.size(), (int) (std::pow(p, 3)*float(k_colors.size()))));
printf("%s%s%s%s", speaker.c_str(), k_colors[col].c_str(), text, "\033[0m");
}
printf("\n");
} else {
const char * text = whisper_full_get_segment_text(ctx, i);
printf("[%s --> %s] %s%s\n", to_timestamp(t0).c_str(), to_timestamp(t1).c_str(), speaker.c_str(), text);
}
}
}
}
bool output_txt(struct whisper_context * ctx, const char * fname) {
std::ofstream fout(fname);
if (!fout.is_open()) {
fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
return false;
}
fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
const int n_segments = whisper_full_n_segments(ctx);
for (int i = 0; i < n_segments; ++i) {
const char * text = whisper_full_get_segment_text(ctx, i);
fout << text << "\n";
}
return true;
}
bool output_vtt(struct whisper_context * ctx, const char * fname) {
std::ofstream fout(fname);
if (!fout.is_open()) {
fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
return false;
}
fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
fout << "WEBVTT\n\n";
const int n_segments = whisper_full_n_segments(ctx);
for (int i = 0; i < n_segments; ++i) {
const char * text = whisper_full_get_segment_text(ctx, i);
const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
fout << to_timestamp(t0) << " --> " << to_timestamp(t1) << "\n";
fout << text << "\n\n";
}
return true;
}
bool output_srt(struct whisper_context * ctx, const char * fname, const whisper_params & params) {
std::ofstream fout(fname);
if (!fout.is_open()) {
fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
return false;
}
fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
const int n_segments = whisper_full_n_segments(ctx);
for (int i = 0; i < n_segments; ++i) {
const char * text = whisper_full_get_segment_text(ctx, i);
const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
fout << i + 1 + params.offset_n << "\n";
fout << to_timestamp(t0, true) << " --> " << to_timestamp(t1, true) << "\n";
fout << text << "\n\n";
}
return true;
}
// karaoke video generation
// outputs a bash script that uses ffmpeg to generate a video with the subtitles
// TODO: font parameter adjustments
bool output_wts(struct whisper_context * ctx, const char * fname, const char * fname_inp, const whisper_params & /*params*/, float t_sec) {
std::ofstream fout(fname);
fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
// TODO: become parameter
static const char * font = "/System/Library/Fonts/Supplemental/Courier New Bold.ttf";
fout << "#!/bin/bash" << "\n";
fout << "\n";
fout << "ffmpeg -i " << fname_inp << " -f lavfi -i color=size=1200x120:duration=" << t_sec << ":rate=25:color=black -vf \"";
for (int i = 0; i < whisper_full_n_segments(ctx); i++) {
const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
const int n = whisper_full_n_tokens(ctx, i);
std::vector<whisper_token_data> tokens(n);
for (int j = 0; j < n; ++j) {
tokens[j] = whisper_full_get_token_data(ctx, i, j);
}
if (i > 0) {
fout << ",";
}
// background text
fout << "drawtext=fontfile='" << font << "':fontsize=24:fontcolor=gray:x=(w-text_w)/2:y=h/2:text='':enable='between(t," << t0/100.0 << "," << t0/100.0 << ")'";
bool is_first = true;
for (int j = 0; j < n; ++j) {
const auto & token = tokens[j];
if (tokens[j].id >= whisper_token_eot(ctx)) {
continue;
}
std::string txt_bg;
std::string txt_fg; // highlight token
std::string txt_ul; // underline
txt_bg = "> ";
txt_fg = "> ";
txt_ul = "\\ \\ ";
{
for (int k = 0; k < n; ++k) {
const auto & token2 = tokens[k];
if (tokens[k].id >= whisper_token_eot(ctx)) {
continue;
}
const std::string txt = whisper_token_to_str(ctx, token2.id);
txt_bg += txt;
if (k == j) {
for (int l = 0; l < (int) txt.size(); ++l) {
txt_fg += txt[l];
txt_ul += "_";
}
txt_fg += "|";
} else {
for (int l = 0; l < (int) txt.size(); ++l) {
txt_fg += "\\ ";
txt_ul += "\\ ";
}
}
}
::replace_all(txt_bg, "'", "\u2019");
::replace_all(txt_bg, "\"", "\\\"");
::replace_all(txt_fg, "'", "\u2019");
::replace_all(txt_fg, "\"", "\\\"");
}
if (is_first) {
// background text
fout << ",drawtext=fontfile='" << font << "':fontsize=24:fontcolor=gray:x=(w-text_w)/2:y=h/2:text='" << txt_bg << "':enable='between(t," << t0/100.0 << "," << t1/100.0 << ")'";
is_first = false;
}
// foreground text
fout << ",drawtext=fontfile='" << font << "':fontsize=24:fontcolor=lightgreen:x=(w-text_w)/2+8:y=h/2:text='" << txt_fg << "':enable='between(t," << token.t0/100.0 << "," << token.t1/100.0 << ")'";
// underline
fout << ",drawtext=fontfile='" << font << "':fontsize=24:fontcolor=lightgreen:x=(w-text_w)/2+8:y=h/2+16:text='" << txt_ul << "':enable='between(t," << token.t0/100.0 << "," << token.t1/100.0 << ")'";
}
}
fout << "\" -c:v libx264 -pix_fmt yuv420p -y " << fname_inp << ".mp4" << "\n";
fout << "\n\n";
fout << "echo \"Your video has been saved to " << fname_inp << ".mp4\"" << "\n";
fout << "\n";
fout << "echo \" ffplay " << fname_inp << ".mp4\"\n";
fout << "\n";
fout.close();
fprintf(stderr, "%s: run 'source %s' to generate karaoke video\n", __func__, fname);
return true;
}
int main(int argc, char ** argv) {
whisper_params params;
if (whisper_params_parse(argc, argv, params) == false) {
return 1;
}
if (params.fname_inp.empty()) {
fprintf(stderr, "error: no input files specified\n");
whisper_print_usage(argc, argv, params);
return 2;
}
if (params.language != "auto" && whisper_lang_id(params.language.c_str()) == -1) {
fprintf(stderr, "error: unknown language '%s'\n", params.language.c_str());
whisper_print_usage(argc, argv, params);
exit(0);
}
// whisper init
struct whisper_context * ctx = whisper_init(params.model.c_str());
if (ctx == nullptr) {
fprintf(stderr, "error: failed to initialize whisper context\n");
return 3;
}
// initial prompt
std::vector<whisper_token> prompt_tokens;
if (!params.prompt.empty()) {
prompt_tokens.resize(1024);
prompt_tokens.resize(whisper_tokenize(ctx, params.prompt.c_str(), prompt_tokens.data(), prompt_tokens.size()));
fprintf(stderr, "\n");
fprintf(stderr, "initial prompt: '%s'\n", params.prompt.c_str());
fprintf(stderr, "initial tokens: [ ");
for (int i = 0; i < (int) prompt_tokens.size(); ++i) {
fprintf(stderr, "%d ", prompt_tokens[i]);
}
fprintf(stderr, "]\n");
}
for (int f = 0; f < (int) params.fname_inp.size(); ++f) {
const auto fname_inp = params.fname_inp[f];
std::vector<float> pcmf32; // mono-channel F32 PCM
std::vector<std::vector<float>> pcmf32s; // stereo-channel F32 PCM
// WAV input
{
drwav wav;
std::vector<uint8_t> wav_data; // used for pipe input from stdin
if (fname_inp == "-") {
{
uint8_t buf[1024];
while (true)
{
const size_t n = fread(buf, 1, sizeof(buf), stdin);
if (n == 0) {
break;
}
wav_data.insert(wav_data.end(), buf, buf + n);
}
}
if (drwav_init_memory(&wav, wav_data.data(), wav_data.size(), nullptr) == false) {
fprintf(stderr, "error: failed to open WAV file from stdin\n");
return 4;
}
fprintf(stderr, "%s: read %zu bytes from stdin\n", __func__, wav_data.size());
}
else if (drwav_init_file(&wav, fname_inp.c_str(), nullptr) == false) {
fprintf(stderr, "error: failed to open '%s' as WAV file\n", fname_inp.c_str());
return 5;
}
if (wav.channels != 1 && wav.channels != 2) {
fprintf(stderr, "%s: WAV file '%s' must be mono or stereo\n", argv[0], fname_inp.c_str());
return 6;
}
if (params.diarize && wav.channels != 2 && params.no_timestamps == false) {
fprintf(stderr, "%s: WAV file '%s' must be stereo for diarization and timestamps have to be enabled\n", argv[0], fname_inp.c_str());
return 6;
}
if (wav.sampleRate != WHISPER_SAMPLE_RATE) {
fprintf(stderr, "%s: WAV file '%s' must be 16 kHz\n", argv[0], fname_inp.c_str());
return 8;
}
if (wav.bitsPerSample != 16) {
fprintf(stderr, "%s: WAV file '%s' must be 16-bit\n", argv[0], fname_inp.c_str());
return 9;
}
const uint64_t n = wav_data.empty() ? wav.totalPCMFrameCount : wav_data.size()/(wav.channels*wav.bitsPerSample/8);
std::vector<int16_t> pcm16;
pcm16.resize(n*wav.channels);
drwav_read_pcm_frames_s16(&wav, n, pcm16.data());
drwav_uninit(&wav);
// convert to mono, float
pcmf32.resize(n);
if (wav.channels == 1) {
for (uint64_t i = 0; i < n; i++) {
pcmf32[i] = float(pcm16[i])/32768.0f;
}
} else {
for (uint64_t i = 0; i < n; i++) {
pcmf32[i] = float(pcm16[2*i] + pcm16[2*i + 1])/65536.0f;
}
}
if (params.diarize) {
// convert to stereo, float
pcmf32s.resize(2);
pcmf32s[0].resize(n);
pcmf32s[1].resize(n);
for (uint64_t i = 0; i < n; i++) {
pcmf32s[0][i] = float(pcm16[2*i])/32768.0f;
pcmf32s[1][i] = float(pcm16[2*i + 1])/32768.0f;
}
}
}
// print system information
{
fprintf(stderr, "\n");
fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
params.n_threads*params.n_processors, std::thread::hardware_concurrency(), whisper_print_system_info());
}
// print some info about the processing
{
fprintf(stderr, "\n");
if (!whisper_is_multilingual(ctx)) {
if (params.language != "en" || params.translate) {
params.language = "en";
params.translate = false;
fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);
}
}
fprintf(stderr, "%s: processing '%s' (%d samples, %.1f sec), %d threads, %d processors, lang = %s, task = %s, timestamps = %d ...\n",
__func__, fname_inp.c_str(), int(pcmf32.size()), float(pcmf32.size())/WHISPER_SAMPLE_RATE,
params.n_threads, params.n_processors,
params.language.c_str(),
params.translate ? "translate" : "transcribe",
params.no_timestamps ? 0 : 1);
fprintf(stderr, "\n");
}
// run the inference
{
whisper_full_params wparams = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);
wparams.print_realtime = false;
wparams.print_progress = params.print_progress;
wparams.print_timestamps = !params.no_timestamps;
wparams.print_special = params.print_special;
wparams.translate = params.translate;
wparams.language = params.language.c_str();
wparams.n_threads = params.n_threads;
wparams.n_max_text_ctx = params.max_context >= 0 ? params.max_context : wparams.n_max_text_ctx;
wparams.offset_ms = params.offset_t_ms;
wparams.duration_ms = params.duration_ms;
wparams.token_timestamps = params.output_wts || params.max_len > 0;
wparams.thold_pt = params.word_thold;
wparams.max_len = params.output_wts && params.max_len == 0 ? 60 : params.max_len;
wparams.speed_up = params.speed_up;
wparams.prompt_tokens = prompt_tokens.empty() ? nullptr : prompt_tokens.data();
wparams.prompt_n_tokens = prompt_tokens.empty() ? 0 : prompt_tokens.size();
whisper_print_user_data user_data = { ¶ms, &pcmf32s };
// this callback is called on each new segment
if (!wparams.print_realtime) {
wparams.new_segment_callback = whisper_print_segment_callback;
wparams.new_segment_callback_user_data = &user_data;
}
// example for abort mechanism
// in this example, we do not abort the processing, but we could if the flag is set to true
// the callback is called before every encoder run - if it returns false, the processing is aborted
{
static bool is_aborted = false; // NOTE: this should be atomic to avoid data race
wparams.encoder_begin_callback = [](struct whisper_context * /*ctx*/, void * user_data) {
bool is_aborted = *(bool*)user_data;
return !is_aborted;
};
wparams.encoder_begin_callback_user_data = &is_aborted;
}
if (whisper_full_parallel(ctx, wparams, pcmf32.data(), pcmf32.size(), params.n_processors) != 0) {
fprintf(stderr, "%s: failed to process audio\n", argv[0]);
return 10;
}
}
// output stuff
{
printf("\n");
// output to text file
if (params.output_txt) {
const auto fname_txt = fname_inp + ".txt";
output_txt(ctx, fname_txt.c_str());
}
// output to VTT file
if (params.output_vtt) {
const auto fname_vtt = fname_inp + ".vtt";
output_vtt(ctx, fname_vtt.c_str());
}
// output to SRT file
if (params.output_srt) {
const auto fname_srt = fname_inp + ".srt";
output_srt(ctx, fname_srt.c_str(), params);
}
// output to WTS file
if (params.output_wts) {
const auto fname_wts = fname_inp + ".wts";
output_wts(ctx, fname_wts.c_str(), fname_inp.c_str(), params, float(pcmf32.size() + 1000)/WHISPER_SAMPLE_RATE);
}
}
}
whisper_print_timings(ctx);
whisper_free(ctx);
return 0;
}
| 28,768
|
C++
|
.cpp
| 555
| 40.742342
| 211
| 0.505946
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,630
|
Logger.cpp
|
Const-me_Whisper/Examples/OldMain/Utils/Logger.cpp
|
#include <stdint.h>
#include <vector>
#include <cstdarg>
#include "Logger.h"
namespace
{
void logMessage( const char* lvl, const char8_t* pszFormat, std::va_list va )
{
fprintf( stderr, "%s: ", lvl );
vfprintf( stderr, (const char*)pszFormat, va );
fprintf( stderr, "\n" );
}
}
#define LOG_MESSAGE_IMPL( lvl ) \
std::va_list args; \
va_start( args, pszFormat ); \
logMessage( lvl, pszFormat, args ); \
va_end( args );
void logError( const char8_t* pszFormat, ... )
{
LOG_MESSAGE_IMPL( "Error" );
}
void logWarning( const char8_t* pszFormat, ... )
{
LOG_MESSAGE_IMPL( "Warning" );
}
void logInfo( const char8_t* pszFormat, ... )
{
LOG_MESSAGE_IMPL( "Info" );
}
void logDebug( const char8_t* pszFormat, ... )
{
LOG_MESSAGE_IMPL( "Debug" );
}
| 822
|
C++
|
.cpp
| 34
| 22.529412
| 78
| 0.616858
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,631
|
miscUtils.cpp
|
Const-me_Whisper/Examples/main/miscUtils.cpp
|
#include "miscUtils.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
std::string utf8( const std::wstring& utf16 )
{
int count = WideCharToMultiByte( CP_UTF8, 0, utf16.c_str(), (int)utf16.length(), nullptr, 0, nullptr, nullptr );
std::string str( count, 0 );
WideCharToMultiByte( CP_UTF8, 0, utf16.c_str(), -1, &str[ 0 ], count, nullptr, nullptr );
return str;
}
std::wstring utf16( const std::string& u8 )
{
int count = MultiByteToWideChar( CP_UTF8, 0, u8.c_str(), (int)u8.length(), nullptr, 0 );
std::wstring str( count, 0 );
MultiByteToWideChar( CP_UTF8, 0, u8.c_str(), (int)u8.length(), &str[ 0 ], count );
return str;
}
namespace
{
wchar_t* formatMessage( HRESULT hr )
{
wchar_t* err;
if( FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
hr,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
(LPTSTR)&err,
0,
NULL ) )
return err;
return nullptr;
}
}
void printError( const char* what, HRESULT hr )
{
const wchar_t* err = formatMessage( hr );
if( nullptr != err )
{
fwprintf( stderr, L"%S: %s\n", what, err );
LocalFree( (HLOCAL)err );
}
else
fprintf( stderr, "%s: error code %i (0x%08X)\n", what, hr, hr );
}
| 1,197
|
C++
|
.cpp
| 44
| 25.022727
| 113
| 0.671304
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,632
|
main.cpp
|
Const-me_Whisper/Examples/main/main.cpp
|
#include "params.h"
#include "../../Whisper/API/iContext.cl.h"
#include "../../Whisper/API/iMediaFoundation.cl.h"
#include "../../ComLightLib/comLightClient.h"
#include "miscUtils.h"
#include <array>
#include <atomic>
#include "textWriter.h"
using namespace Whisper;
#define STREAM_AUDIO 1
static HRESULT loadWhisperModel( const wchar_t* path, const std::wstring& gpu, iModel** pp )
{
using namespace Whisper;
sModelSetup setup;
setup.impl = eModelImplementation::GPU;
if( !gpu.empty() )
setup.adapter = gpu.c_str();
return Whisper::loadModel( path, setup, nullptr, pp );
}
namespace
{
// Terminal color map. 10 colors grouped in ranges [0.0, 0.1, ..., 0.9]
// Lowest is red, middle is yellow, highest is green.
static const std::array<const char*, 10> k_colors =
{
"\033[38;5;196m", "\033[38;5;202m", "\033[38;5;208m", "\033[38;5;214m", "\033[38;5;220m",
"\033[38;5;226m", "\033[38;5;190m", "\033[38;5;154m", "\033[38;5;118m", "\033[38;5;82m",
};
std::string to_timestamp( sTimeSpan ts, bool comma = false )
{
sTimeSpanFields fields = ts;
uint32_t msec = fields.ticks / 10'000;
uint32_t hr = fields.days * 24 + fields.hours;
uint32_t min = fields.minutes;
uint32_t sec = fields.seconds;
char buf[ 32 ];
snprintf( buf, sizeof( buf ), "%02d:%02d:%02d%s%03d", hr, min, sec, comma ? "," : ".", msec );
return std::string( buf );
}
static int colorIndex( const sToken& tok )
{
const float p = tok.probability;
const float p3 = p * p * p;
int col = (int)( p3 * float( k_colors.size() ) );
col = std::max( 0, std::min( (int)k_colors.size() - 1, col ) );
return col;
}
HRESULT __cdecl newSegmentCallback( iContext* context, uint32_t n_new, void* user_data ) noexcept
{
ComLight::CComPtr<iTranscribeResult> results;
CHECK( context->getResults( eResultFlags::Timestamps | eResultFlags::Tokens, &results ) );
sTranscribeLength length;
CHECK( results->getSize( length ) );
const whisper_params& params = *( (const whisper_params*)user_data );
// print the last n_new segments
const uint32_t s0 = length.countSegments - n_new;
if( s0 == 0 )
printf( "\n" );
const sSegment* const segments = results->getSegments();
const sToken* const tokens = results->getTokens();
for( uint32_t i = s0; i < length.countSegments; i++ )
{
const sSegment& seg = segments[ i ];
if( params.no_timestamps )
{
if( params.print_colors )
{
for( uint32_t j = 0; j < seg.countTokens; j++ )
{
const sToken& tok = tokens[ seg.firstToken + j ];
if( !params.print_special && ( tok.flags & eTokenFlags::Special ) )
continue;
wprintf( L"%S%s%S", k_colors[ colorIndex( tok ) ], utf16( tok.text ).c_str(), "\033[0m" );
}
}
else
wprintf( L"%s", utf16( seg.text ).c_str() );
fflush( stdout );
continue;
}
std::string speaker = "";
if( params.diarize )
{
eSpeakerChannel channel;
HRESULT hr = context->detectSpeaker( seg.time, channel );
if( SUCCEEDED( hr ) && channel != eSpeakerChannel::NoStereoData )
{
using namespace std::string_literals;
switch( channel )
{
case eSpeakerChannel::Unsure:
speaker = "(speaker ?)"s;
break;
case eSpeakerChannel::Left:
speaker = "(speaker 0)"s;
break;
case eSpeakerChannel::Right:
speaker = "(speaker 1)";
break;
}
}
}
if( params.print_colors )
{
printf( "[%s --> %s] %s ",
to_timestamp( seg.time.begin ).c_str(),
to_timestamp( seg.time.end ).c_str(),
speaker.c_str() );
for( uint32_t j = 0; j < seg.countTokens; j++ )
{
const sToken& tok = tokens[ seg.firstToken + j ];
if( !params.print_special && ( tok.flags & eTokenFlags::Special ) )
continue;
wprintf( L"%S%s%S", k_colors[ colorIndex( tok ) ], utf16( tok.text ).c_str(), "\033[0m" );
}
printf( "\n" );
}
else
wprintf( L"[%S --> %S] %S%s\n", to_timestamp( seg.time.begin ).c_str(), to_timestamp( seg.time.end ).c_str(), speaker.c_str(), utf16( seg.text ).c_str() );
}
return S_OK;
}
HRESULT __cdecl beginSegmentCallback( iContext* context, void* user_data ) noexcept
{
std::atomic_bool* flag = (std::atomic_bool*)user_data;
bool aborted = flag->load();
return aborted ? S_FALSE : S_OK;
}
HRESULT setupConsoleColors()
{
HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
if( h == INVALID_HANDLE_VALUE )
return HRESULT_FROM_WIN32( GetLastError() );
DWORD mode = 0;
if( !GetConsoleMode( h, &mode ) )
return HRESULT_FROM_WIN32( GetLastError() );
if( 0 != ( mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING ) )
return S_FALSE;
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if( !SetConsoleMode( h, mode ) )
return HRESULT_FROM_WIN32( GetLastError() );
return S_OK;
}
}
static void __stdcall setPrompt( const int* ptr, int length, void* pv )
{
std::vector<int>& vec = *( std::vector<int> * )( pv );
if( length > 0 )
vec.assign( ptr, ptr + length );
}
int wmain( int argc, wchar_t* argv[] )
{
// Whisper::dbgCompareTraces( LR"(C:\Temp\2remove\Whisper\ref.bin)", LR"(C:\Temp\2remove\Whisper\gpu.bin )" ); return 0;
// Tell logger to use the standard output stream for the messages
{
Whisper::sLoggerSetup logSetup;
logSetup.flags = eLoggerFlags::UseStandardError;
logSetup.level = eLogLevel::Debug;
Whisper::setupLogger( logSetup );
}
whisper_params params;
if( !params.parse( argc, argv ) )
return 1;
if( params.print_colors )
{
if( FAILED( setupConsoleColors() ) )
params.print_colors = false;
}
if( params.fname_inp.empty() )
{
fprintf( stderr, "error: no input files specified\n" );
whisper_print_usage( argc, argv, params );
return 2;
}
if( Whisper::findLanguageKeyA( params.language.c_str() ) == UINT_MAX )
{
fprintf( stderr, "error: unknown language '%s'\n", params.language.c_str() );
whisper_print_usage( argc, argv, params );
return 3;
}
ComLight::CComPtr<iModel> model;
HRESULT hr = loadWhisperModel( params.model.c_str(), params.gpu, &model );
if( FAILED( hr ) )
{
printError( "failed to load the model", hr );
return 4;
}
std::vector<int> prompt;
if( !params.prompt.empty() )
{
hr = model->tokenize( params.prompt.c_str(), &setPrompt, &prompt );
if( FAILED( hr ) )
{
printError( "failed to tokenize the initial prompt", hr );
return 5;
}
}
ComLight::CComPtr<iContext> context;
hr = model->createContext( &context );
if( FAILED( hr ) )
{
printError( "failed to initialize whisper context", hr );
return 6;
}
ComLight::CComPtr<iMediaFoundation> mf;
hr = initMediaFoundation( &mf );
if( FAILED( hr ) )
{
printError( "failed to initialize Media Foundation runtime", hr );
return 7;
}
for( const std::wstring& fname : params.fname_inp )
{
// print some info about the processing
{
if( model->isMultilingual() == S_FALSE )
{
if( params.language != "en" || params.translate )
{
params.language = "en";
params.translate = false;
fprintf( stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__ );
}
}
}
// run the inference
Whisper::sFullParams wparams;
context->fullDefaultParams( eSamplingStrategy::Greedy, &wparams );
wparams.resetFlag( eFullParamsFlags::PrintRealtime | eFullParamsFlags::PrintProgress );
wparams.setFlag( eFullParamsFlags::PrintTimestamps, !params.no_timestamps );
wparams.setFlag( eFullParamsFlags::PrintSpecial, params.print_special );
wparams.setFlag( eFullParamsFlags::Translate, params.translate );
// When there're multiple input files, assuming they're independent clips
wparams.setFlag( eFullParamsFlags::NoContext );
wparams.language = Whisper::makeLanguageKey( params.language.c_str() );
wparams.cpuThreads = params.n_threads;
if( params.max_context != UINT_MAX )
wparams.n_max_text_ctx = params.max_context;
wparams.offset_ms = params.offset_t_ms;
wparams.duration_ms = params.duration_ms;
wparams.setFlag( eFullParamsFlags::TokenTimestamps, params.output_wts || params.max_len > 0 );
wparams.thold_pt = params.word_thold;
wparams.max_len = params.output_wts && params.max_len == 0 ? 60 : params.max_len;
wparams.setFlag( eFullParamsFlags::SpeedupAudio, params.speed_up );
if( !prompt.empty() )
{
wparams.prompt_tokens = prompt.data();
wparams.prompt_n_tokens = (int)prompt.size();
}
// This callback is called on each new segment
if( !wparams.flag( eFullParamsFlags::PrintRealtime ) )
{
wparams.new_segment_callback = &newSegmentCallback;
wparams.new_segment_callback_user_data = ¶ms;
}
// example for abort mechanism
// in this example, we do not abort the processing, but we could if the flag is set to true
// the callback is called before every encoder run - if it returns false, the processing is aborted
std::atomic_bool is_aborted = false;
{
wparams.encoder_begin_callback = &beginSegmentCallback;
wparams.encoder_begin_callback_user_data = &is_aborted;
}
if( STREAM_AUDIO && !wparams.flag( eFullParamsFlags::TokenTimestamps ) )
{
ComLight::CComPtr<iAudioReader> reader;
CHECK( mf->openAudioFile( fname.c_str(), params.diarize, &reader ) );
sProgressSink progressSink{ nullptr, nullptr };
hr = context->runStreamed( wparams, progressSink, reader );
}
else
{
// Token-level timestamps feature is not currently implemented when streaming the audio
// When these timestamps are requested, fall back to buffered mode.
ComLight::CComPtr<iAudioBuffer> buffer;
CHECK( mf->loadAudioFile( fname.c_str(), params.diarize, &buffer ) );
hr = context->runFull( wparams, buffer );
}
if( FAILED( hr ) )
{
printError( "Unable to process audio", hr );
return 10;
}
if( params.output_txt )
{
bool timestamps = !params.no_timestamps;
hr = writeText( context, fname.c_str(), timestamps );
if( FAILED( hr ) )
printError( "Unable to produce the text file", hr );
}
if( params.output_srt )
{
hr = writeSubRip( context, fname.c_str() );
if( FAILED( hr ) )
printError( "Unable to produce the text file", hr );
}
if( params.output_vtt )
{
hr = writeWebVTT( context, fname.c_str() );
if( FAILED( hr ) )
printError( "Unable to produce the text file", hr );
}
}
context->timingsPrint();
context = nullptr;
return 0;
}
| 10,351
|
C++
|
.cpp
| 307
| 30.283388
| 160
| 0.672767
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,633
|
textWriter.cpp
|
Const-me_Whisper/Examples/main/textWriter.cpp
|
#include "textWriter.h"
#include "../../ComLightLib/comLightClient.h"
#include <array>
#define WIN32_LEAN_AND_MEAN
#include <pathcch.h>
#include <atlstr.h>
#include <atlfile.h>
#pragma comment(lib, "Pathcch.lib")
namespace
{
HRESULT replaceExtension( CString& path, LPCTSTR inputPath, LPCTSTR ext )
{
path = inputPath;
const size_t len = (size_t)path.GetLength() + 4;
wchar_t* buffer = path.GetBufferSetLength( (int)len );
const HRESULT hr = PathCchRenameExtension( buffer, len, ext );
path.ReleaseBuffer();
return hr;
}
// Abstract base class for text writers
class Writer
{
protected:
CAtlFile file;
virtual HRESULT impl( const Whisper::sSegment* const segments, const size_t length ) = 0;
public:
HRESULT write( Whisper::iContext* context, LPCTSTR audioPath, LPCTSTR ext )
{
CString path;
CHECK( replaceExtension( path, audioPath, ext ) );
CHECK( file.Create( path, GENERIC_WRITE, 0, CREATE_ALWAYS ) );
using namespace Whisper;
const eResultFlags resultFlags = eResultFlags::Timestamps | eResultFlags::Tokens;
ComLight::CComPtr<iTranscribeResult> result;
CHECK( context->getResults( resultFlags, &result ) );
sTranscribeLength len;
CHECK( result->getSize( len ) );
const sSegment* const segments = result->getSegments();
return impl( segments, len.countSegments );
}
};
HRESULT writeUtf8Bom( CAtlFile& file )
{
const std::array<uint8_t, 3> bom = { 0xEF, 0xBB, 0xBF };
return file.Write( bom.data(), 3 );
}
void printTime( CStringA& rdi, Whisper::sTimeSpan time, bool comma = false )
{
Whisper::sTimeSpanFields fields = time;
const uint32_t hours = fields.days * 24 + fields.hours;
const char separator = comma ? ',' : '.';
rdi.AppendFormat( "%02d:%02d:%02d%c%03d",
(int)hours,
(int)fields.minutes,
(int)fields.seconds,
separator,
fields.ticks / 10'000 );
}
const char* skipBlank( const char* rsi )
{
while( true )
{
const char c = *rsi;
if( c == ' ' || c == '\t' )
{
rsi++;
continue;
}
return rsi;
}
}
inline const char* cstr( const CStringA& s ) { return s; }
HRESULT writeString( CAtlFile& file, const CStringA& line )
{
if( line.GetLength() > 0 )
CHECK( file.Write( cstr( line ), (DWORD)line.GetLength() ) );
return S_OK;
}
// Writer for UTF-8 text files
class TextWriter : public Writer
{
const bool timestamps;
HRESULT impl( const Whisper::sSegment* const segments, const size_t length ) override final
{
CHECK( writeUtf8Bom( file ) );
using namespace Whisper;
CStringA line;
for( size_t i = 0; i < length; i++ )
{
const sSegment& seg = segments[ i ];
if( timestamps )
{
line = "[";
printTime( line, seg.time.begin );
line += " --> ";
printTime( line, seg.time.end );
line += "] ";
}
else
line = "";
line += skipBlank( seg.text );
line += "\r\n";
CHECK( writeString( file, line ) );
}
return S_OK;
}
public:
TextWriter( bool tt ) : timestamps( tt ) { }
};
// Writer for SubRip format: https://en.wikipedia.org/wiki/SubRip#SubRip_file_format
class SubRipWriter : public Writer
{
HRESULT impl( const Whisper::sSegment* const segments, const size_t length ) override final
{
CHECK( writeUtf8Bom( file ) );
using namespace Whisper;
CStringA line;
for( size_t i = 0; i < length; i++ )
{
const sSegment& seg = segments[ i ];
line.Format( "%zu\r\n", i + 1 );
printTime( line, seg.time.begin, true );
line += " --> ";
printTime( line, seg.time.end, true );
line += "\r\n";
line += skipBlank( seg.text );
line += "\r\n\r\n";
CHECK( writeString( file, line ) );
}
return S_OK;
}
};
// Writer for WebVTT format: https://en.wikipedia.org/wiki/WebVTT
class VttWriter : public Writer
{
HRESULT impl( const Whisper::sSegment* const segments, const size_t length ) override final
{
CHECK( writeUtf8Bom( file ) );
using namespace Whisper;
CStringA line;
line = "WEBVTT\r\n\r\n";
CHECK( writeString( file, line ) );
for( size_t i = 0; i < length; i++ )
{
const sSegment& seg = segments[ i ];
line = "";
printTime( line, seg.time.begin );
line += " --> ";
printTime( line, seg.time.end );
line += "\r\n";
line += skipBlank( seg.text );
line += "\r\n\r\n";
CHECK( writeString( file, line ) );
}
return S_OK;
}
};
}
HRESULT writeText( Whisper::iContext* context, LPCTSTR audioPath, bool timestamps )
{
TextWriter writer{ timestamps };
return writer.write( context, audioPath, L".txt" );
}
HRESULT writeSubRip( Whisper::iContext* context, LPCTSTR audioPath )
{
SubRipWriter writer;
return writer.write( context, audioPath, L".srt" );
}
HRESULT writeWebVTT( Whisper::iContext* context, LPCTSTR audioPath )
{
VttWriter writer;
return writer.write( context, audioPath, L".vtt" );
}
| 4,877
|
C++
|
.cpp
| 173
| 24.815029
| 93
| 0.661749
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,634
|
params.cpp
|
Const-me_Whisper/Examples/main/params.cpp
|
#include "params.h"
#include <algorithm>
#include <thread>
#include "miscUtils.h"
#include "../../Whisper/API/iContext.cl.h"
whisper_params::whisper_params()
{
#ifdef _DEBUG
n_threads = 2;
#else
n_threads = std::min( 4u, std::thread::hardware_concurrency() );
#endif
}
namespace
{
const char* cstr( bool b )
{
return b ? "true" : "false";
}
}
void whisper_print_usage( int argc, wchar_t** argv, const whisper_params& params )
{
fprintf( stderr, "\n" );
fprintf( stderr, "usage: %S [options] file0.wav file1.wav ...\n", argv[ 0 ] );
fprintf( stderr, "\n" );
fprintf( stderr, "options:\n" );
fprintf( stderr, " -h, --help [default] show this help message and exit\n" );
fprintf( stderr, " -la, --list-adapters List graphic adapters and exit\n" );
fprintf( stderr, " -gpu, --use-gpu The graphic adapter to use for inference\n" );
fprintf( stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads );
fprintf( stderr, " -p N, --processors N [%-7d] number of processors to use during computation\n", params.n_processors );
fprintf( stderr, " -ot N, --offset-t N [%-7d] time offset in milliseconds\n", params.offset_t_ms );
fprintf( stderr, " -on N, --offset-n N [%-7d] segment index offset\n", params.offset_n );
fprintf( stderr, " -d N, --duration N [%-7d] duration of audio to process in milliseconds\n", params.duration_ms );
fprintf( stderr, " -mc N, --max-context N [%-7d] maximum number of text context tokens to store\n", params.max_context );
fprintf( stderr, " -ml N, --max-len N [%-7d] maximum segment length in characters\n", params.max_len );
fprintf( stderr, " -wt N, --word-thold N [%-7.2f] word timestamp probability threshold\n", params.word_thold );
fprintf( stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", cstr( params.speed_up ) );
fprintf( stderr, " -tr, --translate [%-7s] translate from source language to english\n", cstr( params.translate ) );
fprintf( stderr, " -di, --diarize [%-7s] stereo audio diarization\n", cstr( params.diarize ) );
fprintf( stderr, " -otxt, --output-txt [%-7s] output result in a text file\n", cstr( params.output_txt ) );
fprintf( stderr, " -ovtt, --output-vtt [%-7s] output result in a vtt file\n", cstr( params.output_vtt ) );
fprintf( stderr, " -osrt, --output-srt [%-7s] output result in a srt file\n", cstr( params.output_srt ) );
fprintf( stderr, " -owts, --output-words [%-7s] output script for generating karaoke video\n", cstr( params.output_wts ) );
fprintf( stderr, " -ps, --print-special [%-7s] print special tokens\n", cstr( params.print_special ) );
fprintf( stderr, " -nc, --no-colors [%-7s] do not print colors\n", cstr( !params.print_colors ) );
fprintf( stderr, " -nt, --no-timestamps [%-7s] do not print timestamps\n", cstr( params.no_timestamps ) );
fprintf( stderr, " -l LANG, --language LANG [%-7s] spoken language\n", params.language.c_str() );
fprintf( stderr, " -m FNAME, --model FNAME [%-7S] model path\n", params.model.c_str() );
fprintf( stderr, " -f FNAME, --file FNAME [%-7s] path of the input audio file\n", "" );
fprintf( stderr, " --prompt initial prompt for the model\n" );
fprintf( stderr, "\n" );
}
static void __stdcall pfnListAdapter( const wchar_t* name, void* )
{
wprintf( L"\"%s\"\n", name );
}
static void listGpus()
{
printf( " Available graphic adapters:\n" );
HRESULT hr = Whisper::listGPUs( &pfnListAdapter, nullptr );
if( SUCCEEDED( hr ) )
return;
printError( "Unable to enumerate GPUs", hr );
}
bool whisper_params::parse( int argc, wchar_t* argv[] )
{
for( int i = 1; i < argc; i++ )
{
std::wstring arg = argv[ i ];
if( arg[ 0 ] != '-' )
{
fname_inp.push_back( arg );
continue;
}
if( arg == L"-h" || arg == L"--help" )
{
whisper_print_usage( argc, argv, *this );
return false;
}
if( arg == L"-la" || arg == L"--list-adapters" )
{
listGpus();
return false;
}
else if( arg == L"-t" || arg == L"--threads" ) { n_threads = std::stoul( argv[ ++i ] ); }
else if( arg == L"-p" || arg == L"--processors" ) { n_processors = std::stoul( argv[ ++i ] ); }
else if( arg == L"-ot" || arg == L"--offset-t" ) { offset_t_ms = std::stoul( argv[ ++i ] ); }
else if( arg == L"-on" || arg == L"--offset-n" ) { offset_n = std::stoul( argv[ ++i ] ); }
else if( arg == L"-d" || arg == L"--duration" ) { duration_ms = std::stoul( argv[ ++i ] ); }
else if( arg == L"-mc" || arg == L"--max-context" ) { max_context = std::stoul( argv[ ++i ] ); }
else if( arg == L"-ml" || arg == L"--max-len" ) { max_len = std::stoul( argv[ ++i ] ); }
else if( arg == L"-wt" || arg == L"--word-thold" ) { word_thold = std::stof( argv[ ++i ] ); }
else if( arg == L"-su" || arg == L"--speed-up" ) { speed_up = true; }
else if( arg == L"-tr" || arg == L"--translate" ) { translate = true; }
else if( arg == L"-di" || arg == L"--diarize" ) { diarize = true; }
else if( arg == L"-otxt" || arg == L"--output-txt" ) { output_txt = true; }
else if( arg == L"-ovtt" || arg == L"--output-vtt" ) { output_vtt = true; }
else if( arg == L"-osrt" || arg == L"--output-srt" ) { output_srt = true; }
else if( arg == L"-owts" || arg == L"--output-words" ) { output_wts = true; }
else if( arg == L"-ps" || arg == L"--print-special" ) { print_special = true; }
else if( arg == L"-nc" || arg == L"--no-colors" ) { print_colors = false; }
else if( arg == L"-nt" || arg == L"--no-timestamps" ) { no_timestamps = true; }
else if( arg == L"-l" || arg == L"--language" ) { language = utf8( argv[ ++i ] ); }
else if( arg == L"-m" || arg == L"--model" ) { model = argv[ ++i ]; }
else if( arg == L"-f" || arg == L"--file" ) { fname_inp.push_back( argv[ ++i ] ); }
else if( arg == L"-gpu" || arg == L"--use-gpu" ) { gpu = argv[ ++i ]; }
else if( arg == L"--prompt" ) { prompt = utf8( argv[ ++i ] ); }
else
{
fprintf( stderr, "error: unknown argument: %S\n", arg.c_str() );
whisper_print_usage( argc, argv, *this );
return false;
}
}
return true;
}
| 6,205
|
C++
|
.cpp
| 117
| 50.692308
| 129
| 0.583155
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,638
|
comLightCommon.h
|
Const-me_Whisper/ComLightLib/comLightCommon.h
|
#pragma once
#include "hresult.h"
#ifdef _MSC_VER
#include <guiddef.h>
#else
#include "pal/guiddef.h"
using LPCTSTR = const char*;
#endif
#include "unknwn.h"
| 159
|
C++
|
.h
| 9
| 16.555556
| 28
| 0.758389
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,641
|
comLightServer.h
|
Const-me_Whisper/ComLightLib/comLightServer.h
|
#pragma once
#include "comLightCommon.h"
#include "client/CComPtr.hpp"
#include "server/ObjectRoot.hpp"
#include "server/interfaceMap.h"
#include "server/Object.hpp"
#include "server/freeThreadedMarshaller.h"
#ifdef _MSC_VER
// On Windows, it's controlled by library.def module definition file. There's __declspec(dllexport), but it adds underscore, I don't like that.
#define DLLEXPORT extern "C"
#else
#define DLLEXPORT extern "C" __attribute__((visibility("default")))
#endif
| 480
|
C++
|
.h
| 13
| 35.846154
| 143
| 0.781116
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,644
|
hresult.h
|
Const-me_Whisper/ComLightLib/pal/hresult.h
|
#pragma once
#include <stdint.h>
using HRESULT = int32_t;
#define _HRESULT_TYPEDEF_(_sc) ((HRESULT)_sc)
#define SEVERITY_ERROR 1
#define FACILITY_CONTROL 10
inline constexpr HRESULT MAKE_SCODE( uint32_t sev, uint32_t fac, uint32_t code )
{
return (HRESULT)( ( (uint32_t)( sev ) << 31 ) | ( (unsigned long)( fac ) << 16 ) | ( (unsigned long)( code ) ) );
};
// ==== Copy-pasted from coreclr-master\src\pal\inc\rt\palrt.h ====
#define S_OK _HRESULT_TYPEDEF_(0x00000000L)
#define S_FALSE _HRESULT_TYPEDEF_(0x00000001L)
#define E_NOTIMPL _HRESULT_TYPEDEF_(0x80004001L)
#define E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L)
#define E_UNEXPECTED _HRESULT_TYPEDEF_(0x8000FFFFL)
#define E_OUTOFMEMORY _HRESULT_TYPEDEF_(0x8007000EL)
#define E_INVALIDARG _HRESULT_TYPEDEF_(0x80070057L)
#define E_POINTER _HRESULT_TYPEDEF_(0x80004003L)
#define E_HANDLE _HRESULT_TYPEDEF_(0x80070006L)
#define E_ABORT _HRESULT_TYPEDEF_(0x80004004L)
#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L)
#define E_ACCESSDENIED _HRESULT_TYPEDEF_(0x80070005L)
#define E_PENDING _HRESULT_TYPEDEF_(0x8000000AL)
#define DISP_E_PARAMNOTFOUND _HRESULT_TYPEDEF_(0x80020004L)
#define DISP_E_TYPEMISMATCH _HRESULT_TYPEDEF_(0x80020005L)
#define DISP_E_BADVARTYPE _HRESULT_TYPEDEF_(0x80020008L)
#define DISP_E_OVERFLOW _HRESULT_TYPEDEF_(0x8002000AL)
#define DISP_E_DIVBYZERO _HRESULT_TYPEDEF_(0x80020012L)
#define CLASS_E_CLASSNOTAVAILABLE _HRESULT_TYPEDEF_(0x80040111L)
#define CLASS_E_NOAGGREGATION _HRESULT_TYPEDEF_(0x80040110L)
#define CO_E_CLASSSTRING _HRESULT_TYPEDEF_(0x800401F3L)
#define MK_E_SYNTAX _HRESULT_TYPEDEF_(0x800401E4L)
#define STG_E_INVALIDFUNCTION _HRESULT_TYPEDEF_(0x80030001L)
#define STG_E_FILENOTFOUND _HRESULT_TYPEDEF_(0x80030002L)
#define STG_E_PATHNOTFOUND _HRESULT_TYPEDEF_(0x80030003L)
#define STG_E_WRITEFAULT _HRESULT_TYPEDEF_(0x8003001DL)
#define STG_E_FILEALREADYEXISTS _HRESULT_TYPEDEF_(0x80030050L)
#define STG_E_ABNORMALAPIEXIT _HRESULT_TYPEDEF_(0x800300FAL)
#define NTE_BAD_UID _HRESULT_TYPEDEF_(0x80090001L)
#define NTE_BAD_HASH _HRESULT_TYPEDEF_(0x80090002L)
#define NTE_BAD_KEY _HRESULT_TYPEDEF_(0x80090003L)
#define NTE_BAD_LEN _HRESULT_TYPEDEF_(0x80090004L)
#define NTE_BAD_DATA _HRESULT_TYPEDEF_(0x80090005L)
#define NTE_BAD_SIGNATURE _HRESULT_TYPEDEF_(0x80090006L)
#define NTE_BAD_VER _HRESULT_TYPEDEF_(0x80090007L)
#define NTE_BAD_ALGID _HRESULT_TYPEDEF_(0x80090008L)
#define NTE_BAD_FLAGS _HRESULT_TYPEDEF_(0x80090009L)
#define NTE_BAD_TYPE _HRESULT_TYPEDEF_(0x8009000AL)
#define NTE_BAD_KEY_STATE _HRESULT_TYPEDEF_(0x8009000BL)
#define NTE_BAD_HASH_STATE _HRESULT_TYPEDEF_(0x8009000CL)
#define NTE_NO_KEY _HRESULT_TYPEDEF_(0x8009000DL)
#define NTE_NO_MEMORY _HRESULT_TYPEDEF_(0x8009000EL)
#define NTE_SIGNATURE_FILE_BAD _HRESULT_TYPEDEF_(0x8009001CL)
#define NTE_FAIL _HRESULT_TYPEDEF_(0x80090020L)
#define CRYPT_E_HASH_VALUE _HRESULT_TYPEDEF_(0x80091007L)
#define TYPE_E_SIZETOOBIG _HRESULT_TYPEDEF_(0x800288C5L)
#define TYPE_E_DUPLICATEID _HRESULT_TYPEDEF_(0x800288C6L)
#define STD_CTL_SCODE(n) MAKE_SCODE(SEVERITY_ERROR, FACILITY_CONTROL, n)
#define CTL_E_OVERFLOW STD_CTL_SCODE(6)
#define CTL_E_OUTOFMEMORY STD_CTL_SCODE(7)
#define CTL_E_DIVISIONBYZERO STD_CTL_SCODE(11)
#define CTL_E_OUTOFSTACKSPACE STD_CTL_SCODE(28)
#define CTL_E_FILENOTFOUND STD_CTL_SCODE(53)
#define CTL_E_DEVICEIOERROR STD_CTL_SCODE(57)
#define CTL_E_PERMISSIONDENIED STD_CTL_SCODE(70)
#define CTL_E_PATHFILEACCESSERROR STD_CTL_SCODE(75)
#define CTL_E_PATHNOTFOUND STD_CTL_SCODE(76)
#define INET_E_CANNOT_CONNECT _HRESULT_TYPEDEF_(0x800C0004L)
#define INET_E_RESOURCE_NOT_FOUND _HRESULT_TYPEDEF_(0x800C0005L)
#define INET_E_OBJECT_NOT_FOUND _HRESULT_TYPEDEF_(0x800C0006L)
#define INET_E_DATA_NOT_AVAILABLE _HRESULT_TYPEDEF_(0x800C0007L)
#define INET_E_DOWNLOAD_FAILURE _HRESULT_TYPEDEF_(0x800C0008L)
#define INET_E_CONNECTION_TIMEOUT _HRESULT_TYPEDEF_(0x800C000BL)
#define INET_E_UNKNOWN_PROTOCOL _HRESULT_TYPEDEF_(0x800C000DL)
#define DBG_PRINTEXCEPTION_C _HRESULT_TYPEDEF_(0x40010006L)
// ==== Done pasting ====
inline constexpr bool SUCCEEDED( HRESULT hr )
{
return hr >= 0;
}
inline constexpr bool FAILED( HRESULT hr )
{
return hr < 0;
}
| 5,162
|
C++
|
.h
| 85
| 59.517647
| 114
| 0.633149
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,652
|
CommandLineArgs.h
|
Const-me_Whisper/Tools/compareTraces/CommandLineArgs.h
|
#pragma once
struct CommandLineArgs
{
int64_t printDiff = -1;
std::array<CString, 2> inputs;
bool parse( int argc, wchar_t* argv[] );
};
| 141
|
C++
|
.h
| 7
| 18.571429
| 41
| 0.714286
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,653
|
TraceReader.h
|
Const-me_Whisper/Tools/compareTraces/TraceReader.h
|
#pragma once
#include "../../Whisper/Utils/Trace/TraceStructures.h"
#include <atlstr.h>
#include <atlfile.h>
namespace Tracing
{
class TraceReader
{
const uint8_t* payloadPointer = nullptr;
const sTraceItem* items = nullptr;
size_t countItems = 0;
size_t countStrings = 0;
const uint32_t* stringIndex = nullptr;
const char* stringData = nullptr;
CAtlFile file;
CAtlFileMapping<uint8_t> mapping;
public:
TraceReader() = default;
~TraceReader() = default;
HRESULT open( LPCTSTR path );
size_t size() const { return countItems; }
const sTraceItem& operator[]( size_t idx ) const;
CStringA getName( const sTraceItem& item ) const;
const void* payload( const sTraceItem& item ) const
{
return payloadPointer + item.payloadOffset;
}
};
}
| 778
|
C++
|
.h
| 29
| 24.241379
| 54
| 0.733871
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,654
|
stdafx.h
|
Const-me_Whisper/Tools/compareTraces/stdafx.h
|
#pragma once
#include <stdint.h>
#include <assert.h>
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <atlstr.h>
#include <d3d11.h>
#include <vector>
#include <array>
#include <emmintrin.h>
#include <smmintrin.h>
#define CHECK( hr ) { const HRESULT __hr = ( hr ); if( FAILED( __hr ) ) return __hr; }
inline __m128i load16( const int* rsi )
{
return _mm_loadu_si128( ( const __m128i* )rsi );
}
inline __m128i load16( const uint32_t* rsi )
{
return _mm_loadu_si128( ( const __m128i* )rsi );
}
inline __m128i load( const std::array<uint32_t, 4>& arr )
{
return load16( arr.data() );
}
inline bool vectorEqual( __m128i a, __m128i b )
{
__m128i xx = _mm_xor_si128( a, b );
return (bool)_mm_testz_si128( xx, xx );
}
void printError( HRESULT hr );
inline const char* cstr( const CStringA& s ) { return s; }
inline const wchar_t* cstr( const CString& s ) { return s; }
| 898
|
C++
|
.h
| 33
| 25.878788
| 86
| 0.67986
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,655
|
compare.h
|
Const-me_Whisper/Tools/compareTraces/compare.h
|
#pragma once
#include "CommandLineArgs.h"
HRESULT compareTraces( const CommandLineArgs& arguments );
| 101
|
C++
|
.h
| 3
| 32.666667
| 58
| 0.836735
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,656
|
stdafx.h
|
Const-me_Whisper/Whisper/stdafx.h
|
#pragma once
#define _USE_MATH_DEFINES
#include <stdint.h>
#include <assert.h>
#include <array>
#include <vector>
#include <algorithm>
#include <emmintrin.h> // SSE 2
#include <smmintrin.h> // SSE 4.1
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
// Setup Windows SDK to only enable features available since Windows 8.0
#include <WinSDKVer.h>
#define _WIN32_WINNT _WIN32_WINNT_WIN8
#define NTDDI_VERSION NTDDI_WIN8
#include <sdkddkver.h>
#include <windows.h>
#define _XM_SSE4_INTRINSICS_
#include <d3d11.h>
#include <DirectXMath.h>
#include <atlcomcli.h>
#include "Utils/Logger.h"
#include "Utils/miscUtils.h"
// Build both legacy and DirectCompute implementations
#define BUILD_BOTH_VERSIONS 0
// Build hybrid model which uses DirectCompute only for the encode step of the algorithm, and decodes on CPU, using AVX SIMD and the Windows' built-in thread pool.
// Disabled because on all computers I have in this house that hybrid model performed worse than D3D11 GPGPU model
#define BUILD_HYBRID_VERSION 0
// Enable debug traces. Should be disabled in production, the feature comes with a huge performance overhead.
// When enabled, while computing things it streams gigabytes of data into that binary file.
// See Tools / compareTraces project for a command-line app to compare these traces.
#define SAVE_DEBUG_TRACE 0
// Initialize tensors with NaN numbers, and test for NaN values in the outputs tensors
// Incompatible with SAVE_DEBUG_TRACE macro
// When enabled, it stalls GPU pipelining pretty often. This is not great for performance, should be disabled in production.
#define DBG_TEST_NAN 0
// In addition to collecting total GPU times per compute shader, also collect and print performance data about individual invocations of some of the most expensive shaders
// The feature is relatively cheap in terms of performance overhead, but pretty much useless in production, and clutters debug console with all these numbers
#define PROFILER_COLLECT_TAGS 0
| 1,967
|
C++
|
.h
| 39
| 49.230769
| 171
| 0.8
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,657
|
modelFactory.h
|
Const-me_Whisper/Whisper/modelFactory.h
|
#pragma once
#include "API/sLoadModelCallbacks.h"
#include "API/sModelSetup.h"
namespace Whisper
{
struct iModel;
HRESULT __stdcall loadGpuModel( const wchar_t* path, const sModelSetup& setup, const sLoadModelCallbacks* callbacks, iModel** pp );
HRESULT __stdcall loadReferenceCpuModel( const wchar_t* path, iModel** pp );
}
| 330
|
C++
|
.h
| 9
| 35.111111
| 132
| 0.786834
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,658
|
downloadBuffer.h
|
Const-me_Whisper/Whisper/D3D/downloadBuffer.h
|
#pragma once
namespace DirectCompute
{
// Download a buffer from VRAM into std::vector
// The function is relatively expensive, creates a temporary staging buffer on each call, and only used to test things.
template<class E>
HRESULT downloadBuffer( ID3D11ShaderResourceView* srv, std::vector<E>& vec );
}
| 309
|
C++
|
.h
| 8
| 37.125
| 120
| 0.790698
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,659
|
createBuffer.h
|
Const-me_Whisper/Whisper/D3D/createBuffer.h
|
#pragma once
#include "enums.h"
#include "device.h"
namespace DirectCompute
{
HRESULT createBuffer( eBufferUse use, size_t totalBytes, ID3D11Buffer** ppGpuBuffer, const void* rsi, ID3D11Buffer** ppStagingBuffer, bool shared = false );
}
| 238
|
C++
|
.h
| 7
| 32.857143
| 157
| 0.792208
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,660
|
createDevice.h
|
Const-me_Whisper/Whisper/D3D/createDevice.h
|
// Low-level functions to create and initialize D3D11 device
#pragma once
#include <string>
#include "sGpuInfo.h"
namespace DirectCompute
{
HRESULT createDevice( const std::wstring& adapter, ID3D11Device** dev, ID3D11DeviceContext** context );
HRESULT validateFlags( uint32_t flags );
HRESULT queryDeviceInfo( sGpuInfo& rdi, ID3D11Device* dev, uint32_t flags );
// Create another device and context, on the same hardware GPU
HRESULT cloneDevice( ID3D11Device* source, ID3D11Device** dev, ID3D11DeviceContext** context );
}
| 531
|
C++
|
.h
| 12
| 42.583333
| 104
| 0.794574
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,661
|
MappedResource.h
|
Const-me_Whisper/Whisper/D3D/MappedResource.h
|
#pragma once
#include "device.h"
#include <assert.h>
namespace DirectCompute
{
class MappedResource
{
D3D11_MAPPED_SUBRESOURCE mapped;
ID3D11Resource* resource;
public:
MappedResource();
HRESULT map( ID3D11Resource* res, bool reading );
~MappedResource();
void* data() const
{
assert( nullptr != mapped.pData );
return mapped.pData;
}
};
}
| 367
|
C++
|
.h
| 20
| 16
| 51
| 0.736994
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,662
|
sGpuInfo.h
|
Const-me_Whisper/Whisper/D3D/sGpuInfo.h
|
#pragma once
#include <stdint.h>
namespace DirectCompute
{
// DXGI_ADAPTER_DESC.VendorId magic numbers; they come from that database: https://pcisig.com/membership/member-companies
enum struct eGpuVendor : uint16_t
{
AMD = 0x1002,
NVidia = 0x10de,
Intel = 0x8086,
VMWare = 0x15ad,
};
enum struct eGpuEffectiveFlags : uint8_t
{
Wave64 = 1,
ReshapedMatMul = 2,
Cloneable = 4,
};
struct sGpuInfo
{
eGpuEffectiveFlags flags;
eGpuVendor vendor;
uint16_t device, revision;
uint32_t subsystem;
size_t vramDedicated, ramDedicated, ramShared;
std::wstring description;
inline bool wave64() const
{
return 0 != ( (uint8_t)flags & (uint8_t)eGpuEffectiveFlags::Wave64 );
}
// On nVidia 1080Ti that approach is much slower, by a factor of 2.4
// On AMD Cezanne that approach is faster by a factor of 0.69, i.e. 30% faster.
// Dunno why that is, maybe 'coz on that AMD complete panels fit in L3 cache.
// Anyway, we do want extra 30% perf on AMD Cezanne, so only using that code on AMD GPUs.
// Dunno how it gonna behave on other GPUs, need to test.
inline bool useReshapedMatMul() const
{
return 0 != ( (uint8_t)flags & (uint8_t)eGpuEffectiveFlags::ReshapedMatMul );
}
inline bool cloneableModel() const
{
return 0 != ( (uint8_t)flags & (uint8_t)eGpuEffectiveFlags::Cloneable );
}
};
}
| 1,351
|
C++
|
.h
| 45
| 27.288889
| 122
| 0.721752
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,663
|
device.h
|
Const-me_Whisper/Whisper/D3D/device.h
|
#pragma once
#include <atlcomcli.h>
#include <string>
#include "sGpuInfo.h"
namespace DirectCompute
{
ID3D11Device* device();
ID3D11DeviceContext* context();
const sGpuInfo& gpuInfo();
inline void csSetCB( ID3D11Buffer* cb )
{
context()->CSSetConstantBuffers( 0, 1, &cb );
}
__m128i bufferMemoryUsage( ID3D11Buffer* buffer );
__m128i resourceMemoryUsage( ID3D11ShaderResourceView* srv );
}
| 403
|
C++
|
.h
| 16
| 23.375
| 62
| 0.768229
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,664
|
enums.h
|
Const-me_Whisper/Whisper/D3D/enums.h
|
#pragma once
#include <stdint.h>
#include <assert.h>
namespace DirectCompute
{
enum struct eDataType : uint8_t
{
FP16,
FP32,
U32,
};
inline size_t elementSize( eDataType dt )
{
assert( dt == eDataType::FP16 || dt == eDataType::FP32 || dt == eDataType::U32 );
return ( dt == eDataType::FP16 ) ? 2 : 4;
}
DXGI_FORMAT viewFormat( eDataType dt );
enum struct eBufferUse : uint8_t
{
// Immutable tensor, readable from GPU
Immutable,
// Read+write tensor, readable and writable on GPU
ReadWrite,
// Read+write tensor, readable and writable on GPU, which supports downloads from GPU
ReadWriteDownload,
// The tensor is accessible by both GPU (read only) and CPU (write only). Optimized for resources frequently updated from CPU.
Dynamic,
};
}
| 776
|
C++
|
.h
| 29
| 24.37931
| 128
| 0.7214
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,665
|
Binder.h
|
Const-me_Whisper/Whisper/D3D/Binder.h
|
#pragma once
#include "device.h"
namespace DirectCompute
{
class Binder
{
uint8_t maxSrv = 0;
uint8_t maxUav = 0;
public:
Binder() = default;
Binder( const Binder& ) = delete;
void bind( ID3D11ShaderResourceView* srv0, ID3D11UnorderedAccessView* uav0 );
void bind( ID3D11ShaderResourceView* srv0, ID3D11ShaderResourceView* srv1, ID3D11UnorderedAccessView* uav0 );
void bind( std::initializer_list<ID3D11ShaderResourceView*> srvs, std::initializer_list<ID3D11UnorderedAccessView*> uavs );
void bind( ID3D11UnorderedAccessView* uav0 );
~Binder();
};
}
| 574
|
C++
|
.h
| 18
| 29.555556
| 125
| 0.770758
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,666
|
shaderNames.h
|
Const-me_Whisper/Whisper/D3D/shaderNames.h
|
// This header is generated by a tool
#pragma once
#include <stdint.h>
namespace DirectCompute
{
enum struct eComputeShader: uint16_t
{
add = 0,
addInPlace = 1,
addRepeat = 2,
addRepeatEx = 3,
addRepeatGelu = 4,
addRepeatScale = 5,
addRows = 6,
convolutionMain = 7,
convolutionMain2 = 8,
convolutionMain2Fixed = 9,
convolutionPrep1 = 10,
convolutionPrep2 = 11,
copyConvert = 12,
copyTranspose = 13,
dbgFindNaN = 14,
diagMaskInf = 15,
flashAttention = 16,
flashAttentionCompat1 = 17,
flashAttentionCompat2 = 18,
flashAttentionCompat3 = 19,
fmaRepeat1 = 20,
fmaRepeat2 = 21,
matReshapePanels = 22,
mulMatByRow = 23,
mulMatByRowTiled = 24,
mulMatByRowTiledEx = 25,
mulMatByScalar = 26,
mulMatDotMain = 27,
mulMatDotReshape = 28,
mulMatMadMain = 29,
mulMatTiled = 30,
mulMatTiledEx = 31,
norm = 32,
normCompat = 33,
normFixed = 34,
scaleInPlace = 35,
softMax = 36,
softMaxCompat = 37,
softMaxFixed = 38,
softMaxLong = 39,
zeroMemory = 40,
};
const char* computeShaderName( eComputeShader cs );
}
| 1,079
|
C++
|
.h
| 51
| 18.45098
| 52
| 0.721519
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,667
|
shaders.h
|
Const-me_Whisper/Whisper/D3D/shaders.h
|
#pragma once
#include "shaderNames.h"
namespace DirectCompute
{
HRESULT createComputeShaders( std::vector<CComPtr<ID3D11ComputeShader>>& shaders );
void bindShader( eComputeShader shader );
}
| 195
|
C++
|
.h
| 7
| 26.428571
| 84
| 0.823529
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,668
|
listGPUs.h
|
Const-me_Whisper/Whisper/D3D/listGPUs.h
|
#pragma once
#include <API/iContext.cl.h>
namespace DirectCompute
{
CComPtr<IDXGIAdapter1> selectAdapter( const std::wstring& requestedName );
}
| 146
|
C++
|
.h
| 6
| 23.166667
| 75
| 0.814286
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,670
|
renderDoc.h
|
Const-me_Whisper/Whisper/D3D/RenderDoc/renderDoc.h
|
#pragma once
namespace DirectCompute
{
bool initializeRenderDoc();
class CaptureRaii
{
bool capturing;
public:
CaptureRaii();
CaptureRaii( const CaptureRaii& ) = delete;
~CaptureRaii();
};
}
| 205
|
C++
|
.h
| 13
| 13.692308
| 45
| 0.759162
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,671
|
HybridLoader.h
|
Const-me_Whisper/Whisper/CPU/HybridLoader.h
|
#pragma once
#include "DecoderTensors.h"
#include <atlstr.h>
#include <atlcoll.h>
#include "../../ComLightLib/streams.h"
namespace CpuCompute
{
__interface iLoaderProgressSink
{
HRESULT gotBytes( int64_t cb );
};
class HybridLoader
{
DecoderTensors& destination;
CAtlMap<CStringA, Tensor*> map;
size_t bufferBytes = 0;
struct alignas( 32 ) PendingTensor
{
Tensor* destPointer = nullptr;
int64_t streamOffset = 0;
size_t bufferOffset = 0;
size_t payloadBytes = 0;
};
std::vector<PendingTensor> pending;
public:
HybridLoader( DecoderTensors& m, int countLayers );
HRESULT setupTensor( const CStringA& name, int n_dims, int ftype, const std::array<int, 4>& ne, ComLight::iReadStream* stream, int64_t& postponedBytes );
HRESULT completeLoad( ComLight::iReadStream* stream, iLoaderProgressSink& progressSink );
};
}
| 858
|
C++
|
.h
| 30
| 26.033333
| 155
| 0.745742
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,672
|
MlContext.h
|
Const-me_Whisper/Whisper/CPU/MlContext.h
|
#pragma once
#include "Tensor.h"
#include "ParallelForRunner.h"
namespace CpuCompute
{
class MlContext
{
ParallelForRunner pfor;
iMemoryAllocator* allocator = nullptr;
public:
MlContext( int threads );
MlContext( const MlContext& ) = delete;
~MlContext() = default;
HRESULT setThreadsCount( int threads )
{
return pfor.setThreadsCount( threads );
}
iMemoryAllocator* setAllocator( iMemoryAllocator* alloc )
{
iMemoryAllocator* const ret = allocator;
allocator = alloc;
return ret;
}
Tensor createTensor( eDataType type, const std::array<uint32_t, 4>& size );
Tensor createTensor( eDataType type, std::initializer_list<uint32_t> size );
Tensor addRows( const Tensor& d_te, const Tensor& d_pe, const int* tokens, const int n_tokens, const int n_past );
Tensor norm( const Tensor& arg );
// cur = add( mul( repeat( w, cur ), cur ), repeat( b, cur ) );
void fmaRepeat( Tensor& cur, const Tensor& w, const Tensor& b );
inline void fmaRepeat( Tensor& cur, const TensorPair wb )
{
fmaRepeat( cur, wb.w, wb.b );
}
// Multiply two matrices
Tensor mulMat( const Tensor& a, const Tensor& b );
// cur = add( repeat( b, cur ), cur ); cur = scale(cur, scaling)
void addRepeatScale( Tensor& cur, const Tensor& b, float scaling );
void addRepeat( Tensor& cur, const Tensor& b );
Tensor add( const Tensor& a, const Tensor& b );
void addInPlace( Tensor& a, const Tensor& b );
void addRepeatGelu( Tensor& cur, const Tensor& b );
// cur = scale(cur, scaling)
void scale( Tensor& cur, float scaling );
void diagMaskInf( Tensor& cur, uint32_t n_past );
void softMax( Tensor& cur, float inputScale = 1.0f );
Tensor copy( const Tensor& a, eDataType type, std::initializer_list<uint32_t> size );
HRESULT copyImpl( Tensor& result, const Tensor& source );
Tensor permute( const Tensor& a, uint8_t axis0, uint8_t axis1, uint8_t axis2, uint8_t axis3 );
void copyInPlace( Tensor& dest, const Tensor& a, eDataType type, std::initializer_list<uint32_t> size );
};
}
| 2,044
|
C++
|
.h
| 51
| 36.921569
| 116
| 0.7077
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,673
|
KvTensors.h
|
Const-me_Whisper/Whisper/CPU/KvTensors.h
|
#pragma once
#include "Tensor.h"
#include "LargeBuffer.h"
#include "../Whisper/sModelParams.h"
namespace CpuCompute
{
class KvTensors
{
uint16_t* keys = nullptr;
uint16_t* values = nullptr;
uint32_t size = 0;
CpuCompute::LargeBuffer memory;
public:
// Create these two large tensors, FP16 precision
HRESULT create( const Whisper::sModelParams& mp );
// A slice of model.memory_cross_k tensor
Tensor keysView( uint32_t len, uint32_t off ) const
{
if( len + off <= size )
return Tensor::fromData( keys + off, eDataType::FP16, len );
throw E_BOUNDS;
}
// A slice of model.memory_cross_v tensor
Tensor valuesView( uint32_t len, uint32_t off ) const
{
if( len + off <= size )
return Tensor::fromData( values + off, eDataType::FP16, len );
throw E_BOUNDS;
}
};
}
| 813
|
C++
|
.h
| 31
| 23.419355
| 66
| 0.696658
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,674
|
Tensor.h
|
Const-me_Whisper/Whisper/CPU/Tensor.h
|
#pragma once
#include "../D3D/enums.h"
#include "../ML/TensorShape.h"
// 1 = new tensors can be allocated with `nullptr` iMemoryAllocator, by allocating memory internally and counting these references
// 0 = memory allocator is mandatory, create() methods will fail with E_POINTER if the allocator is `nullptr`
#define TENSOR_INTERNAL_ALLOC 0
// 1 = expose compatibility API for GGML interop
#define TENSOR_GGML_COMPAT 0
#if TENSOR_GGML_COMPAT
#include "../source/ggml.h"
#endif
namespace CpuCompute
{
using DirectCompute::TensorShape;
using DirectCompute::eDataType;
__interface iMemoryAllocator
{
void* allocate( size_t cb, size_t align );
};
__interface iArenaAllocator : public iMemoryAllocator
{
void resetArena();
};
#if TENSOR_GGML_COMPAT
class Tensor;
class GgmlTensorView
{
ggml_tensor tensor;
public:
GgmlTensorView( const Tensor& t );
operator ggml_tensor* ( ) { return &tensor; }
};
#endif
// A functional equivalent of ggml_tensor structure, designed for use from C++
class Tensor : public TensorShape
{
void* m_data = nullptr;
eDataType m_type = (eDataType)0xFF;
#if TENSOR_INTERNAL_ALLOC
// True when the memory block was allocated internally by this class
// In this case, this class does reference counting to support cheap copies.
// False when it's owned by someone else, such as iMemoryAllocator object, or a GGML's tensor
bool ownsMemory = false;
void deallocate();
#endif
// Private constructors for fromData() methods
Tensor( void* pointer, eDataType type, std::initializer_list<uint32_t> size );
Tensor( void* pointer, eDataType type, uint32_t length ) noexcept;
public:
// Trivial constructors
Tensor() = default;
#if TENSOR_INTERNAL_ALLOC
~Tensor()
{
deallocate();
}
#else
~Tensor() = default;
#endif
Tensor( Tensor&& that ) noexcept;
void operator=( Tensor&& that ) noexcept;
Tensor( const Tensor& that );
void operator=( const Tensor& that );
// Allocate a new tensor
HRESULT create( eDataType type, const std::array<uint32_t, 4>& sizeElements, iMemoryAllocator* alloc = nullptr );
// Allocate a new tensor
HRESULT create( eDataType type, std::initializer_list<uint32_t> sizeElements, iMemoryAllocator* alloc = nullptr );
// Attach to pre-existing block of memory, interpreting the data as a dense tensor of the specified type and size
HRESULT attach( void* pointer, eDataType type, std::initializer_list<uint32_t> sizeElements );
// Attach to pre-existing block of memory, interpret the data as a dense vector of the specified type and length
static Tensor fromData( void* pointer, eDataType type, uint32_t length );
eDataType type() const { return m_type; }
void* data() const { return m_data; }
uint16_t* fp16()
{
assert( m_type == eDataType::FP16 );
assert( nullptr != m_data );
return (uint16_t*)m_data;
}
const uint16_t* fp16() const
{
assert( m_type == eDataType::FP16 );
assert( nullptr != m_data );
return (uint16_t*)m_data;
}
float* fp32()
{
assert( m_type == eDataType::FP32 );
assert( nullptr != m_data );
return (float*)m_data;
}
const float* fp32() const
{
assert( m_type == eDataType::FP32 );
assert( nullptr != m_data );
return (float*)m_data;
}
Tensor reshape3d( uint32_t ne0, uint32_t ne1, uint32_t ne2 ) const;
void setType( eDataType dt )
{
m_type = dt;
}
void setDataPointer( void* pv )
{
m_data = pv;
}
#if TENSOR_GGML_COMPAT
// Compatibility with GGML's tensors, for testing and lulz
Tensor( const ggml_tensor* ggml );
ggml_tensor ggml() const;
operator GgmlTensorView() const
{
return GgmlTensorView( *this );
}
#endif
};
// A pair of tensors containing weights and biases; apparently, both tensors are of the same shape
struct TensorPair
{
Tensor w, b;
};
}
| 3,819
|
C++
|
.h
| 122
| 28.598361
| 130
| 0.721543
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,675
|
simdUtils.h
|
Const-me_Whisper/Whisper/CPU/simdUtils.h
|
#pragma once
#include <immintrin.h>
void addF16to32( float* rdi, const uint16_t* a, const uint16_t* b, size_t length );
void addF16to32( float* rdi, const uint16_t* a, const float* b, size_t length );
class AlignedSpan
{
float* pointer;
public:
AlignedSpan( void* data )
{
size_t i = (size_t)data;
constexpr size_t mask32 = ~(size_t)31;
i = ( i + 31 ) & mask32;
pointer = (float*)i;
}
operator float* ( ) { return pointer; }
};
inline size_t tempBufferForFloats( size_t count )
{
// Round up by 8 to be able to use full-vector loads and stores
constexpr size_t mask8 = ~(size_t)7;
count = ( count + 7 ) & mask8;
// Add 32 more bytes to align the temporary buffer
return ( count * 4 ) + 32;
}
#define ALIGNED_SPAN( name, countFloats ) AlignedSpan name{ _alloca( tempBufferForFloats( countFloats ) ) }
void norm( float* rdi, float* temp, const float* rsi, size_t length );
void fmaRepeatRow( float* rdi, size_t len, const float* w, const float* b, size_t lenPattern );
void __vectorcall addRepeatScaleRow( float* rdi, size_t len, const float* b, size_t lenPattern, const __m256 scale );
void addRepeatRow( float* rdi, size_t len, const float* b, size_t lenPattern );
void __vectorcall scaleRow( float* rdi, size_t len, const __m256 scale );
namespace DirectCompute
{
struct LookupTablesData;
}
const DirectCompute::LookupTablesData& getLookupTables();
void addRepeatGeluRow( float* rdi, size_t len, const float* b, size_t lenPattern, const DirectCompute::LookupTablesData& lookup );
void softMax( float* rdi, size_t length, const float inputScale );
// A cache line-aligned array where first 8 elements have all bits set, last 8 elements are zeros
extern const std::array<int, 16> s_zeroTailMask;
// Load a tail mask as FP32 vector, for use with _mm256_and_ps or _mm256_blendv_ps instructions
__forceinline __m256 loadTailMaskFloats( size_t remainder )
{
assert( remainder > 0 && remainder < 8 );
const float* rsi = (const float*)&s_zeroTailMask;
rsi += 8;
return _mm256_loadu_ps( rsi - remainder );
}
// Load a tail mask as int32 vector, for use with _mm256_maskstore_ps instruction
template<bool assertIncomplete = true>
__forceinline __m256i loadTailMaskInt( size_t remainder )
{
if constexpr( assertIncomplete )
assert( remainder > 0 && remainder < 8 );
else
assert( remainder >= 0 && remainder <= 8 );
const int* rsi = (const int*)&s_zeroTailMask;
rsi += 8;
return _mm256_loadu_si256( ( const __m256i* )( rsi - remainder ) );
}
void floatsUpcast( float* rdi, const uint16_t* rsi, size_t length );
void floatsDowncast( uint16_t* rdi, const float* rsi, size_t length );
void addRowInPlace( float* rdi, const float* rsi, size_t length );
void addRow( float* rdi, const float* a, const float* b, size_t length );
| 2,761
|
C++
|
.h
| 64
| 41.375
| 130
| 0.725
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,676
|
DecoderTensors.h
|
Const-me_Whisper/Whisper/CPU/DecoderTensors.h
|
#pragma once
#include <vector>
#include "Tensor.h"
#include "LargeBuffer.h"
#if TENSOR_GGML_COMPAT
#include "../source/ggml.h"
#endif
namespace CpuCompute
{
// A set of tensors for one decoder's layer
struct LayerDecoder
{
// decoder.blocks.*.attn_ln
TensorPair attnLn0;
// decoder.blocks.*.attn.out
TensorPair attnLn1;
// decoder.blocks.*.attn.query
TensorPair attnQuery;
// decoder.blocks.*.attn.key
Tensor attnKey;
// decoder.blocks.*.attn.value
TensorPair attnValue;
// decoder.blocks.*.cross_attn_ln
TensorPair crossAttnLn0;
// decoder.blocks.*.cross_attn.out
TensorPair crossAttnLn1;
// decoder.blocks.*.cross_attn.query
TensorPair crossAttnQuery;
// decoder.blocks.*.cross_attn.key
// Tensor crossAttnKey;
// decoder.blocks.*.cross_attn.value
// TensorPair crossAttnValue;
// decoder.blocks.*.mlp_ln
TensorPair mlpLn;
// decoder.blocks.*.mlp.0
TensorPair mlp0;
// decoder.blocks.*.mlp.2
TensorPair mlp1;
#if TENSOR_GGML_COMPAT
// decoder.blocks.*.attn_ln
ggml_tensor* attn_ln_0_w;
ggml_tensor* attn_ln_0_b;
// decoder.blocks.*.attn.out
ggml_tensor* attn_ln_1_w;
ggml_tensor* attn_ln_1_b;
// decoder.blocks.*.attn.query
ggml_tensor* attn_q_w;
ggml_tensor* attn_q_b;
// decoder.blocks.*.attn.key
ggml_tensor* attn_k_w;
// decoder.blocks.*.attn.value
ggml_tensor* attn_v_w;
ggml_tensor* attn_v_b;
// decoder.blocks.*.cross_attn_ln
ggml_tensor* cross_attn_ln_0_w;
ggml_tensor* cross_attn_ln_0_b;
// decoder.blocks.*.cross_attn.out
ggml_tensor* cross_attn_ln_1_w;
ggml_tensor* cross_attn_ln_1_b;
// decoder.blocks.*.cross_attn.query
ggml_tensor* cross_attn_q_w;
ggml_tensor* cross_attn_q_b;
// decoder.blocks.*.mlp_ln
ggml_tensor* mlp_ln_w;
ggml_tensor* mlp_ln_b;
// decoder.blocks.*.mlp.0
ggml_tensor* mlp_0_w;
ggml_tensor* mlp_0_b;
// decoder.blocks.*.mlp.2
ggml_tensor* mlp_1_w;
ggml_tensor* mlp_1_b;
#endif
};
struct DecoderTensors
{
// decoder.positional_embedding
Tensor positionalEmbedding;
// decoder.token_embedding
Tensor tokenEmbedding;
// decoder.ln
TensorPair ln;
// A vector of layers
std::vector<LayerDecoder> layers;
void setMemoryBuffer( LargeBuffer&& mem ) noexcept
{
memory = std::move( mem );
#if TENSOR_GGML_COMPAT
makeCompatTensors();
#endif
}
#if TENSOR_GGML_COMPAT
void makeCompatTensors();
// decoder.positional_embedding
ggml_tensor* d_pe; // DD
// decoder.token_embedding
ggml_tensor* d_te; // DD
// decoder.ln
ggml_tensor* d_ln_w; // DD
ggml_tensor* d_ln_b; // DD
#endif
private:
// A smart pointer which owns the memory for all the above tensors
LargeBuffer memory;
#if TENSOR_GGML_COMPAT
std::vector<ggml_tensor> ggml;
#endif
};
}
| 2,759
|
C++
|
.h
| 108
| 22.731481
| 68
| 0.713199
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,677
|
mulMat.kernel.hpp
|
Const-me_Whisper/Whisper/CPU/mulMat.kernel.hpp
|
#pragma once
#include <stdint.h>
#include <immintrin.h>
#include "simdUtils.h"
template<uint8_t panelHeightRegs, uint8_t tileWidthFloats>
struct ResultTile
{
static constexpr size_t totalRegs = (size_t)(tileWidthFloats)*panelHeightRegs;
std::array<__m256, totalRegs> arr;
template<size_t idx>
__forceinline void fmadd( __m256 a, __m256 b )
{
arr[ idx ] = _mm256_fmadd_ps( a, b, arr[ idx ] );
}
__forceinline void kernel( const std::array<__m256, panelHeightRegs>& panel, const float* rsi, size_t stride );
__forceinline void kernelPartial( const std::array<__m256, panelHeightRegs>& panel, const float* rsi, size_t stride, size_t rem )
{
throw E_UNEXPECTED;
}
__forceinline void store( float* rdi, size_t w, size_t h, size_t stride ) const;
};
#pragma region setZero functions
__forceinline void setZero( std::array<__m256, 1>& dest )
{
dest[ 0 ] = _mm256_setzero_ps();
}
__forceinline void setZero( std::array<__m256, 2>& dest )
{
dest[ 0 ] = _mm256_setzero_ps();
dest[ 1 ] = _mm256_setzero_ps();
}
__forceinline void setZero( std::array<__m256, 3>& dest )
{
dest[ 0 ] = _mm256_setzero_ps();
dest[ 1 ] = _mm256_setzero_ps();
dest[ 2 ] = _mm256_setzero_ps();
}
__forceinline void setZero( std::array<__m256, 4>& dest )
{
dest[ 0 ] = _mm256_setzero_ps();
dest[ 1 ] = _mm256_setzero_ps();
dest[ 2 ] = _mm256_setzero_ps();
dest[ 3 ] = _mm256_setzero_ps();
}
__forceinline void setZero( std::array<__m256, 6>& dest )
{
dest[ 0 ] = _mm256_setzero_ps();
dest[ 1 ] = _mm256_setzero_ps();
dest[ 2 ] = _mm256_setzero_ps();
dest[ 3 ] = _mm256_setzero_ps();
dest[ 4 ] = _mm256_setzero_ps();
dest[ 5 ] = _mm256_setzero_ps();
}
__forceinline void setZero( std::array<__m256, 8>& dest )
{
dest[ 0 ] = _mm256_setzero_ps();
dest[ 1 ] = _mm256_setzero_ps();
dest[ 2 ] = _mm256_setzero_ps();
dest[ 3 ] = _mm256_setzero_ps();
dest[ 4 ] = _mm256_setzero_ps();
dest[ 5 ] = _mm256_setzero_ps();
dest[ 6 ] = _mm256_setzero_ps();
dest[ 7 ] = _mm256_setzero_ps();
}
#pragma endregion
#pragma region Micro-kernels
__forceinline void ResultTile<1, 1>::kernel( const std::array<__m256, 1>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
}
__forceinline void ResultTile<1, 2>::kernel( const std::array<__m256, 1>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
b = _mm256_broadcast_ss( rsi + stride );
fmadd<1>( panel[ 0 ], b );
}
__forceinline void ResultTile<1, 2>::kernelPartial( const std::array<__m256, 1>& panel, const float* rsi, size_t stride, size_t rem )
{
assert( 1 == rem );
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
}
__forceinline void ResultTile<1, 3>::kernel( const std::array<__m256, 1>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
b = _mm256_broadcast_ss( rsi + stride );
fmadd<1>( panel[ 0 ], b );
b = _mm256_broadcast_ss( rsi + stride * 2 );
fmadd<2>( panel[ 0 ], b );
}
__forceinline void ResultTile<1, 3>::kernelPartial( const std::array<__m256, 1>& panel, const float* rsi, size_t stride, size_t rem )
{
assert( rem > 0 && rem < 3 );
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
if( rem > 1 )
{
b = _mm256_broadcast_ss( rsi + stride );
fmadd<1>( panel[ 0 ], b );
}
}
__forceinline void ResultTile<1, 4>::kernel( const std::array<__m256, 1>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
b = _mm256_broadcast_ss( rsi + stride );
fmadd<1>( panel[ 0 ], b );
b = _mm256_broadcast_ss( rsi + stride * 2 );
fmadd<2>( panel[ 0 ], b );
b = _mm256_broadcast_ss( rsi + stride * 3 );
fmadd<3>( panel[ 0 ], b );
}
__forceinline void ResultTile<1, 4>::kernelPartial( const std::array<__m256, 1>& panel, const float* rsi, size_t stride, size_t rem )
{
assert( rem > 0 && rem < 4 );
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
switch( rem )
{
case 3:
b = _mm256_broadcast_ss( rsi + stride * 2 );
fmadd<2>( panel[ 0 ], b );
case 2:
b = _mm256_broadcast_ss( rsi + stride );
fmadd<1>( panel[ 0 ], b );
}
}
__forceinline void ResultTile<4, 1>::kernel( const std::array<__m256, 4>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
fmadd<2>( panel[ 2 ], b );
fmadd<3>( panel[ 3 ], b );
}
__forceinline void ResultTile<2, 4>::kernel( const std::array<__m256, 2>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
b = _mm256_broadcast_ss( rsi + stride );
fmadd<2>( panel[ 0 ], b );
fmadd<3>( panel[ 1 ], b );
b = _mm256_broadcast_ss( rsi + stride * 2 );
fmadd<4>( panel[ 0 ], b );
fmadd<5>( panel[ 1 ], b );
b = _mm256_broadcast_ss( rsi + stride * 3 );
fmadd<6>( panel[ 0 ], b );
fmadd<7>( panel[ 1 ], b );
}
__forceinline void ResultTile<2, 4>::kernelPartial( const std::array<__m256, 2>& panel, const float* rsi, size_t stride, size_t rem )
{
assert( rem > 0 && rem < 4 );
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
switch( rem )
{
case 3:
b = _mm256_broadcast_ss( rsi + stride * 2 );
fmadd<4>( panel[ 0 ], b );
fmadd<5>( panel[ 1 ], b );
case 2:
b = _mm256_broadcast_ss( rsi + stride );
fmadd<2>( panel[ 0 ], b );
fmadd<3>( panel[ 1 ], b );
}
}
__forceinline void ResultTile<2, 3>::kernel( const std::array<__m256, 2>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
b = _mm256_broadcast_ss( rsi + stride );
fmadd<2>( panel[ 0 ], b );
fmadd<3>( panel[ 1 ], b );
b = _mm256_broadcast_ss( rsi + stride * 2 );
fmadd<4>( panel[ 0 ], b );
fmadd<5>( panel[ 1 ], b );
}
__forceinline void ResultTile<2, 3>::kernelPartial( const std::array<__m256, 2>& panel, const float* rsi, size_t stride, size_t rem )
{
assert( rem > 0 && rem < 3 );
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
if( rem > 1 )
{
b = _mm256_broadcast_ss( rsi + stride );
fmadd<2>( panel[ 0 ], b );
fmadd<3>( panel[ 1 ], b );
}
}
__forceinline void ResultTile<4, 2>::kernel( const std::array<__m256, 4>& panel, const float* rsi, size_t stride )
{
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
fmadd<2>( panel[ 2 ], b );
fmadd<3>( panel[ 3 ], b );
b = _mm256_broadcast_ss( rsi + stride );
fmadd<4>( panel[ 0 ], b );
fmadd<5>( panel[ 1 ], b );
fmadd<6>( panel[ 2 ], b );
fmadd<7>( panel[ 3 ], b );
}
__forceinline void ResultTile<4, 2>::kernelPartial( const std::array<__m256, 4>& panel, const float* rsi, size_t stride, size_t rem )
{
assert( 1 == rem );
__m256 b = _mm256_broadcast_ss( rsi );
fmadd<0>( panel[ 0 ], b );
fmadd<1>( panel[ 1 ], b );
fmadd<2>( panel[ 2 ], b );
fmadd<3>( panel[ 3 ], b );
}
#pragma endregion
#pragma region Loads
// This function should compile into a single `vcvtph2ps` instruction, with memory operand
__forceinline __m256 loadUpcasted( const uint16_t* rsi )
{
__m128i i = _mm_load_si128( ( const __m128i* )rsi );
return _mm256_cvtph_ps( i );
}
// We loading the panel from the temporary buffer.
// For this reason, we don't need to handle remainders, the code which made the buffer wrote zeros into the remainder elements
// We can even use aligned load instructions.
__forceinline void loadPanel( const uint16_t* rsi, std::array<__m256, 1>& dest )
{
dest[ 0 ] = loadUpcasted( rsi );
}
__forceinline void loadPanel( const uint16_t* rsi, std::array<__m256, 2>& dest )
{
dest[ 0 ] = loadUpcasted( rsi );
dest[ 1 ] = loadUpcasted( rsi + 8 );
}
__forceinline void loadPanel( const uint16_t* rsi, std::array<__m256, 3>& dest )
{
dest[ 0 ] = loadUpcasted( rsi );
dest[ 1 ] = loadUpcasted( rsi + 8 );
dest[ 2 ] = loadUpcasted( rsi + 8 * 2 );
}
__forceinline void loadPanel( const uint16_t* rsi, std::array<__m256, 4>& dest )
{
dest[ 0 ] = loadUpcasted( rsi );
dest[ 1 ] = loadUpcasted( rsi + 8 );
dest[ 2 ] = loadUpcasted( rsi + 8 * 2 );
dest[ 3 ] = loadUpcasted( rsi + 8 * 3 );
}
#pragma endregion
#pragma region Stores
__forceinline void ResultTile<1, 1>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h == 1 && w > 0 && w <= 8 );
if( w == 8 )
_mm256_storeu_ps( rdi, arr[ 0 ] );
else
{
const __m256i mask = loadTailMaskInt( w );
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
}
}
__forceinline void ResultTile<1, 2>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h > 0 && w > 0 && h <= 2 && w <= 8 );
if( w == 8 )
{
switch( h )
{
case 2:
_mm256_storeu_ps( rdi + stride, arr[ 1 ] );
case 1:
_mm256_storeu_ps( rdi, arr[ 0 ] );
}
}
else
{
const __m256i mask = loadTailMaskInt( w );
switch( h )
{
case 2:
_mm256_maskstore_ps( rdi + stride, mask, arr[ 1 ] );
case 1:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
}
}
}
__forceinline void ResultTile<1, 3>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h > 0 && w > 0 && h <= 3 && w <= 8 );
if( w == 8 )
{
switch( h )
{
case 3:
_mm256_storeu_ps( rdi + stride * 2, arr[ 2 ] );
case 2:
_mm256_storeu_ps( rdi + stride, arr[ 1 ] );
case 1:
_mm256_storeu_ps( rdi, arr[ 0 ] );
}
}
else
{
const __m256i mask = loadTailMaskInt( w );
switch( h )
{
case 3:
_mm256_maskstore_ps( rdi + stride * 2, mask, arr[ 2 ] );
case 2:
_mm256_maskstore_ps( rdi + stride, mask, arr[ 1 ] );
case 1:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
}
}
}
__forceinline void ResultTile<1, 4>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h > 0 && w > 0 && h <= 4 && w <= 8 );
if( w == 8 )
{
switch( h )
{
case 4:
_mm256_storeu_ps( rdi + stride * 3, arr[ 3 ] );
case 3:
_mm256_storeu_ps( rdi + stride * 2, arr[ 2 ] );
case 2:
_mm256_storeu_ps( rdi + stride, arr[ 1 ] );
case 1:
_mm256_storeu_ps( rdi, arr[ 0 ] );
}
}
else
{
const __m256i mask = loadTailMaskInt( w );
switch( h )
{
case 4:
_mm256_maskstore_ps( rdi + stride * 3, mask, arr[ 3 ] );
case 3:
_mm256_maskstore_ps( rdi + stride * 2, mask, arr[ 2 ] );
case 2:
_mm256_maskstore_ps( rdi + stride, mask, arr[ 1 ] );
case 1:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
}
}
}
__forceinline void ResultTile<4, 1>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h == 1 && w > 0 && w <= 32 );
if( w == 32 )
{
// 4 complete vectors, this branch is very likely to be taken
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
_mm256_storeu_ps( rdi + 8 * 3, arr[ 3 ] );
}
else
{
const size_t rem = w % 8;
const __m256i mask = loadTailMaskInt<false>( rem );
const size_t completeVectors = w / 8;
const size_t key = ( completeVectors << 1 ) | ( ( 0 == rem ) ? 0 : 1 );
switch( key )
{
case 1: // 0 complete vectors + remainder
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
break;
case 2: // 1 complete vector
_mm256_storeu_ps( rdi, arr[ 0 ] );
break;
case 3: // 1 complete vector + remainder
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
break;
case 4: // 2 complete vectors
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
break;
case 5: // 2 complete vectors + remainder
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_maskstore_ps( rdi + 8 * 2, mask, arr[ 2 ] );
break;
case 6: // 3 complete vectors
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
break;
case 7: // 3 complete vectors + remainder
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
_mm256_maskstore_ps( rdi + 8 * 3, mask, arr[ 3 ] );
break;
default:
throw E_UNEXPECTED;
}
}
}
__forceinline void ResultTile<4, 2>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h > 0 && w > 0 && h <= 2 && w <= 32 );
const bool twoRows = h == 2;
float* const rdi1 = rdi + stride;
if( w == 32 )
{
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
_mm256_storeu_ps( rdi + 8 * 3, arr[ 3 ] );
if( twoRows )
{
_mm256_storeu_ps( rdi1, arr[ 4 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 5 ] );
_mm256_storeu_ps( rdi1 + 8 * 2, arr[ 6 ] );
_mm256_storeu_ps( rdi1 + 8 * 3, arr[ 7 ] );
}
}
else
{
const size_t rem = w % 8;
const __m256i mask = loadTailMaskInt<false>( rem );
const size_t completeVectors = w / 8;
// Lowest bit: remainder
// Next bit: set when storing 2 rows
// Next 2 bits: count of complete vectors in X direction, [ 0..3 ]
const size_t key = ( completeVectors << 2 ) | ( ( 0 == rem ) ? 0 : 1 ) | ( twoRows ? 2 : 0 );
switch( key )
{
case 1: // 0 complete vectors + remainder, 1 row
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
break;
case 3: // 0 complete vectors + remainder, 2 rows
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
_mm256_maskstore_ps( rdi1, mask, arr[ 4 ] );
break;
case 4: // 1 complete vector, 1 row
_mm256_storeu_ps( rdi, arr[ 0 ] );
break;
case 5: // 1 complete vector + remainder, 1 row
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
break;
case 6: // 1 complete vector, 2 rows
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi1, arr[ 4 ] );
break;
case 7: // 1 complete vector + remainder, 2 rows
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 4 ] );
_mm256_maskstore_ps( rdi1 + 8, mask, arr[ 5 ] );
break;
case 8: // 2 complete vectors, 1 row
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
break;
case 9: // 2 complete vectors + remainder, 1 row
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_maskstore_ps( rdi + 8 * 2, mask, arr[ 2 ] );
break;
case 10: // 2 complete vectors, 2 rows
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 4 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 5 ] );
break;
case 11: // 2 complete vectors + remainder, 2 rows
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_maskstore_ps( rdi + 8 * 2, mask, arr[ 2 ] );
_mm256_storeu_ps( rdi1, arr[ 4 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 5 ] );
_mm256_maskstore_ps( rdi1 + 8 * 2, mask, arr[ 6 ] );
break;
case 12: // 3 complete vectors, 1 row
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
break;
case 13: // 3 complete vectors + remainder, 1 row
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
_mm256_maskstore_ps( rdi + 8 * 3, mask, arr[ 3 ] );
break;
case 14: // 3 complete vectors, 2 rows
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
_mm256_storeu_ps( rdi1, arr[ 4 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 5 ] );
_mm256_storeu_ps( rdi1 + 8 * 2, arr[ 6 ] );
break;
case 15: // 3 complete vectors + remainder, 2 rows
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
_mm256_storeu_ps( rdi + 8 * 2, arr[ 2 ] );
_mm256_maskstore_ps( rdi + 8 * 3, mask, arr[ 3 ] );
_mm256_storeu_ps( rdi1, arr[ 4 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 5 ] );
_mm256_storeu_ps( rdi1 + 8 * 2, arr[ 6 ] );
_mm256_maskstore_ps( rdi1 + 8 * 3, mask, arr[ 7 ] );
break;
default:
throw E_UNEXPECTED;
}
}
}
__forceinline void ResultTile<2, 4>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h > 0 && w > 0 && h <= 4 && w <= 16 );
h--;
float* const rdi1 = rdi + stride;
float* const rdi2 = rdi + stride * 2;
float* const rdi3 = rdi + stride * 3;
if( w == 16 )
{
switch( h )
{
case 3:
_mm256_storeu_ps( rdi3, arr[ 6 ] );
_mm256_storeu_ps( rdi3 + 8, arr[ 7 ] );
case 2:
_mm256_storeu_ps( rdi2, arr[ 4 ] );
_mm256_storeu_ps( rdi2 + 8, arr[ 5 ] );
case 1:
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 3 ] );
case 0:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
}
}
else
{
const size_t rem = w % 8;
const __m256i mask = loadTailMaskInt<false>( rem );
// 0 for partial first vector, 1 for exactly 1 complete vector, 2 for 1 complete vector with remainder
const size_t partialCase = ( w < 8 ) ? 0 : ( ( w == 8 ) ? 1 : 2 );
// Merge into a single integer for the switch statement
const size_t key = partialCase + h * 3;
switch( key )
{
// h = 1
case 0:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
break;
case 1:
_mm256_storeu_ps( rdi, arr[ 0 ] );
break;
case 2:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
break;
// h = 2
case 3:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
_mm256_maskstore_ps( rdi1, mask, arr[ 2 ] );
break;
case 4:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
break;
case 5:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_maskstore_ps( rdi1 + 8, mask, arr[ 3 ] );
break;
// h = 3
case 6:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
_mm256_maskstore_ps( rdi1, mask, arr[ 2 ] );
_mm256_maskstore_ps( rdi2, mask, arr[ 4 ] );
break;
case 7:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_storeu_ps( rdi2, arr[ 4 ] );
break;
case 8:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_maskstore_ps( rdi1 + 8, mask, arr[ 3 ] );
_mm256_storeu_ps( rdi2, arr[ 4 ] );
_mm256_maskstore_ps( rdi2 + 8, mask, arr[ 5 ] );
break;
// h = 4
case 9:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
_mm256_maskstore_ps( rdi1, mask, arr[ 2 ] );
_mm256_maskstore_ps( rdi2, mask, arr[ 4 ] );
_mm256_maskstore_ps( rdi3, mask, arr[ 6 ] );
break;
case 10:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_storeu_ps( rdi2, arr[ 4 ] );
_mm256_storeu_ps( rdi3, arr[ 6 ] );
break;
case 11:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_maskstore_ps( rdi1 + 8, mask, arr[ 3 ] );
_mm256_storeu_ps( rdi2, arr[ 4 ] );
_mm256_maskstore_ps( rdi2 + 8, mask, arr[ 5 ] );
_mm256_storeu_ps( rdi3, arr[ 6 ] );
_mm256_maskstore_ps( rdi3 + 8, mask, arr[ 7 ] );
break;
default:
throw E_UNEXPECTED;
}
}
}
__forceinline void ResultTile<2, 3>::store( float* rdi, size_t w, size_t h, size_t stride ) const
{
assert( h > 0 && w > 0 && h <= 3 && w <= 16 );
float* const rdi1 = rdi + stride;
float* const rdi2 = rdi + stride * 2;
h--;
if( w == 16 )
{
switch( h )
{
case 2:
_mm256_storeu_ps( rdi2, arr[ 4 ] );
_mm256_storeu_ps( rdi2 + 8, arr[ 5 ] );
case 1:
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_storeu_ps( rdi1 + 8, arr[ 3 ] );
case 0:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi + 8, arr[ 1 ] );
}
}
else
{
const size_t rem = w % 8;
const __m256i mask = loadTailMaskInt<false>( rem );
// 0 for partial first vector, 1 for exactly 1 complete vector, 2 for 1 complete vector with remainder
const size_t partialCase = ( w < 8 ) ? 0 : ( ( w == 8 ) ? 1 : 2 );
// Merge into a single integer for the switch statement
const size_t key = partialCase + h * 3;
switch( key )
{
// h = 1
case 0:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
break;
case 1:
_mm256_storeu_ps( rdi, arr[ 0 ] );
break;
case 2:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
break;
// h = 2
case 3:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
_mm256_maskstore_ps( rdi1, mask, arr[ 2 ] );
break;
case 4:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
break;
case 5:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_maskstore_ps( rdi1 + 8, mask, arr[ 3 ] );
break;
// h = 3
case 6:
_mm256_maskstore_ps( rdi, mask, arr[ 0 ] );
_mm256_maskstore_ps( rdi1, mask, arr[ 2 ] );
_mm256_maskstore_ps( rdi2, mask, arr[ 4 ] );
break;
case 7:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_storeu_ps( rdi2, arr[ 4 ] );
break;
case 8:
_mm256_storeu_ps( rdi, arr[ 0 ] );
_mm256_maskstore_ps( rdi + 8, mask, arr[ 1 ] );
_mm256_storeu_ps( rdi1, arr[ 2 ] );
_mm256_maskstore_ps( rdi1 + 8, mask, arr[ 3 ] );
_mm256_storeu_ps( rdi2, arr[ 4 ] );
_mm256_maskstore_ps( rdi2 + 8, mask, arr[ 5 ] );
break;
default:
throw E_UNEXPECTED;
}
}
}
#pragma endregion
| 21,534
|
C++
|
.h
| 706
| 27.771955
| 133
| 0.588563
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,678
|
mulMat.h
|
Const-me_Whisper/Whisper/CPU/mulMat.h
|
#pragma once
#include "ParallelForRunner.h"
#include "Tensor.h"
namespace CpuCompute
{
HRESULT mulMat( Tensor& result, const Tensor& a, const Tensor& b, ParallelForRunner& pfor );
}
#if TENSOR_GGML_COMPAT
#include "../source/ggml.h"
inline HRESULT mulMat( ggml_tensor* result, const ggml_tensor* a, const ggml_tensor* b, CpuCompute::ParallelForRunner& pfor )
{
CpuCompute::Tensor r{ result }, lhs{ a }, rhs{ b };
return CpuCompute::mulMat( r, lhs, rhs, pfor );
}
#endif
| 474
|
C++
|
.h
| 15
| 30.333333
| 125
| 0.744541
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,679
|
mulMatImpl.h
|
Const-me_Whisper/Whisper/CPU/mulMatImpl.h
|
#pragma once
// Matrix*matrix multiplication is the most expensive algorithm in the model, by far.
// For this reason, the code in this source file, and in the mulMat.kernel.hpp header, is optimized for performance. Readability suffers.
// The implementation is inspired by following two articles:
// https://gist.github.com/nadavrot/5b35d44e8ba3dd718e595e40184d03f0
// https://link.springer.com/article/10.1007/s11227-022-05003-3
#include "ParallelForRunner.h"
#include "Tensor.h"
namespace CpuCompute
{
// Abstract base class for all implementations, to reduce binary size
class MulMatBase : public iComputeRange
{
protected:
// Pointers to the payload of the output matrix
float* const resultPointer;
// Lengths of the dot products to compute, equal to width of both source matrices
uint32_t length;
// Last 3 strides of the output matrix, expressed as count of elements. The first one is always 1 because the output matrix is continuous.
std::array<uint32_t, 3> resultStrides;
// Size of the output matrix
std::array<uint32_t, 4> resultSize;
// Pointers to the payload of the source matrices
const void* const pa;
const void* const pb;
// Matrix strides, expressed as count of elements
std::array<uint32_t, 4> stridesA, stridesB;
// Total count of panels in the layer of the output matrix.
// The last panel might be incomplete, with smaller height.
// The thread-local buffer however is always complete, unused elements will be zeros.
uint32_t countPanels;
// Complete tiles in the length of the panel
uint32_t completeTilesPerPanel;
// Count of the last remainder columns in the panel, can be 0
uint8_t lastColumnsInPanel;
// Same as panelHeightRegs template argument - height of the panels, in AVX vectors
uint8_t panelHeightRegisters;
// Same as tileWidthFloats template argument - width of the tile, in floats
uint8_t tileWidth;
// Method pointer to reshape a panel from the source matrix into a thread-local buffer
using pfnTransposePanel = HRESULT( MulMatBase::* )( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
pfnTransposePanel pfnMakePanel;
// The object which implements multithreading for this job, and supplies memory for thread-local buffers
ParallelForRunner& runner;
// Count of FP16 values in the thread-local panel buffer
uint32_t floatsPerPanel() const
{
return length * panelHeightRegisters * 8;
}
// Transpose a horizontal panel of the first matrix, when the rows are continuous in that matrix
HRESULT transposePanel( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
HRESULT transposePanelAvx2( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
// Copy a horizontal panel of the first matrix without transpose, for column major layout of that matrix
HRESULT copyPanelColumnMajor8( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
HRESULT copyPanelColumnMajor16( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
HRESULT copyPanelColumnMajor32( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
// Transpose a panel of the first matrix for irregular layout of that matrix, when neither rows nor columns are at sequential addresses.
// This one ain't implemented yet.
HRESULT gatherPanel( uint16_t* rdi, size_t i, size_t m2, size_t m3 ) const;
const uint16_t* getPanelA( size_t i, size_t m2, size_t m3 ) const;
// Pointer to the first element of the second source matrix in the specified layer
const float* getLayerB( size_t m2, size_t m3 ) const;
// Pointer to the first element of the output tile of the result matrix
float* getPanelDest( size_t i, size_t m2, size_t m3 ) const
{
float* rdi = resultPointer;
rdi += m2 * resultStrides[ 1 ];
rdi += m3 * resultStrides[ 2 ];
rdi += i * panelHeightRegisters * 8;
return rdi;
}
static const bool haveAvx2;
public:
MulMatBase( Tensor& result, const Tensor& a, const Tensor& b, ParallelForRunner& pfor, uint8_t panelHeightRegs, uint8_t tileWidthFloats );
HRESULT run( ParallelForRunner& pfor );
};
// This class actually contains the kernels implementations
template<uint8_t panelHeightRegs, uint8_t tileWidthFloats>
class MulMatImpl : public MulMatBase
{
HRESULT __stdcall compute( size_t i, size_t end ) const noexcept override final;
public:
MulMatImpl( Tensor& result, const Tensor& a, const Tensor& b, ParallelForRunner& pfor ) :
MulMatBase( result, a, b, pfor, panelHeightRegs, tileWidthFloats )
{ }
};
}
| 4,480
|
C++
|
.h
| 87
| 48.597701
| 140
| 0.7552
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,680
|
LargeBuffer.h
|
Const-me_Whisper/Whisper/CPU/LargeBuffer.h
|
#pragma once
namespace CpuCompute
{
// A large memory buffer allocated with VirtualAlloc kernel API, bypassing the heap.
class LargeBuffer
{
void* pv = nullptr;
public:
LargeBuffer() = default;
LargeBuffer( const LargeBuffer& ) = delete;
LargeBuffer( LargeBuffer&& that ) noexcept
{
pv = that.pv;
that.pv = nullptr;
}
~LargeBuffer()
{
deallocate();
}
void operator=( LargeBuffer&& that ) noexcept
{
std::swap( pv, that.pv );
}
void operator=( const LargeBuffer& that ) = delete;
// Allocate buffer with specified count of bytes, and read+write memory protection
// The OS kernel guarantees zero-initialization of that memory.
HRESULT allocate( size_t cb );
// Change memory protection of the buffer to read only
HRESULT setReadOnly( size_t cb );
// Unless the pointer is nullptr, deallocate the buffer
void deallocate();
// Pointer to the start of the buffer, aligned by memory page = 4 kilobytes
uint8_t* pointer() const
{
assert( nullptr != pv );
return (uint8_t*)pv;
}
};
}
| 1,052
|
C++
|
.h
| 39
| 24.051282
| 85
| 0.710605
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,681
|
ParallelForRunner.h
|
Const-me_Whisper/Whisper/CPU/ParallelForRunner.h
|
#pragma once
#include "LargeBuffer.h"
namespace CpuCompute
{
// Callback interface for the parallel `for`
__interface iComputeRange
{
// The implementation calls this method on multiple thread pool threads in parallel, and aggregates status codes.
HRESULT __stdcall compute( size_t begin, size_t end ) const;
};
// Similar to ThreadPoolWork in parallelFor.h, optimized to be used as a direct replacement of OpenMP pool.
class alignas( 64 ) ParallelForRunner
{
public:
ParallelForRunner( int threads );
~ParallelForRunner();
HRESULT setThreadsCount( int threads );
HRESULT parallelFor( iComputeRange& compute, size_t length, size_t minBatch = 1 );
// Allocate a temporary buffer for the calling thread.
// The pointer is guaranteed to be aligned by page size = 4kb
void* threadLocalBuffer( size_t cb );
private:
int maxThreads;
PTP_WORK work = nullptr;
iComputeRange* computeRange = nullptr;
size_t countItems = 0;
size_t countThreads = 0;
// Aligning by cache lines.
// Avoiding cache line sharing between CPU cores improves performance, despite wasting a few bytes of memory.
struct alignas( 64 ) ThreadBuffer
{
LargeBuffer memory;
size_t cb = 0;
};
std::vector<ThreadBuffer> threadBuffers;
alignas( 64 ) volatile long threadIndex = 0;
volatile HRESULT status = S_OK;
void runBatch( size_t ith ) noexcept;
static void __stdcall workCallbackStatic( PTP_CALLBACK_INSTANCE Instance, void* pv, PTP_WORK Work ) noexcept;
};
}
| 1,496
|
C++
|
.h
| 41
| 33.682927
| 115
| 0.755017
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,682
|
mulMatUtils.hpp
|
Const-me_Whisper/Whisper/CPU/mulMatUtils.hpp
|
#pragma once
#include <immintrin.h>
#include <stdint.h>
#include <assert.h>
__forceinline __m128i f16Load( const uint16_t* rsi )
{
return _mm_loadu_si128( ( const __m128i* )rsi );
}
constexpr size_t maskAlign8 = ~(size_t)7;
__forceinline void transpose8( uint16_t* rdi, size_t w, const uint16_t* rsi, size_t sourceStride, size_t destStride )
{
assert( 0 == ( (size_t)rdi ) % 16 );
assert( 0 == destStride % 8 );
assert( w <= sourceStride );
const uint16_t* const rsiEndAligned = rsi + ( w & maskAlign8 );
const uint16_t* rsi5 = rsi + sourceStride * 5;
uint16_t* rdi5 = rdi + destStride * 5;
const size_t rem = w % 8;
for( ; rsi < rsiEndAligned; rsi += 8, rsi5 += 8, rdi += 8 * destStride, rdi5 += 8 * destStride )
{
// Load 8x8 block into 8 registers
__m128i r0 = f16Load( rsi ); // 00, 01, 02, 03, 04, 05, 06, 07
__m128i r1 = f16Load( rsi + sourceStride ); // 10, 11, 12, 13, 14, 15, 16, 17
__m128i r2 = f16Load( rsi + sourceStride * 2 ); // 20, 21, 22, 23, 24, 25, 26, 27
__m128i r3 = f16Load( rsi5 - sourceStride * 2 ); // 30, 31, 32, 33, 34, 35, 36, 37
__m128i r4 = f16Load( rsi5 - sourceStride ); // 40, 41, 42, 43, 44, 45, 46, 47
__m128i r5 = f16Load( rsi5 ); // 50, 51, 52, 53, 54, 55, 56, 57
__m128i r6 = f16Load( rsi5 + sourceStride ); // 60, 61, 62, 63, 64, 65, 66, 67
__m128i r7 = f16Load( rsi5 + sourceStride * 2 ); // 70, 71, 72, 73, 74, 75, 76, 77
// Transpose FP16 values in registers
__m128i t0 = _mm_unpacklo_epi16( r0, r1 ); // 00, 10, 01, 11, 02, 12, 03, 13
__m128i t1 = _mm_unpackhi_epi16( r0, r1 ); // 04, 14, 05, 15, 06, 16, 07, 17
__m128i t2 = _mm_unpacklo_epi16( r2, r3 ); // 20, 30, 21, 31, 22, 32, 23, 33
__m128i t3 = _mm_unpackhi_epi16( r2, r3 ); // 24, 34, 25, 35, 26, 36, 27, 37
__m128i t4 = _mm_unpacklo_epi16( r4, r5 ); // 40, 50, 41, 52, 42, 52, 43, 53
__m128i t5 = _mm_unpackhi_epi16( r4, r5 ); // 44, 54, 45, 55, 46, 56, 47, 57
__m128i t6 = _mm_unpacklo_epi16( r6, r7 ); // 60, 70, 61, 71, 62, 72, 63, 73
__m128i t7 = _mm_unpackhi_epi16( r6, r7 ); // 64, 74, 65, 75, 66, 76, 67, 77
r0 = _mm_unpacklo_epi32( t0, t2 ); // 00, 10, 20, 30, 01, 11, 21, 31
r1 = _mm_unpackhi_epi32( t0, t2 ); // 02, 12, 22, 32, 03, 13, 23, 33
r2 = _mm_unpacklo_epi32( t1, t3 ); // 04, 14, 24, 34, 05, 15, 25, 35
r3 = _mm_unpackhi_epi32( t1, t3 ); // 06, 16, 26, 36, 07, 17, 27, 37
r4 = _mm_unpacklo_epi32( t4, t6 ); // 40, 50, 60, 70, 41, 51, 61, 71
r5 = _mm_unpackhi_epi32( t4, t6 ); // 42, 52, 62, 72, 43, 53, 63, 73
r6 = _mm_unpacklo_epi32( t5, t7 ); // 44, 54, 64, 74, 45, 55, 65, 75
r7 = _mm_unpackhi_epi32( t5, t7 ); // 46, 56, 66, 76, 47, 57, 67, 77
t0 = _mm_unpacklo_epi64( r0, r4 ); // 00, 10, 20, 30, 40, 50, 60, 70
t1 = _mm_unpackhi_epi64( r0, r4 ); // 01, 11, 21, 31, 41, 52, 61, 71
t2 = _mm_unpacklo_epi64( r1, r5 ); // 02, 12, 22, 32, 42, 52, 62, 72
t3 = _mm_unpackhi_epi64( r1, r5 ); // 03, 13, 23, 33, 43, 53, 63, 73
t4 = _mm_unpacklo_epi64( r2, r6 );
t5 = _mm_unpackhi_epi64( r2, r6 );
t6 = _mm_unpacklo_epi64( r3, r7 );
t7 = _mm_unpackhi_epi64( r3, r7 );
// Store
store16( rdi, t0 );
store16( rdi + destStride, t1 );
store16( rdi + destStride * 2, t2 );
store16( rdi5 - destStride * 2, t3 );
store16( rdi5 - destStride, t4 );
store16( rdi5, t5 );
store16( rdi5 + destStride, t6 );
store16( rdi5 + destStride * 2, t7 );
}
#pragma loop( no_vector )
for( size_t i = 0; i < rem; rsi++, rsi5++, rdi += destStride )
{
const int16_t* p0 = (const int16_t*)rsi;
const int16_t* p5 = (const int16_t*)rsi5;
// Load a complete column into a vector
__m128i v = _mm_cvtsi32_si128( *rsi );
v = _mm_insert_epi16( v, *( p0 + sourceStride ), 1 );
v = _mm_insert_epi16( v, *( p0 + sourceStride * 2 ), 2 );
v = _mm_insert_epi16( v, *( p5 - sourceStride * 2 ), 3 );
v = _mm_insert_epi16( v, *( p5 - sourceStride ), 4 );
v = _mm_insert_epi16( v, *( p5 ), 5 );
v = _mm_insert_epi16( v, *( p5 + sourceStride ), 6 );
v = _mm_insert_epi16( v, *( p5 + sourceStride * 2 ), 7 );
// Store 8 FP16 values
store16( rdi, v );
}
}
inline void transpose8Partial( uint16_t* rdi, size_t w, size_t h, const uint16_t* rsi, size_t sourceStride, size_t destStride )
{
assert( 0 == ( (size_t)rdi ) % 16 );
assert( 0 == destStride % 8 );
assert( w <= sourceStride );
assert( h > 0 && h < 8 );
const uint16_t* const rsiEndAligned = rsi + ( w & maskAlign8 );
const uint16_t* rsi5 = rsi + sourceStride * 5;
uint16_t* rdi5 = rdi + destStride * 5;
const size_t rem = w % 8;
for( ; rsi < rsiEndAligned; rsi += 8, rsi5 += 8, rdi += 8 * destStride, rdi5 += 8 * destStride )
{
// Load the block into 8 registers, set unused rows to zero
__m128i r0 = f16Load( rsi );
__m128i r1 = _mm_setzero_si128();
__m128i r2 = _mm_setzero_si128();
__m128i r3 = _mm_setzero_si128();
__m128i r4 = _mm_setzero_si128();
__m128i r5 = _mm_setzero_si128();
__m128i r6 = _mm_setzero_si128();
// These branches, whether direct or indirect, are very predictable: same outcome for all iterations of the outer loop
switch( h )
{
case 7:
r6 = f16Load( rsi5 + sourceStride );
case 6:
r5 = f16Load( rsi5 );
case 5:
r4 = f16Load( rsi5 - sourceStride );
case 4:
r3 = f16Load( rsi5 - sourceStride * 2 );
case 3:
r2 = f16Load( rsi + sourceStride * 2 );
case 2:
r1 = f16Load( rsi + sourceStride );
}
__m128i r7 = _mm_setzero_si128();
// Transpose FP16 values in registers
__m128i t0 = _mm_unpacklo_epi16( r0, r1 ); // 00, 10, 01, 11, 02, 12, 03, 13
__m128i t1 = _mm_unpackhi_epi16( r0, r1 ); // 04, 14, 05, 15, 06, 16, 07, 17
__m128i t2 = _mm_unpacklo_epi16( r2, r3 ); // 20, 30, 21, 31, 22, 32, 23, 33
__m128i t3 = _mm_unpackhi_epi16( r2, r3 ); // 24, 34, 25, 35, 26, 36, 27, 37
__m128i t4 = _mm_unpacklo_epi16( r4, r5 ); // 40, 50, 41, 52, 42, 52, 43, 53
__m128i t5 = _mm_unpackhi_epi16( r4, r5 ); // 44, 54, 45, 55, 46, 56, 47, 57
__m128i t6 = _mm_unpacklo_epi16( r6, r7 ); // 60, 70, 61, 71, 62, 72, 63, 73
__m128i t7 = _mm_unpackhi_epi16( r6, r7 ); // 64, 74, 65, 75, 66, 76, 67, 77
r0 = _mm_unpacklo_epi32( t0, t2 ); // 00, 10, 20, 30, 01, 11, 21, 31
r1 = _mm_unpackhi_epi32( t0, t2 ); // 02, 12, 22, 32, 03, 13, 23, 33
r2 = _mm_unpacklo_epi32( t1, t3 ); // 04, 14, 24, 34, 05, 15, 25, 35
r3 = _mm_unpackhi_epi32( t1, t3 ); // 06, 16, 26, 36, 07, 17, 27, 37
r4 = _mm_unpacklo_epi32( t4, t6 ); // 40, 50, 60, 70, 41, 51, 61, 71
r5 = _mm_unpackhi_epi32( t4, t6 ); // 42, 52, 62, 72, 43, 53, 63, 73
r6 = _mm_unpacklo_epi32( t5, t7 ); // 44, 54, 64, 74, 45, 55, 65, 75
r7 = _mm_unpackhi_epi32( t5, t7 ); // 46, 56, 66, 76, 47, 57, 67, 77
t0 = _mm_unpacklo_epi64( r0, r4 ); // 00, 10, 20, 30, 40, 50, 60, 70
t1 = _mm_unpackhi_epi64( r0, r4 ); // 01, 11, 21, 31, 41, 52, 61, 71
t2 = _mm_unpacklo_epi64( r1, r5 ); // 02, 12, 22, 32, 42, 52, 62, 72
t3 = _mm_unpackhi_epi64( r1, r5 ); // 03, 13, 23, 33, 43, 53, 63, 73
t4 = _mm_unpacklo_epi64( r2, r6 );
t5 = _mm_unpackhi_epi64( r2, r6 );
t6 = _mm_unpacklo_epi64( r3, r7 );
t7 = _mm_unpackhi_epi64( r3, r7 );
// Store
store16( rdi, t0 );
store16( rdi + destStride, t1 );
store16( rdi + destStride * 2, t2 );
store16( rdi5 - destStride * 2, t3 );
store16( rdi5 - destStride, t4 );
store16( rdi5, t5 );
store16( rdi5 + destStride, t6 );
store16( rdi5 + destStride * 2, t7 );
}
#pragma loop( no_vector )
for( size_t i = 0; i < rem; rsi++, rsi5++, rdi += destStride )
{
const int16_t* p0 = (const int16_t*)rsi;
const int16_t* p5 = (const int16_t*)rsi5;
// Load a partial column into vector
__m128i v = _mm_cvtsi32_si128( *rsi );
switch( h )
{
case 7:
v = _mm_insert_epi16( v, *( p5 + sourceStride ), 6 );
case 6:
v = _mm_insert_epi16( v, *( p5 ), 5 );
case 5:
v = _mm_insert_epi16( v, *( p5 - sourceStride ), 4 );
case 4:
v = _mm_insert_epi16( v, *( p5 - sourceStride * 2 ), 3 );
case 3:
v = _mm_insert_epi16( v, *( p0 + sourceStride * 2 ), 2 );
case 2:
v = _mm_insert_epi16( v, *( p0 + sourceStride ), 1 );
}
// Store 8 FP16 values
store16( rdi, v );
}
}
// Same as above, but skip the transpose. The source stride is distance between columns of the matrix.
__forceinline void copyColumnMajor( uint16_t* rdi, size_t w, const uint16_t* rsi, size_t sourceStride, size_t destStride )
{
assert( 0 == ( (size_t)rdi ) % 16 );
assert( 0 == destStride % 8 );
constexpr size_t maskAlign4 = ~(size_t)3;
const uint16_t* const rsiEndAligned = rsi + sourceStride * ( w & maskAlign4 );
const uint16_t* const rsiEnd = rsi + sourceStride * w;
for( ; rsi < rsiEndAligned; rsi += sourceStride * 4, rdi += destStride * 4 )
{
__m128i c = f16Load( rsi );
store16( rdi, c );
c = f16Load( rsi + sourceStride );
store16( rdi + destStride, c );
c = f16Load( rsi + sourceStride * 2 );
store16( rdi + destStride * 2, c );
c = f16Load( rsi + sourceStride * 3 );
store16( rdi + destStride * 3, c );
}
for( ; rsi < rsiEnd; rsi += sourceStride, rdi += destStride )
{
__m128i c = f16Load( rsi );
store16( rdi, c );
}
}
__forceinline __m128i loadPartial( const uint16_t* x, size_t count )
{
assert( count < 8 );
__m128i ix;
switch( count )
{
case 1: // load 2 bytes
ix = _mm_cvtsi32_si128( *x );
break;
case 2: // load 4 bytes
ix = _mm_cvtsi32_si128( *(const int*)x );
break;
case 3: // load 6 bytes
ix = _mm_cvtsi32_si128( *(const int*)x );
ix = _mm_insert_epi16( ix, x[ 2 ], 2 );
break;
case 4: // load 8 bytes
ix = _mm_cvtsi64_si128( *(const int64_t*)x );
break;
case 5: // load 10 bytes
ix = _mm_cvtsi64_si128( *(const int64_t*)x );
ix = _mm_insert_epi16( ix, x[ 4 ], 4 );
break;
case 6: // load 12 bytes
ix = _mm_cvtsi64_si128( *(const int64_t*)x );
ix = _mm_insert_epi32( ix, *(const int*)( x + 4 ), 2 );
break;
case 7: // load 14 bytes
ix = _mm_cvtsi64_si128( *(const int64_t*)x );
ix = _mm_insert_epi32( ix, *(const int*)( x + 4 ), 2 );
ix = _mm_insert_epi16( ix, x[ 6 ], 6 );
break;
default:
return _mm_setzero_si128();
}
return ix;
}
inline void copyColumnMajorPartial( uint16_t* rdi, size_t w, size_t h, const uint16_t* rsi, size_t sourceStride, size_t destStride )
{
assert( 0 == ( (size_t)rdi ) % 32 );
assert( 0 == destStride % 8 );
assert( h > 0 && h < 8 );
const uint16_t* const rsiEnd = rsi + sourceStride * w;
for( ; rsi < rsiEnd; rsi += sourceStride, rdi += destStride )
{
// Can't use mask loads because loading 2-byte elements
// Still, that switch() in loadPartial makes a very predictable branch, same outcome for all iterations of this loop.
__m128i c = loadPartial( rsi, h );
store16( rdi, c );
}
}
// Store zeros into block of memory, with aligned AVX store instructions
__forceinline void zeroAlignedMemory( void* pv, size_t cb )
{
assert( 0 == cb % 16 );
assert( 0 == ( (size_t)pv % 32 ) );
uint8_t* rdi = (uint8_t*)pv;
constexpr size_t maskAlign32 = ~(size_t)31;
uint8_t* const rdiEndAligned = rdi + ( cb & maskAlign32 );
uint8_t* const rdiEnd = rdi + cb;
const __m256 zero = _mm256_setzero_ps();
for( ; rdi < rdiEndAligned; rdi += 32 )
_mm256_store_ps( (float*)rdi, zero );
if( rdi < rdiEnd )
_mm_store_ps( (float*)rdi, _mm_setzero_ps() );
}
| 11,231
|
C++
|
.h
| 271
| 38.767528
| 132
| 0.591803
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,683
|
BufferAllocator.h
|
Const-me_Whisper/Whisper/CPU/BufferAllocator.h
|
#pragma once
#include "LargeBuffer.h"
#include "Tensor.h"
namespace CpuCompute
{
#ifdef NDEBUG
inline void dbgMarkUninitializedMemory( void* pv, size_t cb ) { }
inline void dbgMarkFreedMemory( void* pv, size_t cb ) { }
#else
void dbgMarkUninitializedMemory( void* pv, size_t cb );
void dbgMarkFreedMemory( void* pv, size_t cb );
#endif
// An implementation of arena allocator which slices pieces of a large buffer allocated in advance
class BufferAllocator : public iArenaAllocator
{
LargeBuffer buffer;
size_t head = 0;
size_t size = 0;
void resetArena() noexcept override final
{
head = 0;
dbgMarkFreedMemory( buffer.pointer(), size );
}
void* allocate( size_t cb, size_t align ) noexcept override final;
public:
BufferAllocator() = default;
BufferAllocator( const BufferAllocator& ) = delete;
~BufferAllocator() = default;
// Allocate a large buffer with the specified count of bytes
HRESULT create( size_t cb );
};
// An implementation of arena allocator which allocates a large chunk of virtual memory, and maps new physical pages into that memory region as needed.
class VirtualAllocator : public iArenaAllocator
{
uint8_t* pointer = nullptr;
size_t head = 0;
size_t sizeAllocated = 0;
size_t sizeVirtual = 0;
void resetArena() noexcept override final
{
head = 0;
dbgMarkFreedMemory( pointer, sizeAllocated );
}
void* allocate( size_t cb, size_t align ) noexcept override final;
public:
VirtualAllocator() = default;
VirtualAllocator( const VirtualAllocator& ) = delete;
~VirtualAllocator();
// Reserve virtual memory space for the specified count of bytes in the arena, but don't allocate any pages
HRESULT create( size_t cb );
};
}
| 1,727
|
C++
|
.h
| 52
| 30.538462
| 152
| 0.748197
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,684
|
ModelLoader.h
|
Const-me_Whisper/Whisper/Whisper/ModelLoader.h
|
#pragma once
#include "ModelBuffers.h"
#include <map>
namespace DirectCompute
{
struct ModelLoader
{
ModelLoader( int encoderLayers, int decoderLayers );
void add( const ggml_tensor* ggml, Tensor& gpu );
void add( const ggml_tensor* w, const ggml_tensor* b, TensorPair& gpu )
{
add( w, gpu.w );
add( b, gpu.b );
}
bool tryLoad( const ggml_tensor* ggml );
ModelBuffers& model;
private:
Tensor* lookup( const ggml_tensor* ggml ) const;
std::map<const ggml_tensor*, Tensor*> map;
};
}
| 517
|
C++
|
.h
| 21
| 21.952381
| 73
| 0.705521
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,685
|
loaderUtils.h
|
Const-me_Whisper/Whisper/Whisper/loaderUtils.h
|
#pragma once
#include "../../ComLightLib/streams.h"
namespace Whisper
{
inline HRESULT readBytes( ComLight::iReadStream* stm, void* rdi, size_t cb )
{
if( cb > INT_MAX )
return DISP_E_OVERFLOW;
if( cb == 0 )
return S_FALSE;
int n;
CHECK( stm->read( rdi, (int)cb, n ) );
if( n != (int)cb )
return E_EOF;
return S_OK;
}
template<typename T>
inline HRESULT readStruct( ComLight::iReadStream* stm, T& dest )
{
return readBytes( stm, &dest, sizeof( T ) );
}
}
| 486
|
C++
|
.h
| 22
| 19.681818
| 77
| 0.656587
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,686
|
TranscribeResult.h
|
Const-me_Whisper/Whisper/Whisper/TranscribeResult.h
|
#pragma once
#include "../API/iTranscribeResult.cl.h"
#include "../ComLightLib/comLightServer.h"
namespace Whisper
{
class TranscribeResult : public ComLight::ObjectRoot<iTranscribeResult>
{
HRESULT COMLIGHTCALL getSize( sTranscribeLength& rdi ) const noexcept override final
{
rdi.countSegments = (uint32_t)segments.size();
rdi.countTokens = (uint32_t)tokens.size();
return S_OK;
}
const sSegment* COMLIGHTCALL getSegments() const noexcept override final
{
if( !segments.empty() )
return segments.data();
return nullptr;
}
const sToken* COMLIGHTCALL getTokens() const noexcept override final
{
if( !tokens.empty() )
return tokens.data();
return nullptr;
}
public:
std::vector<sSegment> segments;
std::vector<sToken> tokens;
std::vector<std::string> segmentsText;
};
class TranscribeResultStatic : public ComLight::Object<TranscribeResult>
{
uint32_t COMLIGHTCALL Release() override final
{
// When the ref.counter reaches zero, Object.Release() method calls `delete this`.
// We don't want that for the aggregated object.
// Instead we only decrement the ref.counter, but do not delete the object even when the counter reaches zero.
return RefCounter::implRelease();
}
};
}
| 1,255
|
C++
|
.h
| 41
| 27.658537
| 113
| 0.744224
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,687
|
Spectrogram.h
|
Const-me_Whisper/Whisper/Whisper/Spectrogram.h
|
#pragma once
#include "WhisperModel.h"
#include "iSpectrogram.h"
#include "audioConstants.h"
namespace Whisper
{
struct iAudioBuffer;
// This implementation of iSpectrogram interface converts complete audio into MEL spectrogram
// Used for unbuffered audio, and capture: iContext.runFull and runCapture methods.
class Spectrogram: public iSpectrogram
{
uint32_t length = 0;
static constexpr uint32_t mel = N_MEL;
std::vector<float> data;
std::vector<StereoSample> stereo;
HRESULT makeBuffer( size_t off, size_t len, const float** buffer, size_t& stride ) noexcept override final
{
if( off + len > length )
return E_BOUNDS;
*buffer = &data[ off ];
stride = length;
return S_OK;
}
class MelContext;
HRESULT copyStereoPcm( size_t offset, size_t length, std::vector<StereoSample>& buffer ) const override final;
public:
size_t getLength() const noexcept override final
{
return length;
}
HRESULT pcmToMel( const iAudioBuffer* buffer, const Filters& filters, int threads = 1 );
size_t memoryUsage() const
{
return data.size() * 4;
}
};
// average the fabs of the signal
void computeSignalEnergy( std::vector<float>& result, const iAudioBuffer* buffer, int n_samples_per_half_window );
}
| 1,252
|
C++
|
.h
| 39
| 29.307692
| 115
| 0.742952
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,688
|
ModelBuffers.h
|
Const-me_Whisper/Whisper/Whisper/ModelBuffers.h
|
#pragma once
#include "../ML/Tensor.h"
#include <vector>
namespace DirectCompute
{
// A pair of tensors containing weights and biases; apparently, both tensors are of the same shape.
struct TensorPair
{
Tensor w, b;
__m128i getMemoryUse() const;
};
// A set of tensors for one encoder's layer
struct LayerEncoder
{
// encoder.blocks.*.attn_ln
TensorPair attnLn0;
// encoder.blocks.*.attn.out
TensorPair attnLn1;
// encoder.blocks.*.attn.query
TensorPair attnQuery;
// encoder.blocks.*.attn.key
Tensor attnKey;
// encoder.blocks.*.attn.value
TensorPair attnValue;
// encoder.blocks.*.mlp_ln
TensorPair mlpLn;
// encoder.blocks.*.mlp.0
TensorPair mlp0;
// encoder.blocks.*.mlp.2
TensorPair mlp1;
__m128i getMemoryUse() const;
};
// A set of tensors for the encoder
struct EncoderBuffers
{
// encoder.positional_embedding
Tensor positionalEmbedding;
// encoder.conv1
TensorPair conv1;
// encoder.conv2
TensorPair conv2;
// encoder.ln_post
TensorPair lnPost;
// A vector of layers
std::vector<LayerEncoder> layers;
__m128i getMemoryUse() const;
};
// A set of tensors for one decoder's layer
struct LayerDecoder
{
// decoder.blocks.*.attn_ln
TensorPair attnLn0;
// decoder.blocks.*.attn.out
TensorPair attnLn1;
// decoder.blocks.*.attn.query
TensorPair attnQuery;
// decoder.blocks.*.attn.key
Tensor attnKey;
// decoder.blocks.*.attn.value
TensorPair attnValue;
// decoder.blocks.*.cross_attn_ln
TensorPair crossAttnLn0;
// decoder.blocks.*.cross_attn.out
TensorPair crossAttnLn1;
// decoder.blocks.*.cross_attn.query
TensorPair crossAttnQuery;
// decoder.blocks.*.cross_attn.key
Tensor crossAttnKey;
// decoder.blocks.*.cross_attn.value
TensorPair crossAttnValue;
// decoder.blocks.*.mlp_ln
TensorPair mlpLn;
// decoder.blocks.*.mlp.0
TensorPair mlp0;
// decoder.blocks.*.mlp.2
TensorPair mlp1;
__m128i getMemoryUse() const;
};
// A set of tensors for the decoder
struct DecoderBuffers
{
// decoder.positional_embedding
Tensor positionalEmbedding;
// decoder.token_embedding
Tensor tokenEmbedding;
// decoder.ln
TensorPair ln;
// A vector of layers
std::vector<LayerDecoder> layers;
__m128i getMemoryUse() const;
};
// A complete set of tensors for a model
struct ModelBuffers
{
EncoderBuffers enc;
DecoderBuffers dec;
__m128i getMemoryUse() const;
HRESULT createClone( const ModelBuffers& rsi );
};
#if BUILD_BOTH_VERSIONS
extern const ModelBuffers& gpuModel;
#endif
}
| 2,544
|
C++
|
.h
| 103
| 21.980583
| 100
| 0.739811
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,689
|
DecoderInputBuffers.h
|
Const-me_Whisper/Whisper/Whisper/DecoderInputBuffers.h
|
#pragma once
#include "../ML/Tensor.h"
namespace DirectCompute
{
// A dynamic buffer
class DecoderInputBuffers
{
CComPtr<ID3D11Buffer> embd;
uint32_t m_size = 0;
uint32_t m_capacity = 0;
public:
void resize( uint32_t size );
// Create 1D tensor with R32_UINT elements, upload the source data
Tensor embedding( const int* rsi ) const;
void clear();
__m128i getMemoryUse() const
{
size_t i = m_capacity;
i *= sizeof( uint32_t );
return _mm_set_epi64x( (int64_t)i, 0 );
}
HRESULT zeroMemory() const;
};
}
| 544
|
C++
|
.h
| 24
| 19.916667
| 68
| 0.692607
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,690
|
WhisperModel.h
|
Const-me_Whisper/Whisper/Whisper/WhisperModel.h
|
#pragma once
#include <memory>
#include "Vocabulary.h"
#include "ModelBuffers.h"
#include "../../ComLightLib/streams.h"
#include "../CPU/DecoderTensors.h"
#include "../API/sLoadModelCallbacks.h"
#include "sModelParams.h"
namespace Whisper
{
struct Filters
{
uint32_t n_mel;
uint32_t n_fft;
std::vector<float> data;
};
struct ModelShared
{
Vocabulary vocab;
Filters filters;
#if BUILD_HYBRID_VERSION
CpuCompute::DecoderTensors hybridTensors;
#endif
};
// The complete model, as loaded from a GGML binary file.
// The entire model is immutable, and can be safely used from multiple threads in parallel.
// The tensors are uploaded to VRAM and don’t stay in system memory, everything else is in the system RAM.
struct WhisperModel
{
sModelParams parameters;
std::shared_ptr<ModelShared> shared;
DirectCompute::ModelBuffers tensors;
HRESULT load( ComLight::iReadStream* stm, bool hybrid, const sLoadModelCallbacks* callbacks );
HRESULT createClone( const WhisperModel& rsi );
// A vector of 2 uint64_t values, both numbers are 100 nanosecond ticks:
// 0. The time it took to load the model, measured on CPU
// 1. The time it took to upload all these tensors to VRAM, measured on GPU
__m128i getLoadTimes() const
{
static_assert( offsetof( WhisperModel, loadTimeCpu ) + 8 == offsetof( WhisperModel, loadTimeGpu ) );
return _mm_loadu_si128( ( const __m128i* )( &loadTimeCpu ) );
}
__m128i getMemoryUse() const;
private:
uint64_t loadTimeCpu = 0;
uint64_t loadTimeGpu = 0;
class CallbacksImpl;
HRESULT loadGpu( ComLight::iReadStream* stm, CallbacksImpl& callbacks );
HRESULT loadHybrid( ComLight::iReadStream* stm, CallbacksImpl& callbacks );
};
}
| 1,719
|
C++
|
.h
| 51
| 31.176471
| 107
| 0.751057
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,691
|
ContextImpl.h
|
Const-me_Whisper/Whisper/Whisper/ContextImpl.h
|
#pragma once
#include "../API/iContext.cl.h"
#include "../ComLightLib/comLightServer.h"
#include "WhisperContext.h"
#include "Spectrogram.h"
#include "TranscribeResult.h"
#include "sTokenData.h"
#include "../ML/Device.h"
namespace Whisper
{
class ContextImpl : public ComLight::ObjectRoot<iContext>
{
const DirectCompute::Device& device;
const WhisperModel& model;
ComLight::CComPtr<iModel> modelPtr;
DirectCompute::WhisperContext context;
Spectrogram spectrogram;
int64_t mediaTimeOffset = 0;
iSpectrogram* currentSpectrogram = nullptr;
class CurrentSpectrogramRaii;
ProfileCollection profiler;
HRESULT COMLIGHTCALL getModel( iModel** pp ) override final;
HRESULT COMLIGHTCALL timingsPrint() override final;
HRESULT COMLIGHTCALL timingsReset() override final;
HRESULT COMLIGHTCALL fullDefaultParams( eSamplingStrategy strategy, sFullParams* rdi ) override final;
HRESULT COMLIGHTCALL runFullImpl( const sFullParams& params, const sProgressSink& progress, iSpectrogram& mel );
HRESULT COMLIGHTCALL runFull( const sFullParams& params, const iAudioBuffer* buffer ) override final;
HRESULT COMLIGHTCALL runStreamed( const sFullParams& params, const sProgressSink& progress, const iAudioReader* reader ) override final;
HRESULT COMLIGHTCALL runCapture( const sFullParams& params, const sCaptureCallbacks& callbacks, const iAudioCapture* reader ) override final;
struct Segment
{
int64_t t0;
int64_t t1;
mutable std::string text;
std::vector<sTokenData> tokens;
size_t memoryUsage() const;
};
std::vector<Segment> result_all;
std::vector<whisper_token> prompt_past;
// [EXPERIMENTAL] token-level timestamps data
int64_t t_beg = 0;
int64_t t_last = 0;
whisper_token tid_last = 0;
std::vector<float> energy; // PCM signal energy
// [EXPERIMENTAL] speed-up techniques
int32_t exp_n_audio_ctx = 0; // 0 - use default
HRESULT encode( iSpectrogram& mel, int seek );
HRESULT decode( const int* tokens, size_t length, int n_past, int threads );
sTokenData sampleBest( const float* probs, bool force_timestamp, bool is_initial );
sTokenData sampleBest();
sTokenData sampleTimestamp( bool initial );
int wrapSegment( int max_len );
void expComputeTokenLevelTimestamps( int i_segment, float thold_pt, float thold_ptsum );
std::vector<float> probs;
std::vector<std::pair<double, Vocabulary::id>> probs_id;
mutable TranscribeResultStatic results;
HRESULT COMLIGHTCALL makeResults( eResultFlags flags, TranscribeResult& res, bool moveStrings ) const noexcept;
HRESULT COMLIGHTCALL getResults( eResultFlags flags, iTranscribeResult** pp ) const noexcept override final;
HRESULT COMLIGHTCALL detectSpeaker( const sTimeInterval& time, eSpeakerChannel& result ) const noexcept override final;
int defaultThreadsCount() const;
__m128i getMemoryUse() const;
mutable std::vector<StereoSample> diarizeBuffer;
public:
ContextImpl( const DirectCompute::Device& dev, const WhisperModel& modelData, iModel* modelPointer );
};
}
| 3,022
|
C++
|
.h
| 66
| 42.893939
| 143
| 0.782121
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,692
|
audioConstants.h
|
Const-me_Whisper/Whisper/Whisper/audioConstants.h
|
#pragma once
#include <stdint.h>
namespace Whisper
{
// WHISPER_SAMPLE_RATE, 16 kHz
constexpr uint32_t SAMPLE_RATE = 16000;
// WHISPER_N_FFT, 25 milliseconds
constexpr uint32_t FFT_SIZE = 400;
// WHISPER_HOP_LENGTH, 10 milliseconds
constexpr uint32_t FFT_STEP = 160;
// WHISPER_N_MEL
constexpr uint32_t N_MEL = 80;
}
| 325
|
C++
|
.h
| 13
| 23.384615
| 40
| 0.746795
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,693
|
MelInputTensor.h
|
Const-me_Whisper/Whisper/Whisper/MelInputTensor.h
|
#pragma once
#include "../ML/TensorEx.h"
#include "sEncodeParams.h"
#include "iSpectrogram.h"
namespace DirectCompute
{
// Input tensor in VRAM, in a dynamic FP32 buffer
class MelInputTensor : public TensorEx
{
uint32_t capacity;
public:
HRESULT create( Whisper::iSpectrogram& spectrogram, const sEncodeParams& encParams );
__m128i getMemoryUse() const
{
return setHigh_size( (size_t)capacity * 4 );
}
};
}
| 428
|
C++
|
.h
| 18
| 21.611111
| 87
| 0.749386
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,694
|
sTokenData.h
|
Const-me_Whisper/Whisper/Whisper/sTokenData.h
|
#pragma once
#include <stdint.h>
namespace Whisper
{
using whisper_token = int;
struct sTokenData
{
whisper_token id; // token id
whisper_token tid; // forced timestamp token id
float p; // probability of the token
float pt; // probability of the timestamp token
float ptsum; // sum of probabilities of all timestamp tokens
float vlen; // voice length of the token
// token-level timestamp data
// do not use if you haven't computed token-level timestamps
int64_t t0; // start time of the token
int64_t t1; // end time of the token
};
}
| 613
|
C++
|
.h
| 19
| 29.842105
| 68
| 0.673435
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,695
|
DecoderResultBuffer.h
|
Const-me_Whisper/Whisper/Whisper/DecoderResultBuffer.h
|
#pragma once
#include "../ML/Tensor.h"
namespace DirectCompute
{
class DecoderResultBuffer
{
CComPtr<ID3D11Buffer> buffer;
uint32_t m_size = 0;
uint32_t m_capacity = 0;
public:
void copyFromVram( const Tensor& rsi );
void copyToVector( std::vector<float>& vec ) const;
uint32_t size() const
{
return m_size;
}
void clear();
__m128i getMemoryUse() const
{
return bufferMemoryUsage( buffer );
}
};
}
| 437
|
C++
|
.h
| 23
| 16.304348
| 53
| 0.704156
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,696
|
sEncodeParams.h
|
Const-me_Whisper/Whisper/Whisper/sEncodeParams.h
|
#pragma once
#include <stdint.h>
namespace DirectCompute
{
struct sEncodeParams
{
uint32_t n_ctx, n_mels, mel_offset;
uint32_t layersCount, n_state, n_head;
uint32_t n_audio_ctx, n_text_state, n_text_layer, n_text_ctx;
};
struct sDecodeParams
{
uint32_t n_state, n_head;
uint32_t n_ctx, n_past, M;
uint32_t n_text_layer;
uint32_t n_vocab;
};
}
| 365
|
C++
|
.h
| 18
| 18.111111
| 63
| 0.713873
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,697
|
sModelParams.h
|
Const-me_Whisper/Whisper/Whisper/sModelParams.h
|
#pragma once
namespace Whisper
{
// default hparams (Whisper tiny)
struct sModelParams
{
int n_vocab = 51864;
int n_audio_ctx = 1500;
int n_audio_state = 384;
int n_audio_head = 6;
int n_audio_layer = 4;
int n_text_ctx = 448;
int n_text_state = 384;
int n_text_head = 6;
int n_text_layer = 4;
int n_mels = 80;
int f16 = 1;
};
}
| 353
|
C++
|
.h
| 19
| 16.263158
| 34
| 0.653731
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,698
|
melSpectrogram.h
|
Const-me_Whisper/Whisper/Whisper/melSpectrogram.h
|
#pragma once
#include "audioConstants.h"
#include "WhisperModel.h"
#include <memory>
namespace Whisper
{
class HanningWindow
{
std::array<float, FFT_SIZE> hann;
public:
HanningWindow();
float operator[]( size_t i ) const
{
return hann[ i ];
}
};
extern const HanningWindow s_hanning;
class SpectrogramContext
{
const Filters& filters;
static float* fftRecursion( float* temp, const float* const rsi, const size_t len );
std::unique_ptr<float[]> tempBuffer;
public:
SpectrogramContext( const Filters& flt );
// First step of the MEL algorithm, and recursively compute the FFT
void fft( std::array<float, N_MEL>& rdi, const float* pcm, size_t length );
};
}
| 695
|
C++
|
.h
| 28
| 22.428571
| 86
| 0.731118
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,699
|
WhisperContext.h
|
Const-me_Whisper/Whisper/Whisper/WhisperContext.h
|
#pragma once
#include "../ML/MlContext.h"
#include "MelInputTensor.h"
#include "KeyValueBuffers.h"
#include "sEncodeParams.h"
#include "DecoderInputBuffers.h"
#include "DecoderResultBuffer.h"
#include "../ML/TensorsArena.h"
#include "iSpectrogram.h"
#include "../Hybrid/HybridContext.h"
#include <memory>
#include "WhisperModel.h"
#include <tuple>
#include <optional>
namespace DirectCompute
{
struct TensorPair;
struct ModelBuffers;
class WhisperContext : public MlContext
{
struct Arenas
{
TensorsArena outer;
TensorsArena layer;
Arenas();
__m128i getMemoryUse() const;
};
iTensorArena* currentArena = nullptr;
Arenas arenas;
// Specialized tensor arena for decoder layer outputs, with just a single tensor
class DecoderLayerPool : public iTensorArena
{
PooledTensor result;
public:
Tensor tensor( eDataType type, const std::array<uint32_t, 4>& ne ) override final;
void reset() override final { }
__m128i getMemoryUse() const;
void clear()
{
result.clear();
}
HRESULT zeroMemory()
{
return result.zeroMemory();
}
};
DecoderLayerPool decPool;
class ArenaRaii;
MelInputTensor melInput;
KeyValueBuffers kv, kvCross;
DecoderInputBuffers decoderInput;
DecoderResultBuffer decoderOutput;
const ModelBuffers& gpuModel;
#if BUILD_HYBRID_VERSION
std::unique_ptr<HybridContext> hybridContext;
#endif
struct sWhisperMel
{
uint32_t n_len;
uint32_t n_mel;
const std::vector<float>& data;
};
void createKeyValueBuffers( const sEncodeParams& encParams );
// Encoder methods
Tensor convolutionAndGelu( const Tensor& mel, uint32_t n_ctx );
Tensor encodeLayer( const Tensor& source, size_t index, uint32_t n_state, uint32_t n_head, uint32_t n_ctx );
struct sLayerDecParams;
// Decoder methods
Tensor decodeLayer( const Tensor& source, size_t index, const sLayerDecParams& ldp );
// cur = add( mul( repeat( that.w, cur ), cur ), repeat( that.b, cur ) );
void fmaRepeat( Tensor& cur, const TensorPair& that );
Tensor createTensor( eDataType type, const std::array<uint32_t, 4>& ne ) override final;
public:
#if BUILD_BOTH_VERSIONS
WhisperContext();
~WhisperContext();
#else
~WhisperContext() = default;
#endif
WhisperContext( const Whisper::WhisperModel& wm, Whisper::ProfileCollection& pc );
WhisperContext( const WhisperContext& ) = delete;
Tensor encode( Whisper::iSpectrogram& spectrogram, const sEncodeParams& encParams );
void decode( const int* tokens, const int n_tokens, const sDecodeParams& decParams, std::vector<float>& probs, int threads );
static WhisperContext& current();
// Create a RAII object which measures both CPU and GPU time for the complete runFull() method
decltype( auto ) completeProfiler()
{
return std::make_tuple(
profiler.cpuBlock( Whisper::eCpuBlock::Run ),
profiler.block( eProfilerBlock::Run ) );
}
// Create a RAII object which measures CPU and optionally GPU time for the loop which calls decode() method
decltype( auto ) decodeProfiler()
{
#if BUILD_HYBRID_VERSION
if( hybridContext )
return std::make_tuple(
profiler.cpuBlock( Whisper::eCpuBlock::Decode ),
std::optional<GpuProfiler::BlockRaii>{} );
else
return std::make_tuple(
profiler.cpuBlock( Whisper::eCpuBlock::Decode ),
std::optional<GpuProfiler::BlockRaii>{ std::in_place, profiler.block( eProfilerBlock::Decode ) } );
#else
return std::make_tuple(
profiler.cpuBlock( Whisper::eCpuBlock::Decode ),
profiler.block( eProfilerBlock::Decode ) );
#endif
}
__m128i getMemoryUse() const;
HRESULT clearState();
};
}
| 3,627
|
C++
|
.h
| 113
| 28.99115
| 127
| 0.739914
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,700
|
ModelImpl.h
|
Const-me_Whisper/Whisper/Whisper/ModelImpl.h
|
#pragma once
#include "../API/iContext.cl.h"
#include "../ComLightLib/comLightServer.h"
#include "WhisperModel.h"
#include "../ComLightLib/streams.h"
#include "../ML/Device.h"
namespace Whisper
{
using ComLight::iReadStream;
class ModelImpl : public ComLight::ObjectRoot<iModel>
{
DirectCompute::Device device;
WhisperModel model;
const uint32_t gpuFlags;
const std::wstring adapter;
HRESULT COMLIGHTCALL createContext( iContext** pp ) override final;
HRESULT COMLIGHTCALL tokenize( const char* text, pfnDecodedTokens pfn, void* pv ) override final;
HRESULT COMLIGHTCALL getSpecialTokens( SpecialTokens& rdi ) override final
{
model.shared->vocab.getSpecialTokens( rdi );
return S_OK;
}
HRESULT COMLIGHTCALL isMultilingual() override final
{
return model.shared->vocab.is_multilingual() ? S_OK : S_FALSE;
}
const char* COMLIGHTCALL stringFromToken( whisper_token token ) override final
{
return model.shared->vocab.string( token );
}
static inline std::wstring makeString( const wchar_t* p )
{
if( p == nullptr )
return std::wstring{};
else
return std::wstring{ p };
}
HRESULT createClone( const ModelImpl& source );
HRESULT COMLIGHTCALL clone( iModel** rdi ) override final;
public:
ModelImpl( const sModelSetup& setup ) :
gpuFlags( setup.flags ),
adapter( makeString( setup.adapter ) )
{ }
ModelImpl( const ModelImpl& source ) :
gpuFlags( source.gpuFlags ),
adapter( source.adapter )
{ }
void FinalRelease();
HRESULT load( iReadStream* stm, bool hybrid, const sLoadModelCallbacks* callbacks );
};
}
| 1,608
|
C++
|
.h
| 52
| 27.865385
| 99
| 0.737047
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,701
|
KeyValueBuffers.h
|
Const-me_Whisper/Whisper/Whisper/KeyValueBuffers.h
|
#pragma once
#include "../ML/Tensor.h"
namespace DirectCompute
{
// FP16 buffer for self-attention and cross-attention layers
class AttentionBuffer
{
CComPtr<ID3D11Buffer> buffer;
uint32_t m_size = 0;
public:
// Create buffer for the specified count of elements
void resize( uint32_t size );
// Create an 1D tensor which references a slice of that buffer
Tensor view( uint32_t length, uint32_t offset ) const;
void clear()
{
buffer = nullptr;
m_size = 0;
}
ID3D11Buffer* getBuffer() const { return buffer; }
uint32_t getSize() const { return m_size; }
HRESULT zeroMemory() const;
};
struct KeyValueBuffers
{
AttentionBuffer keys, values;
void resize( uint32_t size );
void clear()
{
keys.clear();
values.clear();
}
__m128i getMemoryUse() const
{
size_t i = keys.getSize();
i += values.getSize();
i *= sizeof( uint16_t );
return setHigh_size( (int64_t)i ); // They both are in VRAM
}
HRESULT zeroMemory() const;
};
}
| 1,001
|
C++
|
.h
| 42
| 20.809524
| 64
| 0.694093
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,702
|
MelStreamer.h
|
Const-me_Whisper/Whisper/Whisper/MelStreamer.h
|
#pragma once
#include <deque>
#include "../MF/PcmReader.h"
#include "melSpectrogram.h"
#include "iSpectrogram.h"
#include <atlbase.h>
#include "../Utils/parallelFor.h"
#include "../Utils/ProfileCollection.h"
#include "../API/iMediaFoundation.cl.h"
namespace Whisper
{
// Base class for both single- and multi-threaded MEL streamers
// Used by iContext.runStreamed method
class MelStreamer : public iSpectrogram
{
protected:
PcmReader reader;
std::deque<PcmMonoChunk> queuePcmMono;
using MelChunk = std::array<float, N_MEL>;
std::deque<MelChunk> queueMel;
size_t streamStartOffset = 0;
std::vector<float> tempPcm;
std::vector<float> outputMel;
SpectrogramContext melContext;
bool readerEof = false;
ProfileCollection& profiler;
std::deque<PcmStereoChunk> queuePcmStereo;
// If the streamStartOffset value is less than the argument,
// remove ( off - streamStartOffset ) chunks from the start of all 3 queues, and advance streamStartOffset to the `off` argument
void dropOldChunks( size_t off );
// Ensure PCM queues have enough chunks to generate specified count of MEL chunks
// At the end of the stream, the method delivers less chunks then requested and returns S_FALSE
HRESULT ensurePcmChunks( size_t len );
// Copy mono PCM chunks from the queue (starting at the specified element index) into the continuous tempPcm vector
// Returns count of chunks copied there.
size_t serializePcm( size_t startOffset );
size_t lastBufferEnd = ~(size_t)0;
float lastBufferMax = 0.0f;
void makeTransposedBuffer( size_t off, size_t len );
size_t getLength() const noexcept override final { return reader.getLength(); }
HRESULT copyStereoPcm( size_t offset, size_t length, std::vector<StereoSample>& buffer ) const override final;
public:
MelStreamer( const Filters& filters, ProfileCollection& profiler, const iAudioReader* reader );
};
// Single-threaded MEL streamer: runs these FFTs on-demand, from within makeBuffer() method
// Used by iContext.runStreamed method when cpuThreads parameter is less than 2
class MelStreamerSimple : public MelStreamer
{
HRESULT makeBuffer( size_t offset, size_t length, const float** buffer, size_t& stride ) noexcept override final;
public:
MelStreamerSimple( const Filters& filters, ProfileCollection& profiler, const iAudioReader* reader ) :
MelStreamer( filters, profiler, reader ) { }
};
// Multi threaded MEL streamers: runs FFT on a background thread ahead of time
// The background thread tries to keep the queueMel full, this way the makeBuffer() method has very little to do
// makeBuffer() only transposes the data, and does clamping + normalization, both steps are pretty fast
// Used by iContext.runStreamed method when cpuThreads parameter is 2 or more
class MelStreamerThread : public MelStreamer,
ThreadPoolWork
{
HRESULT makeBuffer( size_t offset, size_t length, const float** buffer, size_t& stride ) noexcept override final;
static DWORD __stdcall threadProcStatic( void* lpParameter );
HRESULT run() noexcept;
HRESULT threadMain();
std::vector<MelChunk> pendingChunks;
int fftChunks = 0;
int fftThreads = 0;
std::vector<SpectrogramContext> melContextsWorkers;
CComAutoCriticalSection m_cs;
CONDITION_VARIABLE wakeMain, wakeBackground;
const int workerThreads;
enum struct eThreadStatus : uint8_t
{
NotStarted = 0,
Idle,
Working,
Completed,
Failed
};
eThreadStatus threadStatus;
bool shuttingDown = false;
CHandle threadHandle;
HRESULT threadPoolCallback( int ith ) noexcept override final;
public:
MelStreamerThread( const Filters& filters, ProfileCollection& profiler, const iAudioReader* reader, int countThreads );
~MelStreamerThread();
};
}
| 3,745
|
C++
|
.h
| 88
| 39.784091
| 130
| 0.772128
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,703
|
voiceActivityDetection.h
|
Const-me_Whisper/Whisper/Whisper/voiceActivityDetection.h
|
#pragma once
#include <complex>
#include <memory>
#include "audioConstants.h"
namespace Whisper
{
class VAD
{
using cplx = std::complex<float>;
std::unique_ptr<cplx[]> fft_signal;
struct Feature
{
float energy;
float F;
float SFM;
};
const Feature primThresh;
static Feature defaultPrimaryThresholds();
struct State
{
Feature currThresh;
Feature minFeature;
Feature curr;
uint32_t lastSpeech;
float silenceRun;
uint32_t i;
};
State state;
static inline void fft( cplx* buf, cplx* out, size_t n, size_t step );
void fft() const;
static float computeEnergy( const float* rsi );
static float computeDominant( const cplx* spectrum );
static float computreSpectralFlatnessMeasure( const cplx* spectrum );
public:
VAD();
// When no speech is detected, returns 0
// When speech is detected, returns sample position for the end of the speech
size_t detect( const float* rsi, size_t length );
void clear();
static constexpr uint32_t FFT_POINTS = 256;
static constexpr float FFT_STEP = (float)SAMPLE_RATE / (float)FFT_POINTS;
};
}
| 1,108
|
C++
|
.h
| 43
| 22.744186
| 79
| 0.727962
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,704
|
Vocabulary.h
|
Const-me_Whisper/Whisper/Whisper/Vocabulary.h
|
#pragma once
#include "../../ComLightLib/streams.h"
#include "../API/SpecialTokens.h"
#include "../Utils/MurmurHash3.h"
namespace Whisper
{
class Vocabulary
{
std::vector<const char*> tokens;
std::vector<char> stringData;
using THashMap = CAtlMap<const char*, int, StringPtrTraits>;
THashMap idFromToken;
void addExtra( int index, const char* format, int i );
void completeBuild();
public:
Vocabulary();
int n_vocab = 51864;
HRESULT load( ComLight::iReadStream* stm, int lengthInHeader );
using id = int;
id token_eot = 50256;
id token_sot = 50257;
id token_prev = 50360;
id token_solm = 50361; // ??
id token_not = 50362; // no timestamps
id token_beg = 50363;
// available tasks
static const id token_translate = 50358;
static const id token_transcribe = 50359;
bool is_multilingual() const
{
return n_vocab == 51865;
}
const char* string( int id ) const
{
if( id >= 0 && id < (int)tokens.size() )
return tokens[ id ];
return nullptr;
}
int findId( const char* token ) const;
int findId( const std::string& token ) const
{
return findId( token.c_str() );
}
size_t size() const
{
return tokens.size();
}
void getSpecialTokens( SpecialTokens& rdi ) const;
size_t getMemoryUse() const
{
return vectorMemoryUse( tokens ) + vectorMemoryUse( stringData );
}
HRESULT tokenize( const std::string& text, std::vector<id>& tokens ) const;
};
}
| 1,449
|
C++
|
.h
| 55
| 23.272727
| 77
| 0.68913
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,705
|
Languages.h
|
Const-me_Whisper/Whisper/Whisper/Languages.h
|
#pragma once
#include "../../ComLightLib/comLightCommon.h"
namespace Whisper
{
int lookupLanguageId( const char* code );
int lookupLanguageId( uint32_t key );
const char* lookupLanguageName( const char* code );
int COMLIGHTCALL getLanguageId( const char* lang );
}
| 271
|
C++
|
.h
| 9
| 28.444444
| 52
| 0.773077
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,706
|
iSpectrogram.h
|
Const-me_Whisper/Whisper/Whisper/iSpectrogram.h
|
#pragma once
#include "audioConstants.h"
namespace Whisper
{
struct alignas( 8 ) StereoSample
{
float left, right;
};
__interface iSpectrogram
{
// Make a buffer with length * N_MEL floats, starting at the specified offset
// An implementation of this interface may visualize the spectrogram, making pieces on demand
HRESULT makeBuffer( size_t offset, size_t length, const float** buffer, size_t& stride );
// Apparently, the length unit is 160 input samples = 10 milliseconds of audio
size_t getLength() const;
// If the source data is stereo, copy the specified slice of the data into the provided vector
HRESULT copyStereoPcm( size_t offset, size_t length, std::vector<StereoSample>& buffer ) const;
};
// RAII class to deal with iSpectrogram's makeBuffer method.
// Throws exceptions when things fail.
class MelBufferRaii
{
const float* pointer;
size_t stride;
public:
HRESULT make( iSpectrogram& mel, size_t off, size_t len )
{
return mel.makeBuffer( off, len, &pointer, stride );
}
const float* operator[]( size_t idx ) const
{
assert( idx < N_MEL );
return pointer + idx * stride;
}
const BYTE* bytePtr() const { return (const BYTE*)pointer; }
LONG strideBytes() const { return (LONG)stride * 4; }
};
}
| 1,274
|
C++
|
.h
| 38
| 30.842105
| 97
| 0.728234
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,707
|
mfUtils.h
|
Const-me_Whisper/Whisper/MF/mfUtils.h
|
#pragma once
#include <stdint.h>
#include <mfidl.h>
#include <mfobjects.h>
#include <mfreadwrite.h>
#include "../Whisper/audioConstants.h"
namespace Whisper
{
HRESULT createMediaType( bool stereo, IMFMediaType** pp );
HRESULT getStreamDuration( IMFSourceReader* reader, int64_t& duration );
HRESULT validateCurrentMediaType( IMFSourceReader* reader, uint32_t expectedChannels );
struct iAudioReader;
void setPreciseSamplesCount( const iAudioReader* ar, int64_t count );
}
| 480
|
C++
|
.h
| 14
| 32.714286
| 88
| 0.803456
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,708
|
AudioBuffer.h
|
Const-me_Whisper/Whisper/MF/AudioBuffer.h
|
#pragma once
#include <vector>
namespace Whisper
{
struct AudioBuffer
{
std::vector<float> mono;
std::vector<float> stereo;
void appendMono( const float* rsi, size_t countFloats );
void appendDownmixedStereo( const float* rsi, size_t countFloats );
void appendStereo( const float* rsi, size_t countFloats );
using pfnAppendSamples = void( AudioBuffer::* )( const float* rsi, size_t countFloats );
inline static pfnAppendSamples appendSamplesFunc( bool sourceMono, bool wantStereo )
{
if( sourceMono )
return &AudioBuffer::appendMono;
else if( !wantStereo )
return &AudioBuffer::appendDownmixedStereo;
else
return &AudioBuffer::appendStereo;
}
void clear()
{
mono.clear();
stereo.clear();
}
void swap( AudioBuffer& that )
{
mono.swap( that.mono );
stereo.swap( that.stereo );
}
void resize( size_t len )
{
assert( len <= mono.size() );
mono.resize( len );
if( !stereo.empty() )
stereo.resize( len * 2 );
}
};
}
| 1,001
|
C++
|
.h
| 40
| 21.75
| 90
| 0.696335
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,709
|
loadAudioFile.h
|
Const-me_Whisper/Whisper/MF/loadAudioFile.h
|
#pragma once
#include "../API/iMediaFoundation.cl.h"
namespace Whisper
{
HRESULT COMLIGHTCALL loadAudioFile( LPCTSTR path, bool stereo, iAudioBuffer** pp );
}
| 160
|
C++
|
.h
| 6
| 25.5
| 84
| 0.792208
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,710
|
mfStartup.h
|
Const-me_Whisper/Whisper/MF/mfStartup.h
|
#pragma once
namespace Whisper
{
class MfStartupRaii
{
uint8_t successFlags = 0;
public:
MfStartupRaii() = default;
~MfStartupRaii();
MfStartupRaii( const MfStartupRaii& ) = delete;
HRESULT startup();
};
}
| 221
|
C++
|
.h
| 13
| 14.846154
| 49
| 0.73913
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,711
|
PcmReader.h
|
Const-me_Whisper/Whisper/MF/PcmReader.h
|
#pragma once
#include "../Whisper/audioConstants.h"
#include <mfidl.h>
#include <mfreadwrite.h>
#include "AudioBuffer.h"
#include "../API/iMediaFoundation.cl.h"
namespace Whisper
{
// PCM buffer with 10 milliseconds of single-channel audio
struct PcmMonoChunk
{
std::array<float, FFT_STEP> mono;
};
// PCM buffer with 10 milliseconds of interleaved stereo
struct PcmStereoChunk
{
std::array<float, FFT_STEP * 2> stereo;
};
__interface iSampleHandler;
constexpr HRESULT E_EOF = HRESULT_FROM_WIN32( ERROR_HANDLE_EOF );
// Utility class which reads chunks of FFT_STEP FP32 PCM samples from the MF source reader
// The class always delivers mono chunks, and can optionally deliver stereo in a separate buffer.
class PcmReader
{
// A small intermediate buffer with PCM data for complete media foundation samples
AudioBuffer pcm;
// Index of the first unconsumed sample in the pcm buffer
size_t bufferReadOffset = 0;
// Utility object to abstract away mono versus stereo shenanigans
const iSampleHandler* sampleHandler;
// The underlying MF source reader which delivers audio data
CComPtr<IMFSourceReader> reader;
// True after we consumed all available media samples from the reader
bool m_readerEndOfFile = false;
// True if this object delivers stereo samples
bool m_stereoOutput = false;
// The count of chunks we expect to get from the reader
size_t m_length = 0;
// Read next sample from the reader, store in the PCM buffer in this class
HRESULT readNextSample();
public:
PcmReader( const iAudioReader* reader );
// Count of chunks in the MEL spectrogram.
// The PCM audio is generally slightly longer than that, due to the incomplete last chunk.
size_t getLength() const noexcept
{
return m_length;
}
// True when the stereo flag passed to constructor, and the audio stream actually has 2 or more audio channels
bool outputsStereo() const { return m_stereoOutput; }
// Load another 10ms chunk from the stream
// For the last chunk in the stream, the output buffers are padded with zeros
HRESULT readChunk( PcmMonoChunk& mono, PcmStereoChunk* stereo );
};
}
| 2,143
|
C++
|
.h
| 55
| 36.418182
| 112
| 0.766346
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,712
|
AudioCapture.h
|
Const-me_Whisper/Whisper/MF/AudioCapture.h
|
#pragma once
#include "../API/MfStructs.h"
namespace Whisper
{
struct iAudioCapture;
struct iMediaFoundation;
HRESULT __stdcall captureDeviceList( pfnFoundCaptureDevices pfn, void* pv );
HRESULT __stdcall captureOpen( iMediaFoundation* owner, const wchar_t* endpoint, const sCaptureParams& captureParams, iAudioCapture** pp ) noexcept;
}
| 344
|
C++
|
.h
| 9
| 36.555556
| 149
| 0.807808
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,713
|
iMediaFoundation.h
|
Const-me_Whisper/Whisper/API/iMediaFoundation.h
|
#pragma once
#include <stdint.h>
#include "MfStructs.h"
struct IMFSourceReader;
namespace Whisper
{
__interface __declspec( novtable, uuid( "013583aa-c9eb-42bc-83db-633c2c317051" ) ) iAudioBuffer : public IUnknown
{
uint32_t __stdcall countSamples() const;
const float* __stdcall getPcmMono() const;
const float* __stdcall getPcmStereo() const;
HRESULT __stdcall getTime( int64_t& rdi ) const;
};
__interface __declspec( novtable, uuid( "35b988da-04a6-476a-a193-d8891d5dc390" ) ) iAudioReader : public IUnknown
{
HRESULT __stdcall getDuration( int64_t& rdi ) const;
HRESULT __stdcall getReader( IMFSourceReader** pp ) const;
HRESULT __stdcall requestedStereo() const;
};
__interface __declspec( novtable, uuid( "747752c2-d9fd-40df-8847-583c781bf013" ) ) iAudioCapture : public IUnknown
{
HRESULT __stdcall getReader( IMFSourceReader** pp ) const;
const sCaptureParams& __stdcall getParams() const;
};
__interface __declspec( novtable, uuid( "fb9763a5-d77d-4b6e-aff8-f494813cebd8" ) ) iMediaFoundation : public IUnknown
{
HRESULT __stdcall loadAudioFile( LPCTSTR path, bool stereo, iAudioBuffer** pp ) const;
HRESULT __stdcall openAudioFile( LPCTSTR path, bool stereo, iAudioReader** pp );
HRESULT __stdcall loadAudioFileData( const void* data, uint64_t size, bool stereo, iAudioReader** pp );
HRESULT __stdcall listCaptureDevices( pfnFoundCaptureDevices pfn, void* pv );
HRESULT __stdcall openCaptureDevice( LPCTSTR endpoint, const sCaptureParams& captureParams, iAudioCapture** pp );
};
HRESULT __stdcall initMediaFoundation( iMediaFoundation** pp );
}
| 1,600
|
C++
|
.h
| 34
| 44.705882
| 118
| 0.756566
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,714
|
sFullParams.h
|
Const-me_Whisper/Whisper/API/sFullParams.h
|
#pragma once
#include <stdint.h>
#include <assert.h>
namespace Whisper
{
// Available sampling strategies
enum struct eSamplingStrategy : int
{
// Always select the most probable token
Greedy,
// TODO: not implemented yet!
BeamSearch,
};
using pfnNewSegment = HRESULT( __cdecl* )( iContext* ctx, uint32_t n_new, void* user_data ) noexcept;
// Return S_OK to proceed, or S_FALSE to stop the process and return S_OK from runFull / runStreamed method
using pfnEncoderBegin = HRESULT( __cdecl* )( iContext* ctx, void* user_data ) noexcept;
enum struct eFullParamsFlags : uint32_t
{
Translate = 1,
NoContext = 2,
SingleSegment = 4,
PrintSpecial = 8,
PrintProgress = 0x10,
PrintRealtime = 0x20,
PrintTimestamps = 0x40,
// Experimental
TokenTimestamps = 0x100,
SpeedupAudio = 0x200,
};
inline eFullParamsFlags operator | ( eFullParamsFlags a, eFullParamsFlags b )
{
return (eFullParamsFlags)( (uint32_t)a | (uint32_t)b );
}
inline void operator |= ( eFullParamsFlags& a, eFullParamsFlags b )
{
a = a | b;
}
struct sFullParams
{
eSamplingStrategy strategy;
// Count of CPU threads
int cpuThreads;
int n_max_text_ctx;
int offset_ms; // start offset in ms
int duration_ms; // audio duration to process in ms
eFullParamsFlags flags;
uint32_t language;
// [EXPERIMENTAL] token-level timestamps
float thold_pt; // timestamp token probability threshold (~0.01)
float thold_ptsum; // timestamp token sum probability threshold (~0.01)
int max_len; // max segment length in characters
int max_tokens; // max tokens per segment (0 = no limit)
struct
{
int n_past;
} greedy;
struct
{
int n_past;
int beam_width;
int n_best;
} beam_search;
// [EXPERIMENTAL] speed-up techniques
int audio_ctx; // overwrite the audio context size (0 = use default)
// tokens to provide the whisper model as initial prompt
// these are prepended to any existing text context from a previous call
const whisper_token* prompt_tokens;
int prompt_n_tokens;
pfnNewSegment new_segment_callback;
void* new_segment_callback_user_data;
pfnEncoderBegin encoder_begin_callback;
void* encoder_begin_callback_user_data;
// Couple utility methods, they workaround the lack of bit fields in C++
inline bool flag( eFullParamsFlags f ) const
{
return 0 != ( (uint32_t)flags & (uint32_t)f );
}
inline void resetFlag( eFullParamsFlags bit )
{
uint32_t f = (uint32_t)flags;
f &= ~(uint32_t)bit;
flags = (eFullParamsFlags)f;
}
inline void setFlag( eFullParamsFlags bit, bool set = true )
{
uint32_t f = (uint32_t)flags;
if( set )
f |= (uint32_t)bit;
else
f &= ~(uint32_t)bit;
flags = (eFullParamsFlags)f;
}
};
struct sSegmentTime
{
int64_t begin, end;
};
inline uint32_t makeLanguageKey( const char* code )
{
assert( strlen( code ) <= 4 );
uint32_t res = 0;
uint32_t shift = 0;
for( size_t i = 0; i < 4; i++, code++, shift += 8 )
{
const char c = *code;
if( c == '\0' )
return res;
uint32_t u32 = (uint8_t)c;
u32 = u32 << shift;
res |= u32;
}
return res;
}
using pfnReportProgress = HRESULT( __stdcall* )( double val, iContext* ctx, void* pv ) noexcept;
struct sProgressSink
{
pfnReportProgress pfn;
void* pv;
};
}
| 3,354
|
C++
|
.h
| 120
| 24.933333
| 108
| 0.686061
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,715
|
sLoadModelCallbacks.h
|
Const-me_Whisper/Whisper/API/sLoadModelCallbacks.h
|
#pragma once
namespace Whisper
{
using pfnLoadProgress = HRESULT( __stdcall* )( double val, void* pv ) noexcept;
// Return S_OK to continue, or S_FALSE to fail with "The operation was canceled by the user" status code
using pfnCancel = HRESULT( __stdcall* )( void* pv ) noexcept;
struct sLoadModelCallbacks
{
pfnLoadProgress progress;
pfnCancel cancel;
void* pv;
};
}
| 382
|
C++
|
.h
| 13
| 27.307692
| 105
| 0.743869
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,716
|
SpecialTokens.h
|
Const-me_Whisper/Whisper/API/SpecialTokens.h
|
#pragma once
namespace Whisper
{
struct SpecialTokens
{
// The end of a transcription, token_eot
int TranscriptionEnd;
// Start of a transcription, token_sot
int TranscriptionStart;
// Represents the previous word in the transcription. It is used to help the model predict the current word based on the context of the words that came before it.
int PreviousWord; // token_prev
// Start of a sentence
int SentenceStart; // token_solm
//Represents the word "not" in the transcription
int Not; // token_not
//New transcription
int TranscriptionBegin; // token_beg
// token_translate
int TaskTranslate;
// token_transcribe
int TaskTranscribe;
};
}
| 690
|
C++
|
.h
| 23
| 27.434783
| 164
| 0.746246
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,717
|
iTranscribeResult.cl.h
|
Const-me_Whisper/Whisper/API/iTranscribeResult.cl.h
|
#pragma once
#include "TranscribeStructs.h"
#include "../../ComLightLib/comLightCommon.h"
namespace Whisper
{
struct iTranscribeResult : public ComLight::IUnknown
{
DEFINE_INTERFACE_ID( "{2871a73f-5ce3-48f8-8779-6582ee11935e}" );
virtual HRESULT COMLIGHTCALL getSize( sTranscribeLength& rdi ) const = 0;
virtual const sSegment* COMLIGHTCALL getSegments() const = 0;
virtual const sToken* COMLIGHTCALL getTokens() const = 0;
};
}
| 441
|
C++
|
.h
| 13
| 32
| 75
| 0.775176
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,718
|
TranscribeStructs.h
|
Const-me_Whisper/Whisper/API/TranscribeStructs.h
|
#pragma once
#include <stdint.h>
#include <assert.h>
namespace Whisper
{
// Timespan structure decomposed into fields
struct sTimeSpanFields
{
uint32_t days;
uint8_t hours, minutes, seconds;
uint32_t ticks;
sTimeSpanFields( uint64_t tt )
{
ticks = (uint32_t)( tt % 10'000'000 );
tt /= 10'000'000;
seconds = (uint8_t)( tt % 60 );
tt /= 60;
minutes = (uint8_t)( tt % 60 );
tt /= 60;
hours = (uint8_t)( tt % 24 );
tt /= 24;
days = (uint32_t)tt;
}
};
// C++ equivalent of System.Timespan C# structure
struct sTimeSpan
{
// The value is expressed in 100-nanoseconds ticks: compatible with System.Timespan, FILETIME, and many other things
uint64_t ticks;
operator sTimeSpanFields() const
{
return sTimeSpanFields{ ticks };
}
void operator=( uint64_t tt )
{
ticks = tt;
}
void operator=( int64_t tt )
{
assert( tt >= 0 );
ticks = (uint64_t)tt;
}
};
// Start and end times of the segment or token, expressed in 100-nanosecond ticks
struct sTimeInterval
{
sTimeSpan begin, end;
};
// Segment data
struct sSegment
{
// Segment text, null-terminated, and probably UTF-8 encoded
const char* text;
// Start and end times of the segment
sTimeInterval time;
// These two integers define the slice of the tokens in this segment, in the array returned by iTranscribeResult.getTokens method
uint32_t firstToken, countTokens;
};
enum eTokenFlags : uint32_t
{
None = 0,
Special = 1,
};
inline bool operator &( eTokenFlags a, eTokenFlags b )
{
return 0 != ( (uint32_t)a & (uint32_t)b );
}
// Token data
struct sToken
{
// Token text, null-terminated, and usually UTF-8 encoded.
// I think for Chinese language the models sometimes outputs invalid UTF8 strings here, Unicode code points can be split between adjacent tokens in the same segment
// More info: https://github.com/ggerganov/whisper.cpp/issues/399
const char* text;
// Start and end times of the token
sTimeInterval time;
// Probability of the token
float probability;
// Probability of the timestamp token
float probabilityTimestamp;
// Sum of probabilities of all timestamp tokens
float ptsum;
// Voice length of the token
float vlen;
// Token id
int id;
eTokenFlags flags;
};
struct sTranscribeLength
{
uint32_t countSegments, countTokens;
};
enum struct eResultFlags : uint32_t
{
None = 0,
// Return individual tokens in addition to the segments
Tokens = 1,
// Return timestamps
Timestamps = 2,
// Create a new COM object for the results.
// Without this flag, the context returns a pointer to the COM object stored in the context.
// The content of that object is replaced every time you call iContext.getResults method
NewObject = 0x100,
};
inline eResultFlags operator |( eResultFlags a, eResultFlags b )
{
return (eResultFlags)( (uint32_t)a | (uint32_t)b );
}
inline bool operator &( eResultFlags a, eResultFlags b )
{
return 0 != ( (uint32_t)a & (uint32_t)b );
}
// Output value for iContext.detectSpeaker method
enum struct eSpeakerChannel : uint8_t
{
Unsure = 0,
Left = 1,
Right = 2,
NoStereoData = 0xFF,
};
}
| 3,175
|
C++
|
.h
| 121
| 23.471074
| 166
| 0.709306
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,719
|
iTranscribeResult.h
|
Const-me_Whisper/Whisper/API/iTranscribeResult.h
|
#pragma once
#include "TranscribeStructs.h"
namespace Whisper
{
__interface __declspec( novtable, uuid( "2871a73f-5ce3-48f8-8779-6582ee11935e" ) ) iTranscribeResult : public IUnknown
{
HRESULT __stdcall getSize( sTranscribeLength& rdi ) const;
const sSegment* __stdcall getSegments() const;
const sToken* __stdcall getTokens() const;
};
}
| 348
|
C++
|
.h
| 11
| 29.818182
| 119
| 0.762611
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,720
|
iContext.h
|
Const-me_Whisper/Whisper/API/iContext.h
|
#pragma once
#include "iTranscribeResult.h"
#include "SpecialTokens.h"
#include "loggerApi.h"
#include "sLanguageList.h"
#include "sLoadModelCallbacks.h"
#include "sModelSetup.h"
namespace Whisper
{
__interface iModel;
__interface iAudioBuffer;
__interface iAudioReader;
__interface iAudioCapture;
struct sCaptureCallbacks;
struct sFullParams;
enum struct eModelImplementation : uint32_t;
enum struct eSamplingStrategy : int;
using whisper_token = int;
struct sProgressSink;
__interface __declspec( novtable, uuid( "b9956374-3b18-4943-90f2-2ab18a404537" ) ) iContext : public IUnknown
{
// Run the entire model: PCM -> log mel spectrogram -> encoder -> decoder -> text
// Uses the specified decoding strategy to obtain the text.
HRESULT __stdcall runFull( const sFullParams& params, const iAudioBuffer* buffer );
HRESULT __stdcall runStreamed( const sFullParams& params, const sProgressSink& progress, const iAudioReader* reader );
HRESULT __stdcall runCapture( const sFullParams& params, const sCaptureCallbacks& callbacks, const iAudioCapture* reader );
HRESULT __stdcall getResults( eResultFlags flags, iTranscribeResult** pp ) const;
// Try to detect speaker by comparing channels of the stereo PCM data
HRESULT __stdcall detectSpeaker( const sTimeInterval& time, eSpeakerChannel& result ) const;
HRESULT __stdcall getModel( iModel** pp );
HRESULT __stdcall fullDefaultParams( eSamplingStrategy strategy, sFullParams* rdi );
// Performance information
HRESULT __stdcall timingsPrint();
HRESULT __stdcall timingsReset();
};
__interface __declspec( novtable, uuid( "abefb4c9-e8d8-46a3-8747-5afbadef1adb" ) ) iModel : public IUnknown
{
HRESULT __stdcall createContext( iContext** pp );
HRESULT __stdcall tokenize( const char* text, pfnDecodedTokens pfn, void* pv );
HRESULT __stdcall isMultilingual();
HRESULT __stdcall getSpecialTokens( SpecialTokens& rdi );
// Token Id -> String
const char* __stdcall stringFromToken( whisper_token token );
HRESULT __stdcall clone( iModel** rdi );
};
HRESULT __stdcall setupLogger( const sLoggerSetup& setup );
HRESULT __stdcall loadModel( const wchar_t* path, const sModelSetup& setup, const sLoadModelCallbacks* callbacks, iModel** pp );
uint32_t __stdcall findLanguageKeyW( const wchar_t* lang );
uint32_t __stdcall findLanguageKeyA( const char* lang );
HRESULT __stdcall getSupportedLanguages( sLanguageList& rdi );
HRESULT __stdcall listGPUs( pfnListAdapters pfn, void* pv );
}
#include "sFullParams.h"
| 2,527
|
C++
|
.h
| 53
| 45.150943
| 129
| 0.769857
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,721
|
iContext.cl.h
|
Const-me_Whisper/Whisper/API/iContext.cl.h
|
#pragma once
#include "../../ComLightLib/comLightCommon.h"
#include "iTranscribeResult.cl.h"
#include "SpecialTokens.h"
#include "loggerApi.h"
#include "sLanguageList.h"
#include "sLoadModelCallbacks.h"
#include "sModelSetup.h"
namespace Whisper
{
struct iModel;
struct iAudioBuffer;
struct iAudioReader;
struct iAudioCapture;
struct sCaptureCallbacks;
struct sFullParams;
enum struct eModelImplementation : uint32_t;
enum struct eSamplingStrategy : int;
using whisper_token = int;
struct sProgressSink;
struct DECLSPEC_NOVTABLE iContext : public ComLight::IUnknown
{
DEFINE_INTERFACE_ID( "{b9956374-3b18-4943-90f2-2ab18a404537}" );
// Run the entire model: PCM -> log mel spectrogram -> encoder -> decoder -> text
// Uses the specified decoding strategy to obtain the text.
virtual HRESULT COMLIGHTCALL runFull( const sFullParams& params, const iAudioBuffer* buffer ) = 0;
virtual HRESULT COMLIGHTCALL runStreamed( const sFullParams& params, const sProgressSink& progress, const iAudioReader* reader ) = 0;
virtual HRESULT COMLIGHTCALL runCapture( const sFullParams& params, const sCaptureCallbacks& callbacks, const iAudioCapture* reader ) = 0;
virtual HRESULT COMLIGHTCALL getResults( eResultFlags flags, iTranscribeResult** pp ) const = 0;
// Try to detect speaker by comparing channels of the stereo PCM data
virtual HRESULT COMLIGHTCALL detectSpeaker( const sTimeInterval& time, eSpeakerChannel& result ) const = 0;
virtual HRESULT COMLIGHTCALL getModel( iModel** pp ) = 0;
virtual HRESULT COMLIGHTCALL fullDefaultParams( eSamplingStrategy strategy, sFullParams* rdi ) = 0;
// Performance information
virtual HRESULT COMLIGHTCALL timingsPrint() = 0;
virtual HRESULT COMLIGHTCALL timingsReset() = 0;
};
struct DECLSPEC_NOVTABLE iModel : public ComLight::IUnknown
{
DEFINE_INTERFACE_ID( "{abefb4c9-e8d8-46a3-8747-5afbadef1adb}" );
virtual HRESULT COMLIGHTCALL createContext( iContext** pp ) = 0;
virtual HRESULT COMLIGHTCALL tokenize( const char* text, pfnDecodedTokens pfn, void* pv ) = 0;
virtual HRESULT COMLIGHTCALL isMultilingual() = 0;
virtual HRESULT COMLIGHTCALL getSpecialTokens( SpecialTokens& rdi ) = 0;
// Token Id -> String
virtual const char* COMLIGHTCALL stringFromToken( whisper_token token ) = 0;
virtual HRESULT COMLIGHTCALL clone( iModel** rdi ) = 0;
};
HRESULT COMLIGHTCALL setupLogger( const sLoggerSetup& setup );
HRESULT COMLIGHTCALL loadModel( const wchar_t* path, const sModelSetup& setup, const sLoadModelCallbacks* callbacks, iModel** pp );
uint32_t COMLIGHTCALL findLanguageKeyW( const wchar_t* lang );
uint32_t COMLIGHTCALL findLanguageKeyA( const char* lang );
HRESULT COMLIGHTCALL getSupportedLanguages( sLanguageList& rdi );
HRESULT COMLIGHTCALL listGPUs( pfnListAdapters pfn, void* pv );
}
#include "sFullParams.h"
| 2,837
|
C++
|
.h
| 56
| 48.142857
| 140
| 0.787111
|
Const-me/Whisper
| 8,145
| 691
| 142
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.